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