github.com/lukahartwig/terraform@v0.11.4-0.20180302171601-664391c254ea/command/state_pull.go (about)

     1  package command
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/hashicorp/terraform/terraform"
     9  	"github.com/mitchellh/cli"
    10  )
    11  
    12  // StatePullCommand is a Command implementation that shows a single resource.
    13  type StatePullCommand struct {
    14  	Meta
    15  	StateMeta
    16  }
    17  
    18  func (c *StatePullCommand) Run(args []string) int {
    19  	args, err := c.Meta.process(args, true)
    20  	if err != nil {
    21  		return 1
    22  	}
    23  
    24  	cmdFlags := c.Meta.flagSet("state pull")
    25  	if err := cmdFlags.Parse(args); err != nil {
    26  		return cli.RunResultHelp
    27  	}
    28  	args = cmdFlags.Args()
    29  
    30  	// Load the backend
    31  	b, err := c.Backend(nil)
    32  	if err != nil {
    33  		c.Ui.Error(fmt.Sprintf("Failed to load backend: %s", err))
    34  		return 1
    35  	}
    36  
    37  	// Get the state
    38  	env := c.Workspace()
    39  	state, err := b.State(env)
    40  	if err != nil {
    41  		c.Ui.Error(fmt.Sprintf("Failed to load state: %s", err))
    42  		return 1
    43  	}
    44  	if err := state.RefreshState(); err != nil {
    45  		c.Ui.Error(fmt.Sprintf("Failed to load state: %s", err))
    46  		return 1
    47  	}
    48  
    49  	s := state.State()
    50  	if s == nil {
    51  		// Output on "error" so it shows up on stderr
    52  		c.Ui.Error("Empty state (no state)")
    53  
    54  		return 0
    55  	}
    56  
    57  	var buf bytes.Buffer
    58  	if err := terraform.WriteState(s, &buf); err != nil {
    59  		c.Ui.Error(fmt.Sprintf("Failed to load state: %s", err))
    60  		return 1
    61  	}
    62  
    63  	c.Ui.Output(buf.String())
    64  	return 0
    65  }
    66  
    67  func (c *StatePullCommand) Help() string {
    68  	helpText := `
    69  Usage: terraform state pull [options]
    70  
    71    Pull the state from its location and output it to stdout.
    72  
    73    This command "pulls" the current state and outputs it to stdout.
    74    The primary use of this is for state stored remotely. This command
    75    will still work with local state but is less useful for this.
    76  
    77  `
    78  	return strings.TrimSpace(helpText)
    79  }
    80  
    81  func (c *StatePullCommand) Synopsis() string {
    82  	return "Pull current state and output to stdout"
    83  }