github.com/chalford/terraform@v0.3.7-0.20150113080010-a78c69a8c81f/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  	state, err := c.Meta.loadState()
    36  	if err != nil {
    37  		c.Ui.Error(fmt.Sprintf("Error reading state: %s", err))
    38  		return 1
    39  	}
    40  
    41  	if len(state.RootModule().Outputs) == 0 {
    42  		c.Ui.Error(fmt.Sprintf(
    43  			"The state file has no outputs defined. Define an output\n" +
    44  				"in your configuration with the `output` directive and re-run\n" +
    45  				"`terraform apply` for it to become available."))
    46  		return 1
    47  	}
    48  	v, ok := state.RootModule().Outputs[name]
    49  	if !ok {
    50  		c.Ui.Error(fmt.Sprintf(
    51  			"The output variable requested could not be found in the state\n" +
    52  				"file. If you recently added this to your configuration, be\n" +
    53  				"sure to run `terraform apply`, since the state won't be updated\n" +
    54  				"with new output variables until that command is run."))
    55  		return 1
    56  	}
    57  
    58  	c.Ui.Output(v)
    59  	return 0
    60  }
    61  
    62  func (c *OutputCommand) Help() string {
    63  	helpText := `
    64  Usage: terraform output [options] NAME
    65  
    66    Reads an output variable from a Terraform state file and prints
    67    the value.
    68  
    69  Options:
    70  
    71    -state=path      Path to the state file to read. Defaults to
    72                     "terraform.tfstate".
    73  
    74  `
    75  	return strings.TrimSpace(helpText)
    76  }
    77  
    78  func (c *OutputCommand) Synopsis() string {
    79  	return "Read an output from a state file"
    80  }