github.com/rstandt/terraform@v0.12.32-0.20230710220336-b1063613405c/command/state_pull.go (about) 1 package command 2 3 import ( 4 "bytes" 5 "fmt" 6 "strings" 7 8 "github.com/hashicorp/terraform/states/statefile" 9 "github.com/hashicorp/terraform/states/statemgr" 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.defaultFlagSet("state pull") 25 if err := cmdFlags.Parse(args); err != nil { 26 c.Ui.Error(fmt.Sprintf("Error parsing command-line flags: %s\n", err.Error())) 27 return 1 28 } 29 args = cmdFlags.Args() 30 31 // Load the backend 32 b, backendDiags := c.Backend(nil) 33 if backendDiags.HasErrors() { 34 c.showDiagnostics(backendDiags) 35 return 1 36 } 37 38 // Get the state manager for the current workspace 39 env := c.Workspace() 40 stateMgr, err := b.StateMgr(env) 41 if err != nil { 42 c.Ui.Error(fmt.Sprintf(errStateLoadingState, err)) 43 return 1 44 } 45 if err := stateMgr.RefreshState(); err != nil { 46 c.Ui.Error(fmt.Sprintf("Failed to refresh state: %s", err)) 47 return 1 48 } 49 50 // Get a statefile object representing the latest snapshot 51 stateFile := statemgr.Export(stateMgr) 52 53 if stateFile != nil { // we produce no output if the statefile is nil 54 var buf bytes.Buffer 55 err = statefile.Write(stateFile, &buf) 56 if err != nil { 57 c.Ui.Error(fmt.Sprintf("Failed to write state: %s", err)) 58 return 1 59 } 60 61 c.Ui.Output(buf.String()) 62 } 63 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 }