github.com/rstandt/terraform@v0.12.32-0.20230710220336-b1063613405c/command/refresh.go (about)

     1  package command
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/hashicorp/terraform/addrs"
     8  	"github.com/hashicorp/terraform/backend"
     9  	"github.com/hashicorp/terraform/tfdiags"
    10  )
    11  
    12  // RefreshCommand is a cli.Command implementation that refreshes the state
    13  // file.
    14  type RefreshCommand struct {
    15  	Meta
    16  }
    17  
    18  func (c *RefreshCommand) 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.extendedFlagSet("refresh")
    25  	cmdFlags.StringVar(&c.Meta.statePath, "state", DefaultStateFilename, "path")
    26  	cmdFlags.IntVar(&c.Meta.parallelism, "parallelism", DefaultParallelism, "parallelism")
    27  	cmdFlags.StringVar(&c.Meta.stateOutPath, "state-out", "", "path")
    28  	cmdFlags.StringVar(&c.Meta.backupPath, "backup", "", "path")
    29  	cmdFlags.BoolVar(&c.Meta.stateLock, "lock", true, "lock state")
    30  	cmdFlags.DurationVar(&c.Meta.stateLockTimeout, "lock-timeout", 0, "lock timeout")
    31  	cmdFlags.Usage = func() { c.Ui.Error(c.Help()) }
    32  	if err := cmdFlags.Parse(args); err != nil {
    33  		return 1
    34  	}
    35  
    36  	configPath, err := ModulePath(cmdFlags.Args())
    37  	if err != nil {
    38  		c.Ui.Error(err.Error())
    39  		return 1
    40  	}
    41  
    42  	var diags tfdiags.Diagnostics
    43  
    44  	// Check for user-supplied plugin path
    45  	if c.pluginPath, err = c.loadPluginPath(); err != nil {
    46  		c.Ui.Error(fmt.Sprintf("Error loading plugin path: %s", err))
    47  		return 1
    48  	}
    49  
    50  	backendConfig, configDiags := c.loadBackendConfig(configPath)
    51  	diags = diags.Append(configDiags)
    52  	if configDiags.HasErrors() {
    53  		c.showDiagnostics(diags)
    54  		return 1
    55  	}
    56  
    57  	// Load the backend
    58  	b, backendDiags := c.Backend(&BackendOpts{
    59  		Config: backendConfig,
    60  	})
    61  	diags = diags.Append(backendDiags)
    62  	if backendDiags.HasErrors() {
    63  		c.showDiagnostics(diags)
    64  		return 1
    65  	}
    66  
    67  	// Before we delegate to the backend, we'll print any warning diagnostics
    68  	// we've accumulated here, since the backend will start fresh with its own
    69  	// diagnostics.
    70  	c.showDiagnostics(diags)
    71  	diags = nil
    72  
    73  	// Build the operation
    74  	opReq := c.Operation(b)
    75  	opReq.ConfigDir = configPath
    76  	opReq.Type = backend.OperationTypeRefresh
    77  
    78  	opReq.ConfigLoader, err = c.initConfigLoader()
    79  	if err != nil {
    80  		c.showDiagnostics(err)
    81  		return 1
    82  	}
    83  
    84  	{
    85  		var moreDiags tfdiags.Diagnostics
    86  		opReq.Variables, moreDiags = c.collectVariableValues()
    87  		diags = diags.Append(moreDiags)
    88  		if moreDiags.HasErrors() {
    89  			c.showDiagnostics(diags)
    90  			return 1
    91  		}
    92  	}
    93  
    94  	op, err := c.RunOperation(b, opReq)
    95  	if err != nil {
    96  		c.showDiagnostics(err)
    97  		return 1
    98  	}
    99  	if op.Result != backend.OperationSuccess {
   100  		return op.Result.ExitStatus()
   101  	}
   102  
   103  	if outputs := outputsAsString(op.State, addrs.RootModuleInstance, true); outputs != "" {
   104  		c.Ui.Output(c.Colorize().Color(outputs))
   105  	}
   106  
   107  	return op.Result.ExitStatus()
   108  }
   109  
   110  func (c *RefreshCommand) Help() string {
   111  	helpText := `
   112  Usage: terraform refresh [options] [dir]
   113  
   114    Update the state file of your infrastructure with metadata that matches
   115    the physical resources they are tracking.
   116  
   117    This will not modify your infrastructure, but it can modify your
   118    state file to update metadata. This metadata might cause new changes
   119    to occur when you generate a plan or call apply next.
   120  
   121  Options:
   122  
   123    -backup=path        Path to backup the existing state file before
   124                        modifying. Defaults to the "-state-out" path with
   125                        ".backup" extension. Set to "-" to disable backup.
   126  
   127    -compact-warnings   If Terraform produces any warnings that are not
   128                        accompanied by errors, show them in a more compact form
   129                        that includes only the summary messages.
   130  
   131    -input=true         Ask for input for variables if not directly set.
   132  
   133    -lock=true          Lock the state file when locking is supported.
   134  
   135    -lock-timeout=0s    Duration to retry a state lock.
   136  
   137    -no-color           If specified, output won't contain any color.
   138  
   139    -state=path         Path to read and save state (unless state-out
   140                        is specified). Defaults to "terraform.tfstate".
   141  
   142    -state-out=path     Path to write updated state file. By default, the
   143                        "-state" path will be used.
   144  
   145    -target=resource    Resource to target. Operation will be limited to this
   146                        resource and its dependencies. This flag can be used
   147                        multiple times.
   148  
   149    -var 'foo=bar'      Set a variable in the Terraform configuration. This
   150                        flag can be set multiple times.
   151  
   152    -var-file=foo       Set variables in the Terraform configuration from
   153                        a file. If "terraform.tfvars" or any ".auto.tfvars"
   154                        files are present, they will be automatically loaded.
   155  
   156  `
   157  	return strings.TrimSpace(helpText)
   158  }
   159  
   160  func (c *RefreshCommand) Synopsis() string {
   161  	return "Update local state file against real resources"
   162  }