github.com/nicgrayson/terraform@v0.4.3-0.20150415203910-c4de50829380/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 cmdFlags := flag.NewFlagSet("output", flag.ContinueOnError) 19 cmdFlags.StringVar(&c.Meta.statePath, "state", DefaultStateFilename, "path") 20 cmdFlags.Usage = func() { c.Ui.Error(c.Help()) } 21 if err := cmdFlags.Parse(args); err != nil { 22 return 1 23 } 24 25 args = cmdFlags.Args() 26 if len(args) != 1 || args[0] == "" { 27 c.Ui.Error( 28 "The output command expects exactly one argument with the name\n" + 29 "of an output variable.\n") 30 cmdFlags.Usage() 31 return 1 32 } 33 name := args[0] 34 35 stateStore, err := c.Meta.State() 36 if err != nil { 37 c.Ui.Error(fmt.Sprintf("Error reading state: %s", err)) 38 return 1 39 } 40 41 state := stateStore.State() 42 if state.Empty() || len(state.RootModule().Outputs) == 0 { 43 c.Ui.Error(fmt.Sprintf( 44 "The state file has no outputs defined. Define an output\n" + 45 "in your configuration with the `output` directive and re-run\n" + 46 "`terraform apply` for it to become available.")) 47 return 1 48 } 49 v, ok := state.RootModule().Outputs[name] 50 if !ok { 51 c.Ui.Error(fmt.Sprintf( 52 "The output variable requested could not be found in the state\n" + 53 "file. If you recently added this to your configuration, be\n" + 54 "sure to run `terraform apply`, since the state won't be updated\n" + 55 "with new output variables until that command is run.")) 56 return 1 57 } 58 59 c.Ui.Output(v) 60 return 0 61 } 62 63 func (c *OutputCommand) Help() string { 64 helpText := ` 65 Usage: terraform output [options] NAME 66 67 Reads an output variable from a Terraform state file and prints 68 the value. 69 70 Options: 71 72 -state=path Path to the state file to read. Defaults to 73 "terraform.tfstate". 74 75 ` 76 return strings.TrimSpace(helpText) 77 } 78 79 func (c *OutputCommand) Synopsis() string { 80 return "Read an output from a state file" 81 }