github.com/ezbercih/terraform@v0.1.1-0.20140729011846-3c33865e0839/command/show.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  // ShowCommand is a Command implementation that reads and outputs the
    13  // contents of a Terraform plan or state file.
    14  type ShowCommand struct {
    15  	Meta
    16  }
    17  
    18  func (c *ShowCommand) Run(args []string) int {
    19  	args = c.Meta.process(args)
    20  
    21  	cmdFlags := flag.NewFlagSet("show", flag.ContinueOnError)
    22  	cmdFlags.Usage = func() { c.Ui.Error(c.Help()) }
    23  	if err := cmdFlags.Parse(args); err != nil {
    24  		return 1
    25  	}
    26  
    27  	args = cmdFlags.Args()
    28  	if len(args) != 1 {
    29  		c.Ui.Error(
    30  			"The show command expects exactly one argument with the path\n" +
    31  				"to a Terraform state or plan file.\n")
    32  		cmdFlags.Usage()
    33  		return 1
    34  	}
    35  	path := args[0]
    36  
    37  	var plan *terraform.Plan
    38  	var state *terraform.State
    39  
    40  	f, err := os.Open(path)
    41  	if err != nil {
    42  		c.Ui.Error(fmt.Sprintf("Error loading file: %s", err))
    43  		return 1
    44  	}
    45  
    46  	var planErr, stateErr error
    47  	plan, err = terraform.ReadPlan(f)
    48  	if err != nil {
    49  		if _, err := f.Seek(0, 0); err != nil {
    50  			c.Ui.Error(fmt.Sprintf("Error reading file: %s", err))
    51  			return 1
    52  		}
    53  
    54  		plan = nil
    55  		planErr = err
    56  	}
    57  	if plan == nil {
    58  		state, err = terraform.ReadState(f)
    59  		if err != nil {
    60  			stateErr = err
    61  		}
    62  	}
    63  	if plan == nil && state == nil {
    64  		c.Ui.Error(fmt.Sprintf(
    65  			"Terraform couldn't read the given file as a state or plan file.\n"+
    66  				"The errors while attempting to read the file as each format are\n"+
    67  				"shown below.\n\n"+
    68  				"State read error: %s\n\nPlan read error: %s",
    69  			stateErr,
    70  			planErr))
    71  		return 1
    72  	}
    73  
    74  	if plan != nil {
    75  		c.Ui.Output(FormatPlan(plan, c.Colorize()))
    76  		return 0
    77  	}
    78  
    79  	c.Ui.Output(FormatState(state, c.Colorize()))
    80  	return 0
    81  }
    82  
    83  func (c *ShowCommand) Help() string {
    84  	helpText := `
    85  Usage: terraform show [options] path
    86  
    87    Reads and outputs a Terraform state or plan file in a human-readable
    88    form.
    89  
    90  Options:
    91  
    92    -no-color     If specified, output won't contain any color.
    93  
    94  `
    95  	return strings.TrimSpace(helpText)
    96  }
    97  
    98  func (c *ShowCommand) Synopsis() string {
    99  	return "Inspect Terraform state or plan"
   100  }