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