github.com/kevinklinger/open_terraform@v1.3.6/noninternal/command/state_pull.go (about) 1 package command 2 3 import ( 4 "bytes" 5 "fmt" 6 "strings" 7 8 "github.com/kevinklinger/open_terraform/noninternal/states/statefile" 9 "github.com/kevinklinger/open_terraform/noninternal/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 = c.Meta.process(args) 20 cmdFlags := c.Meta.defaultFlagSet("state pull") 21 if err := cmdFlags.Parse(args); err != nil { 22 c.Ui.Error(fmt.Sprintf("Error parsing command-line flags: %s\n", err.Error())) 23 return 1 24 } 25 26 if diags := c.Meta.checkRequiredVersion(); diags != nil { 27 c.showDiagnostics(diags) 28 return 1 29 } 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 // This is a read-only command 39 c.ignoreRemoteVersionConflict(b) 40 41 // Get the state manager for the current workspace 42 env, err := c.Workspace() 43 if err != nil { 44 c.Ui.Error(fmt.Sprintf("Error selecting workspace: %s", err)) 45 return 1 46 } 47 stateMgr, err := b.StateMgr(env) 48 if err != nil { 49 c.Ui.Error(fmt.Sprintf(errStateLoadingState, err)) 50 return 1 51 } 52 if err := stateMgr.RefreshState(); err != nil { 53 c.Ui.Error(fmt.Sprintf("Failed to refresh state: %s", err)) 54 return 1 55 } 56 57 // Get a statefile object representing the latest snapshot 58 stateFile := statemgr.Export(stateMgr) 59 60 if stateFile != nil { // we produce no output if the statefile is nil 61 var buf bytes.Buffer 62 err = statefile.Write(stateFile, &buf) 63 if err != nil { 64 c.Ui.Error(fmt.Sprintf("Failed to write state: %s", err)) 65 return 1 66 } 67 68 c.Ui.Output(buf.String()) 69 } 70 71 return 0 72 } 73 74 func (c *StatePullCommand) Help() string { 75 helpText := ` 76 Usage: terraform [global options] state pull [options] 77 78 Pull the state from its location, upgrade the local copy, and output it 79 to stdout. 80 81 This command "pulls" the current state and outputs it to stdout. 82 As part of this process, Terraform will upgrade the state format of the 83 local copy to the current version. 84 85 The primary use of this is for state stored remotely. This command 86 will still work with local state but is less useful for this. 87 88 ` 89 return strings.TrimSpace(helpText) 90 } 91 92 func (c *StatePullCommand) Synopsis() string { 93 return "Pull current state and output to stdout" 94 }