github.com/inge4pres/terraform@v0.7.5-0.20160930053151-bd083f84f376/command/state_meta.go (about)

     1  package command
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"time"
     7  
     8  	"github.com/hashicorp/terraform/state"
     9  	"github.com/hashicorp/terraform/terraform"
    10  )
    11  
    12  // StateMeta is the meta struct that should be embedded in state subcommands.
    13  type StateMeta struct{}
    14  
    15  // State returns the state for this meta. This is different then Meta.State
    16  // in the way that backups are done. This configures backups to be timestamped
    17  // rather than just the original state path plus a backup path.
    18  func (c *StateMeta) State(m *Meta) (state.State, error) {
    19  	// Disable backups since we wrap it manually below
    20  	m.backupPath = "-"
    21  
    22  	// Get the state (shouldn't be wrapped in a backup)
    23  	s, err := m.State()
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  
    28  	// Determine the backup path. stateOutPath is set to the resulting
    29  	// file where state is written (cached in the case of remote state)
    30  	backupPath := fmt.Sprintf(
    31  		"%s.%d.%s",
    32  		m.stateOutPath,
    33  		time.Now().UTC().Unix(),
    34  		DefaultBackupExtension)
    35  
    36  	// Wrap it for backups
    37  	s = &state.BackupState{
    38  		Real: s,
    39  		Path: backupPath,
    40  	}
    41  
    42  	return s, nil
    43  }
    44  
    45  // filterInstance filters a single instance out of filter results.
    46  func (c *StateMeta) filterInstance(rs []*terraform.StateFilterResult) (*terraform.StateFilterResult, error) {
    47  	var result *terraform.StateFilterResult
    48  	for _, r := range rs {
    49  		if _, ok := r.Value.(*terraform.InstanceState); !ok {
    50  			continue
    51  		}
    52  
    53  		if result != nil {
    54  			return nil, errors.New(errStateMultiple)
    55  		}
    56  
    57  		result = r
    58  	}
    59  
    60  	return result, nil
    61  }
    62  
    63  const errStateMultiple = `Multiple instances found for the given pattern!
    64  
    65  This command requires that the pattern match exactly one instance
    66  of a resource. To view the matched instances, use "terraform state list".
    67  Please modify the pattern to match only a single instance.`