github.com/tkak/terraform@v0.5.4-0.20150712180941-7f738dc27225/command/output.go (about) 1 package command 2 3 import ( 4 "flag" 5 "fmt" 6 "strings" 7 ) 8 9 // OutputCommand is a Command implementation that reads an output 10 // from a Terraform state and prints it. 11 type OutputCommand struct { 12 Meta 13 } 14 15 func (c *OutputCommand) Run(args []string) int { 16 args = c.Meta.process(args, false) 17 18 var module string 19 cmdFlags := flag.NewFlagSet("output", flag.ContinueOnError) 20 cmdFlags.StringVar(&c.Meta.statePath, "state", DefaultStateFilename, "path") 21 cmdFlags.StringVar(&module, "module", "", "module") 22 cmdFlags.Usage = func() { c.Ui.Error(c.Help()) } 23 24 if err := cmdFlags.Parse(args); err != nil { 25 return 1 26 } 27 28 args = cmdFlags.Args() 29 if len(args) != 1 || args[0] == "" { 30 c.Ui.Error( 31 "The output command expects exactly one argument with the name\n" + 32 "of an output variable.\n") 33 cmdFlags.Usage() 34 return 1 35 } 36 name := args[0] 37 38 stateStore, err := c.Meta.State() 39 if err != nil { 40 c.Ui.Error(fmt.Sprintf("Error reading state: %s", err)) 41 return 1 42 } 43 44 if module == "" { 45 module = "root" 46 } else { 47 module = "root." + module 48 } 49 50 // Get the proper module we want to get outputs for 51 modPath := strings.Split(module, ".") 52 53 state := stateStore.State() 54 mod := state.ModuleByPath(modPath) 55 56 if mod == nil { 57 c.Ui.Error(fmt.Sprintf( 58 "The module %s could not be found. There is nothing to output.", 59 module)) 60 return 1 61 } 62 63 if state.Empty() || len(mod.Outputs) == 0 { 64 c.Ui.Error(fmt.Sprintf( 65 "The state file has no outputs defined. Define an output\n" + 66 "in your configuration with the `output` directive and re-run\n" + 67 "`terraform apply` for it to become available.")) 68 return 1 69 } 70 71 v, ok := mod.Outputs[name] 72 if !ok { 73 c.Ui.Error(fmt.Sprintf( 74 "The output variable requested could not be found in the state\n" + 75 "file. If you recently added this to your configuration, be\n" + 76 "sure to run `terraform apply`, since the state won't be updated\n" + 77 "with new output variables until that command is run.")) 78 return 1 79 } 80 81 c.Ui.Output(v) 82 return 0 83 } 84 85 func (c *OutputCommand) Help() string { 86 helpText := ` 87 Usage: terraform output [options] NAME 88 89 Reads an output variable from a Terraform state file and prints 90 the value. 91 92 Options: 93 94 -state=path Path to the state file to read. Defaults to 95 "terraform.tfstate". 96 97 -no-color If specified, output won't contain any color. 98 99 ` 100 return strings.TrimSpace(helpText) 101 } 102 103 func (c *OutputCommand) Synopsis() string { 104 return "Read an output from a state file" 105 }