github.com/jdextraze/terraform@v0.6.17-0.20160511153921-e33847c8a8af/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 mod, err := module.NewTreeModule("", copts.Path) 150 if err != nil { 151 return nil, false, fmt.Errorf("Error loading config: %s", err) 152 } 153 154 err = mod.Load(m.moduleStorage(m.DataDir()), copts.GetMode) 155 if err != nil { 156 return nil, false, fmt.Errorf("Error downloading modules: %s", err) 157 } 158 159 opts.Module = mod 160 opts.Parallelism = copts.Parallelism 161 opts.State = state.State() 162 ctx, err := terraform.NewContext(opts) 163 return ctx, false, err 164 } 165 166 // DataDir returns the directory where local data will be stored. 167 func (m *Meta) DataDir() string { 168 dataDir := DefaultDataDirectory 169 if m.dataDir != "" { 170 dataDir = m.dataDir 171 } 172 173 return dataDir 174 } 175 176 const ( 177 // InputModeEnvVar is the environment variable that, if set to "false" or 178 // "0", causes terraform commands to behave as if the `-input=false` flag was 179 // specified. 180 InputModeEnvVar = "TF_INPUT" 181 ) 182 183 // InputMode returns the type of input we should ask for in the form of 184 // terraform.InputMode which is passed directly to Context.Input. 185 func (m *Meta) InputMode() terraform.InputMode { 186 if test || !m.input { 187 return 0 188 } 189 190 if envVar := os.Getenv(InputModeEnvVar); envVar != "" { 191 if v, err := strconv.ParseBool(envVar); err == nil { 192 if !v { 193 return 0 194 } 195 } 196 } 197 198 var mode terraform.InputMode 199 mode |= terraform.InputModeProvider 200 if len(m.variables) == 0 { 201 mode |= terraform.InputModeVar 202 mode |= terraform.InputModeVarUnset 203 } 204 205 return mode 206 } 207 208 // State returns the state for this meta. 209 func (m *Meta) State() (state.State, error) { 210 if m.state != nil { 211 return m.state, nil 212 } 213 214 result, err := State(m.StateOpts()) 215 if err != nil { 216 return nil, err 217 } 218 219 m.state = result.State 220 m.stateOutPath = result.StatePath 221 m.stateResult = result 222 return m.state, nil 223 } 224 225 // StateRaw is used to setup the state manually. 226 func (m *Meta) StateRaw(opts *StateOpts) (*StateResult, error) { 227 result, err := State(opts) 228 if err != nil { 229 return nil, err 230 } 231 232 m.state = result.State 233 m.stateOutPath = result.StatePath 234 m.stateResult = result 235 return result, nil 236 } 237 238 // StateOpts returns the default state options 239 func (m *Meta) StateOpts() *StateOpts { 240 localPath := m.statePath 241 if localPath == "" { 242 localPath = DefaultStateFilename 243 } 244 remotePath := filepath.Join(m.DataDir(), DefaultStateFilename) 245 246 return &StateOpts{ 247 LocalPath: localPath, 248 LocalPathOut: m.stateOutPath, 249 RemotePath: remotePath, 250 RemoteRefresh: true, 251 BackupPath: m.backupPath, 252 } 253 } 254 255 // UIInput returns a UIInput object to be used for asking for input. 256 func (m *Meta) UIInput() terraform.UIInput { 257 return &UIInput{ 258 Colorize: m.Colorize(), 259 } 260 } 261 262 // PersistState is used to write out the state, handling backup of 263 // the existing state file and respecting path configurations. 264 func (m *Meta) PersistState(s *terraform.State) error { 265 if err := m.state.WriteState(s); err != nil { 266 return err 267 } 268 269 return m.state.PersistState() 270 } 271 272 // Input returns true if we should ask for input for context. 273 func (m *Meta) Input() bool { 274 return !test && m.input && len(m.variables) == 0 275 } 276 277 // contextOpts returns the options to use to initialize a Terraform 278 // context with the settings from this Meta. 279 func (m *Meta) contextOpts() *terraform.ContextOpts { 280 var opts terraform.ContextOpts = *m.ContextOpts 281 opts.Hooks = make( 282 []terraform.Hook, 283 len(m.ContextOpts.Hooks)+len(m.extraHooks)+1) 284 opts.Hooks[0] = m.uiHook() 285 copy(opts.Hooks[1:], m.ContextOpts.Hooks) 286 copy(opts.Hooks[len(m.ContextOpts.Hooks)+1:], m.extraHooks) 287 288 vs := make(map[string]string) 289 for k, v := range opts.Variables { 290 vs[k] = v 291 } 292 for k, v := range m.autoVariables { 293 vs[k] = v 294 } 295 for k, v := range m.variables { 296 vs[k] = v 297 } 298 opts.Variables = vs 299 opts.Targets = m.targets 300 opts.UIInput = m.UIInput() 301 302 return &opts 303 } 304 305 // flags adds the meta flags to the given FlagSet. 306 func (m *Meta) flagSet(n string) *flag.FlagSet { 307 f := flag.NewFlagSet(n, flag.ContinueOnError) 308 f.BoolVar(&m.input, "input", true, "input") 309 f.Var((*FlagKV)(&m.variables), "var", "variables") 310 f.Var((*FlagKVFile)(&m.variables), "var-file", "variable file") 311 f.Var((*FlagStringSlice)(&m.targets), "target", "resource to target") 312 313 if m.autoKey != "" { 314 f.Var((*FlagKVFile)(&m.autoVariables), m.autoKey, "variable file") 315 } 316 317 // Create an io.Writer that writes to our Ui properly for errors. 318 // This is kind of a hack, but it does the job. Basically: create 319 // a pipe, use a scanner to break it into lines, and output each line 320 // to the UI. Do this forever. 321 errR, errW := io.Pipe() 322 errScanner := bufio.NewScanner(errR) 323 go func() { 324 for errScanner.Scan() { 325 m.Ui.Error(errScanner.Text()) 326 } 327 }() 328 f.SetOutput(errW) 329 330 // Set the default Usage to empty 331 f.Usage = func() {} 332 333 return f 334 } 335 336 // moduleStorage returns the module.Storage implementation used to store 337 // modules for commands. 338 func (m *Meta) moduleStorage(root string) getter.Storage { 339 return &uiModuleStorage{ 340 Storage: &getter.FolderStorage{ 341 StorageDir: filepath.Join(root, "modules"), 342 }, 343 Ui: m.Ui, 344 } 345 } 346 347 // process will process the meta-parameters out of the arguments. This 348 // will potentially modify the args in-place. It will return the resulting 349 // slice. 350 // 351 // vars says whether or not we support variables. 352 func (m *Meta) process(args []string, vars bool) []string { 353 // We do this so that we retain the ability to technically call 354 // process multiple times, even if we have no plans to do so 355 if m.oldUi != nil { 356 m.Ui = m.oldUi 357 } 358 359 // Set colorization 360 m.color = m.Color 361 for i, v := range args { 362 if v == "-no-color" { 363 m.color = false 364 m.Color = false 365 args = append(args[:i], args[i+1:]...) 366 break 367 } 368 } 369 370 // Set the UI 371 m.oldUi = m.Ui 372 m.Ui = &cli.ConcurrentUi{ 373 Ui: &ColorizeUi{ 374 Colorize: m.Colorize(), 375 ErrorColor: "[red]", 376 WarnColor: "[yellow]", 377 Ui: m.oldUi, 378 }, 379 } 380 381 // If we support vars and the default var file exists, add it to 382 // the args... 383 m.autoKey = "" 384 if vars { 385 if _, err := os.Stat(DefaultVarsFilename); err == nil { 386 m.autoKey = "var-file-default" 387 args = append(args, "", "") 388 copy(args[2:], args[0:]) 389 args[0] = "-" + m.autoKey 390 args[1] = DefaultVarsFilename 391 } 392 393 if _, err := os.Stat(DefaultVarsFilename + ".json"); err == nil { 394 m.autoKey = "var-file-default" 395 args = append(args, "", "") 396 copy(args[2:], args[0:]) 397 args[0] = "-" + m.autoKey 398 args[1] = DefaultVarsFilename + ".json" 399 } 400 } 401 402 return args 403 } 404 405 // uiHook returns the UiHook to use with the context. 406 func (m *Meta) uiHook() *UiHook { 407 return &UiHook{ 408 Colorize: m.Colorize(), 409 Ui: m.Ui, 410 } 411 } 412 413 const ( 414 // ModuleDepthDefault is the default value for 415 // module depth, which can be overridden by flag 416 // or env var 417 ModuleDepthDefault = -1 418 419 // ModuleDepthEnvVar is the name of the environment variable that can be used to set module depth. 420 ModuleDepthEnvVar = "TF_MODULE_DEPTH" 421 ) 422 423 func (m *Meta) addModuleDepthFlag(flags *flag.FlagSet, moduleDepth *int) { 424 flags.IntVar(moduleDepth, "module-depth", ModuleDepthDefault, "module-depth") 425 if envVar := os.Getenv(ModuleDepthEnvVar); envVar != "" { 426 if md, err := strconv.Atoi(envVar); err == nil { 427 *moduleDepth = md 428 } 429 } 430 } 431 432 // contextOpts are the options used to load a context from a command. 433 type contextOpts struct { 434 // Path to the directory where the root module is. 435 Path string 436 437 // StatePath is the path to the state file. If this is empty, then 438 // no state will be loaded. It is also okay for this to be a path to 439 // a file that doesn't exist; it is assumed that this means that there 440 // is simply no state. 441 StatePath string 442 443 // GetMode is the module.GetMode to use when loading the module tree. 444 GetMode module.GetMode 445 446 // Set to true when running a destroy plan/apply. 447 Destroy bool 448 449 // Number of concurrent operations allowed 450 Parallelism int 451 }