github.com/miquella/terraform@v0.6.17-0.20160517195040-40db82f25ec0/command/meta.go (about)

     1  package command
     2  
     3  import (
     4  	"bufio"
     5  	"flag"
     6  	"fmt"
     7  	"io"
     8  	"os"
     9  	"path/filepath"
    10  	"strconv"
    11  
    12  	"github.com/hashicorp/go-getter"
    13  	"github.com/hashicorp/terraform/config/module"
    14  	"github.com/hashicorp/terraform/state"
    15  	"github.com/hashicorp/terraform/terraform"
    16  	"github.com/mitchellh/cli"
    17  	"github.com/mitchellh/colorstring"
    18  )
    19  
    20  // Meta are the meta-options that are available on all or most commands.
    21  type Meta struct {
    22  	Color       bool
    23  	ContextOpts *terraform.ContextOpts
    24  	Ui          cli.Ui
    25  
    26  	// State read when calling `Context`. This is available after calling
    27  	// `Context`.
    28  	state       state.State
    29  	stateResult *StateResult
    30  
    31  	// This can be set by the command itself to provide extra hooks.
    32  	extraHooks []terraform.Hook
    33  
    34  	// This can be set by tests to change some directories
    35  	dataDir string
    36  
    37  	// Variables for the context (private)
    38  	autoKey       string
    39  	autoVariables map[string]string
    40  	input         bool
    41  	variables     map[string]string
    42  
    43  	// Targets for this context (private)
    44  	targets []string
    45  
    46  	color bool
    47  	oldUi cli.Ui
    48  
    49  	// The fields below are expected to be set by the command via
    50  	// command line flags. See the Apply command for an example.
    51  	//
    52  	// statePath is the path to the state file. If this is empty, then
    53  	// no state will be loaded. It is also okay for this to be a path to
    54  	// a file that doesn't exist; it is assumed that this means that there
    55  	// is simply no state.
    56  	//
    57  	// stateOutPath is used to override the output path for the state.
    58  	// If not provided, the StatePath is used causing the old state to
    59  	// be overriden.
    60  	//
    61  	// backupPath is used to backup the state file before writing a modified
    62  	// version. It defaults to stateOutPath + DefaultBackupExtension
    63  	//
    64  	// parallelism is used to control the number of concurrent operations
    65  	// allowed when walking the graph
    66  	statePath    string
    67  	stateOutPath string
    68  	backupPath   string
    69  	parallelism  int
    70  }
    71  
    72  // initStatePaths is used to initialize the default values for
    73  // statePath, stateOutPath, and backupPath
    74  func (m *Meta) initStatePaths() {
    75  	if m.statePath == "" {
    76  		m.statePath = DefaultStateFilename
    77  	}
    78  	if m.stateOutPath == "" {
    79  		m.stateOutPath = m.statePath
    80  	}
    81  	if m.backupPath == "" {
    82  		m.backupPath = m.stateOutPath + DefaultBackupExtension
    83  	}
    84  }
    85  
    86  // StateOutPath returns the true output path for the state file
    87  func (m *Meta) StateOutPath() string {
    88  	return m.stateOutPath
    89  }
    90  
    91  // Colorize returns the colorization structure for a command.
    92  func (m *Meta) Colorize() *colorstring.Colorize {
    93  	return &colorstring.Colorize{
    94  		Colors:  colorstring.DefaultColors,
    95  		Disable: !m.color,
    96  		Reset:   true,
    97  	}
    98  }
    99  
   100  // Context returns a Terraform Context taking into account the context
   101  // options used to initialize this meta configuration.
   102  func (m *Meta) Context(copts contextOpts) (*terraform.Context, bool, error) {
   103  	opts := m.contextOpts()
   104  
   105  	// First try to just read the plan directly from the path given.
   106  	f, err := os.Open(copts.Path)
   107  	if err == nil {
   108  		plan, err := terraform.ReadPlan(f)
   109  		f.Close()
   110  		if err == nil {
   111  			// Setup our state
   112  			state, statePath, err := StateFromPlan(m.statePath, plan)
   113  			if err != nil {
   114  				return nil, false, fmt.Errorf("Error loading plan: %s", err)
   115  			}
   116  
   117  			// Set our state
   118  			m.state = state
   119  			m.stateOutPath = statePath
   120  
   121  			if len(m.variables) > 0 {
   122  				return nil, false, fmt.Errorf(
   123  					"You can't set variables with the '-var' or '-var-file' flag\n" +
   124  						"when you're applying a plan file. The variables used when\n" +
   125  						"the plan was created will be used. If you wish to use different\n" +
   126  						"variable values, create a new plan file.")
   127  			}
   128  
   129  			ctx, err := plan.Context(opts)
   130  			return ctx, true, err
   131  		}
   132  	}
   133  
   134  	// Load the statePath if not given
   135  	if copts.StatePath != "" {
   136  		m.statePath = copts.StatePath
   137  	}
   138  
   139  	// Tell the context if we're in a destroy plan / apply
   140  	opts.Destroy = copts.Destroy
   141  
   142  	// Store the loaded state
   143  	state, err := m.State()
   144  	if err != nil {
   145  		return nil, false, err
   146  	}
   147  
   148  	// Load the root module
   149  	var mod *module.Tree
   150  	if copts.Path != "" {
   151  		mod, err = module.NewTreeModule("", copts.Path)
   152  		if err != nil {
   153  			return nil, false, fmt.Errorf("Error loading config: %s", err)
   154  		}
   155  	} else {
   156  		mod = module.NewEmptyTree()
   157  	}
   158  
   159  	err = mod.Load(m.moduleStorage(m.DataDir()), copts.GetMode)
   160  	if err != nil {
   161  		return nil, false, fmt.Errorf("Error downloading modules: %s", err)
   162  	}
   163  
   164  	opts.Module = mod
   165  	opts.Parallelism = copts.Parallelism
   166  	opts.State = state.State()
   167  	ctx, err := terraform.NewContext(opts)
   168  	return ctx, false, err
   169  }
   170  
   171  // DataDir returns the directory where local data will be stored.
   172  func (m *Meta) DataDir() string {
   173  	dataDir := DefaultDataDirectory
   174  	if m.dataDir != "" {
   175  		dataDir = m.dataDir
   176  	}
   177  
   178  	return dataDir
   179  }
   180  
   181  const (
   182  	// InputModeEnvVar is the environment variable that, if set to "false" or
   183  	// "0", causes terraform commands to behave as if the `-input=false` flag was
   184  	// specified.
   185  	InputModeEnvVar = "TF_INPUT"
   186  )
   187  
   188  // InputMode returns the type of input we should ask for in the form of
   189  // terraform.InputMode which is passed directly to Context.Input.
   190  func (m *Meta) InputMode() terraform.InputMode {
   191  	if test || !m.input {
   192  		return 0
   193  	}
   194  
   195  	if envVar := os.Getenv(InputModeEnvVar); envVar != "" {
   196  		if v, err := strconv.ParseBool(envVar); err == nil {
   197  			if !v {
   198  				return 0
   199  			}
   200  		}
   201  	}
   202  
   203  	var mode terraform.InputMode
   204  	mode |= terraform.InputModeProvider
   205  	if len(m.variables) == 0 {
   206  		mode |= terraform.InputModeVar
   207  		mode |= terraform.InputModeVarUnset
   208  	}
   209  
   210  	return mode
   211  }
   212  
   213  // State returns the state for this meta.
   214  func (m *Meta) State() (state.State, error) {
   215  	if m.state != nil {
   216  		return m.state, nil
   217  	}
   218  
   219  	result, err := State(m.StateOpts())
   220  	if err != nil {
   221  		return nil, err
   222  	}
   223  
   224  	m.state = result.State
   225  	m.stateOutPath = result.StatePath
   226  	m.stateResult = result
   227  	return m.state, nil
   228  }
   229  
   230  // StateRaw is used to setup the state manually.
   231  func (m *Meta) StateRaw(opts *StateOpts) (*StateResult, error) {
   232  	result, err := State(opts)
   233  	if err != nil {
   234  		return nil, err
   235  	}
   236  
   237  	m.state = result.State
   238  	m.stateOutPath = result.StatePath
   239  	m.stateResult = result
   240  	return result, nil
   241  }
   242  
   243  // StateOpts returns the default state options
   244  func (m *Meta) StateOpts() *StateOpts {
   245  	localPath := m.statePath
   246  	if localPath == "" {
   247  		localPath = DefaultStateFilename
   248  	}
   249  	remotePath := filepath.Join(m.DataDir(), DefaultStateFilename)
   250  
   251  	return &StateOpts{
   252  		LocalPath:     localPath,
   253  		LocalPathOut:  m.stateOutPath,
   254  		RemotePath:    remotePath,
   255  		RemoteRefresh: true,
   256  		BackupPath:    m.backupPath,
   257  	}
   258  }
   259  
   260  // UIInput returns a UIInput object to be used for asking for input.
   261  func (m *Meta) UIInput() terraform.UIInput {
   262  	return &UIInput{
   263  		Colorize: m.Colorize(),
   264  	}
   265  }
   266  
   267  // PersistState is used to write out the state, handling backup of
   268  // the existing state file and respecting path configurations.
   269  func (m *Meta) PersistState(s *terraform.State) error {
   270  	if err := m.state.WriteState(s); err != nil {
   271  		return err
   272  	}
   273  
   274  	return m.state.PersistState()
   275  }
   276  
   277  // Input returns true if we should ask for input for context.
   278  func (m *Meta) Input() bool {
   279  	return !test && m.input && len(m.variables) == 0
   280  }
   281  
   282  // contextOpts returns the options to use to initialize a Terraform
   283  // context with the settings from this Meta.
   284  func (m *Meta) contextOpts() *terraform.ContextOpts {
   285  	var opts terraform.ContextOpts = *m.ContextOpts
   286  	opts.Hooks = make(
   287  		[]terraform.Hook,
   288  		len(m.ContextOpts.Hooks)+len(m.extraHooks)+1)
   289  	opts.Hooks[0] = m.uiHook()
   290  	copy(opts.Hooks[1:], m.ContextOpts.Hooks)
   291  	copy(opts.Hooks[len(m.ContextOpts.Hooks)+1:], m.extraHooks)
   292  
   293  	vs := make(map[string]string)
   294  	for k, v := range opts.Variables {
   295  		vs[k] = v
   296  	}
   297  	for k, v := range m.autoVariables {
   298  		vs[k] = v
   299  	}
   300  	for k, v := range m.variables {
   301  		vs[k] = v
   302  	}
   303  	opts.Variables = vs
   304  	opts.Targets = m.targets
   305  	opts.UIInput = m.UIInput()
   306  
   307  	return &opts
   308  }
   309  
   310  // flags adds the meta flags to the given FlagSet.
   311  func (m *Meta) flagSet(n string) *flag.FlagSet {
   312  	f := flag.NewFlagSet(n, flag.ContinueOnError)
   313  	f.BoolVar(&m.input, "input", true, "input")
   314  	f.Var((*FlagKV)(&m.variables), "var", "variables")
   315  	f.Var((*FlagKVFile)(&m.variables), "var-file", "variable file")
   316  	f.Var((*FlagStringSlice)(&m.targets), "target", "resource to target")
   317  
   318  	if m.autoKey != "" {
   319  		f.Var((*FlagKVFile)(&m.autoVariables), m.autoKey, "variable file")
   320  	}
   321  
   322  	// Create an io.Writer that writes to our Ui properly for errors.
   323  	// This is kind of a hack, but it does the job. Basically: create
   324  	// a pipe, use a scanner to break it into lines, and output each line
   325  	// to the UI. Do this forever.
   326  	errR, errW := io.Pipe()
   327  	errScanner := bufio.NewScanner(errR)
   328  	go func() {
   329  		for errScanner.Scan() {
   330  			m.Ui.Error(errScanner.Text())
   331  		}
   332  	}()
   333  	f.SetOutput(errW)
   334  
   335  	// Set the default Usage to empty
   336  	f.Usage = func() {}
   337  
   338  	return f
   339  }
   340  
   341  // moduleStorage returns the module.Storage implementation used to store
   342  // modules for commands.
   343  func (m *Meta) moduleStorage(root string) getter.Storage {
   344  	return &uiModuleStorage{
   345  		Storage: &getter.FolderStorage{
   346  			StorageDir: filepath.Join(root, "modules"),
   347  		},
   348  		Ui: m.Ui,
   349  	}
   350  }
   351  
   352  // process will process the meta-parameters out of the arguments. This
   353  // will potentially modify the args in-place. It will return the resulting
   354  // slice.
   355  //
   356  // vars says whether or not we support variables.
   357  func (m *Meta) process(args []string, vars bool) []string {
   358  	// We do this so that we retain the ability to technically call
   359  	// process multiple times, even if we have no plans to do so
   360  	if m.oldUi != nil {
   361  		m.Ui = m.oldUi
   362  	}
   363  
   364  	// Set colorization
   365  	m.color = m.Color
   366  	for i, v := range args {
   367  		if v == "-no-color" {
   368  			m.color = false
   369  			m.Color = false
   370  			args = append(args[:i], args[i+1:]...)
   371  			break
   372  		}
   373  	}
   374  
   375  	// Set the UI
   376  	m.oldUi = m.Ui
   377  	m.Ui = &cli.ConcurrentUi{
   378  		Ui: &ColorizeUi{
   379  			Colorize:   m.Colorize(),
   380  			ErrorColor: "[red]",
   381  			WarnColor:  "[yellow]",
   382  			Ui:         m.oldUi,
   383  		},
   384  	}
   385  
   386  	// If we support vars and the default var file exists, add it to
   387  	// the args...
   388  	m.autoKey = ""
   389  	if vars {
   390  		if _, err := os.Stat(DefaultVarsFilename); err == nil {
   391  			m.autoKey = "var-file-default"
   392  			args = append(args, "", "")
   393  			copy(args[2:], args[0:])
   394  			args[0] = "-" + m.autoKey
   395  			args[1] = DefaultVarsFilename
   396  		}
   397  
   398  		if _, err := os.Stat(DefaultVarsFilename + ".json"); err == nil {
   399  			m.autoKey = "var-file-default"
   400  			args = append(args, "", "")
   401  			copy(args[2:], args[0:])
   402  			args[0] = "-" + m.autoKey
   403  			args[1] = DefaultVarsFilename + ".json"
   404  		}
   405  	}
   406  
   407  	return args
   408  }
   409  
   410  // uiHook returns the UiHook to use with the context.
   411  func (m *Meta) uiHook() *UiHook {
   412  	return &UiHook{
   413  		Colorize: m.Colorize(),
   414  		Ui:       m.Ui,
   415  	}
   416  }
   417  
   418  const (
   419  	// ModuleDepthDefault is the default value for
   420  	// module depth, which can be overridden by flag
   421  	// or env var
   422  	ModuleDepthDefault = -1
   423  
   424  	// ModuleDepthEnvVar is the name of the environment variable that can be used to set module depth.
   425  	ModuleDepthEnvVar = "TF_MODULE_DEPTH"
   426  )
   427  
   428  func (m *Meta) addModuleDepthFlag(flags *flag.FlagSet, moduleDepth *int) {
   429  	flags.IntVar(moduleDepth, "module-depth", ModuleDepthDefault, "module-depth")
   430  	if envVar := os.Getenv(ModuleDepthEnvVar); envVar != "" {
   431  		if md, err := strconv.Atoi(envVar); err == nil {
   432  			*moduleDepth = md
   433  		}
   434  	}
   435  }
   436  
   437  // contextOpts are the options used to load a context from a command.
   438  type contextOpts struct {
   439  	// Path to the directory where the root module is.
   440  	Path string
   441  
   442  	// StatePath is the path to the state file. If this is empty, then
   443  	// no state will be loaded. It is also okay for this to be a path to
   444  	// a file that doesn't exist; it is assumed that this means that there
   445  	// is simply no state.
   446  	StatePath string
   447  
   448  	// GetMode is the module.GetMode to use when loading the module tree.
   449  	GetMode module.GetMode
   450  
   451  	// Set to true when running a destroy plan/apply.
   452  	Destroy bool
   453  
   454  	// Number of concurrent operations allowed
   455  	Parallelism int
   456  }