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