github.com/jzbruno/terraform@v0.10.3-0.20180104230435-18975d727047/command/plan.go (about)

     1  package command
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/hashicorp/terraform/backend"
     9  	"github.com/hashicorp/terraform/config"
    10  	"github.com/hashicorp/terraform/config/module"
    11  	"github.com/hashicorp/terraform/tfdiags"
    12  )
    13  
    14  // PlanCommand is a Command implementation that compares a Terraform
    15  // configuration to an actual infrastructure and shows the differences.
    16  type PlanCommand struct {
    17  	Meta
    18  }
    19  
    20  func (c *PlanCommand) Run(args []string) int {
    21  	var destroy, refresh, detailed bool
    22  	var outPath string
    23  	var moduleDepth int
    24  
    25  	args, err := c.Meta.process(args, true)
    26  	if err != nil {
    27  		return 1
    28  	}
    29  
    30  	cmdFlags := c.Meta.flagSet("plan")
    31  	cmdFlags.BoolVar(&destroy, "destroy", false, "destroy")
    32  	cmdFlags.BoolVar(&refresh, "refresh", true, "refresh")
    33  	c.addModuleDepthFlag(cmdFlags, &moduleDepth)
    34  	cmdFlags.StringVar(&outPath, "out", "", "path")
    35  	cmdFlags.IntVar(
    36  		&c.Meta.parallelism, "parallelism", DefaultParallelism, "parallelism")
    37  	cmdFlags.StringVar(&c.Meta.statePath, "state", "", "path")
    38  	cmdFlags.BoolVar(&detailed, "detailed-exitcode", false, "detailed-exitcode")
    39  	cmdFlags.BoolVar(&c.Meta.stateLock, "lock", true, "lock state")
    40  	cmdFlags.DurationVar(&c.Meta.stateLockTimeout, "lock-timeout", 0, "lock timeout")
    41  	cmdFlags.Usage = func() { c.Ui.Error(c.Help()) }
    42  	if err := cmdFlags.Parse(args); err != nil {
    43  		return 1
    44  	}
    45  
    46  	configPath, err := ModulePath(cmdFlags.Args())
    47  	if err != nil {
    48  		c.Ui.Error(err.Error())
    49  		return 1
    50  	}
    51  
    52  	// Check for user-supplied plugin path
    53  	if c.pluginPath, err = c.loadPluginPath(); err != nil {
    54  		c.Ui.Error(fmt.Sprintf("Error loading plugin path: %s", err))
    55  		return 1
    56  	}
    57  
    58  	// Check if the path is a plan
    59  	plan, err := c.Plan(configPath)
    60  	if err != nil {
    61  		c.Ui.Error(err.Error())
    62  		return 1
    63  	}
    64  	if plan != nil {
    65  		// Disable refreshing no matter what since we only want to show the plan
    66  		refresh = false
    67  
    68  		// Set the config path to empty for backend loading
    69  		configPath = ""
    70  	}
    71  
    72  	var diags tfdiags.Diagnostics
    73  
    74  	// Load the module if we don't have one yet (not running from plan)
    75  	var mod *module.Tree
    76  	if plan == nil {
    77  		var modDiags tfdiags.Diagnostics
    78  		mod, modDiags = c.Module(configPath)
    79  		diags = diags.Append(modDiags)
    80  		if modDiags.HasErrors() {
    81  			c.showDiagnostics(diags)
    82  			return 1
    83  		}
    84  	}
    85  
    86  	var conf *config.Config
    87  	if mod != nil {
    88  		conf = mod.Config()
    89  	}
    90  	// Load the backend
    91  	b, err := c.Backend(&BackendOpts{
    92  		Config: conf,
    93  		Plan:   plan,
    94  	})
    95  	if err != nil {
    96  		c.Ui.Error(fmt.Sprintf("Failed to load backend: %s", err))
    97  		return 1
    98  	}
    99  
   100  	// Build the operation
   101  	opReq := c.Operation()
   102  	opReq.Destroy = destroy
   103  	opReq.Module = mod
   104  	opReq.Plan = plan
   105  	opReq.PlanRefresh = refresh
   106  	opReq.PlanOutPath = outPath
   107  	opReq.Type = backend.OperationTypePlan
   108  
   109  	// Perform the operation
   110  	ctx, ctxCancel := context.WithCancel(context.Background())
   111  	defer ctxCancel()
   112  
   113  	op, err := b.Operation(ctx, opReq)
   114  	if err != nil {
   115  		c.Ui.Error(fmt.Sprintf("Error starting operation: %s", err))
   116  		return 1
   117  	}
   118  
   119  	select {
   120  	case <-c.ShutdownCh:
   121  		// Cancel our context so we can start gracefully exiting
   122  		ctxCancel()
   123  
   124  		// Notify the user
   125  		c.Ui.Output(outputInterrupt)
   126  
   127  		// Still get the result, since there is still one
   128  		select {
   129  		case <-c.ShutdownCh:
   130  			c.Ui.Error(
   131  				"Two interrupts received. Exiting immediately")
   132  			return 1
   133  		case <-op.Done():
   134  		}
   135  	case <-op.Done():
   136  		if err := op.Err; err != nil {
   137  			diags = diags.Append(err)
   138  		}
   139  	}
   140  
   141  	c.showDiagnostics(diags)
   142  	if diags.HasErrors() {
   143  		return 1
   144  	}
   145  
   146  	if detailed && !op.PlanEmpty {
   147  		return 2
   148  	}
   149  
   150  	return 0
   151  }
   152  
   153  func (c *PlanCommand) Help() string {
   154  	helpText := `
   155  Usage: terraform plan [options] [DIR-OR-PLAN]
   156  
   157    Generates an execution plan for Terraform.
   158  
   159    This execution plan can be reviewed prior to running apply to get a
   160    sense for what Terraform will do. Optionally, the plan can be saved to
   161    a Terraform plan file, and apply can take this plan file to execute
   162    this plan exactly.
   163  
   164    If a saved plan is passed as an argument, this command will output
   165    the saved plan contents. It will not modify the given plan.
   166  
   167  Options:
   168  
   169    -destroy            If set, a plan will be generated to destroy all resources
   170                        managed by the given configuration and state.
   171  
   172    -detailed-exitcode  Return detailed exit codes when the command exits. This
   173                        will change the meaning of exit codes to:
   174                        0 - Succeeded, diff is empty (no changes)
   175                        1 - Errored
   176                        2 - Succeeded, there is a diff
   177  
   178    -input=true         Ask for input for variables if not directly set.
   179  
   180    -lock=true          Lock the state file when locking is supported.
   181  
   182    -lock-timeout=0s    Duration to retry a state lock.
   183  
   184    -module-depth=n     Specifies the depth of modules to show in the output.
   185                        This does not affect the plan itself, only the output
   186                        shown. By default, this is -1, which will expand all.
   187  
   188    -no-color           If specified, output won't contain any color.
   189  
   190    -out=path           Write a plan file to the given path. This can be used as
   191                        input to the "apply" command.
   192  
   193    -parallelism=n      Limit the number of concurrent operations. Defaults to 10.
   194  
   195    -refresh=true       Update state prior to checking for differences.
   196  
   197    -state=statefile    Path to a Terraform state file to use to look
   198                        up Terraform-managed resources. By default it will
   199                        use the state "terraform.tfstate" if it exists.
   200  
   201    -target=resource    Resource to target. Operation will be limited to this
   202                        resource and its dependencies. This flag can be used
   203                        multiple times.
   204  
   205    -var 'foo=bar'      Set a variable in the Terraform configuration. This
   206                        flag can be set multiple times.
   207  
   208    -var-file=foo       Set variables in the Terraform configuration from
   209                        a file. If "terraform.tfvars" or any ".auto.tfvars"
   210                        files are present, they will be automatically loaded.
   211  `
   212  	return strings.TrimSpace(helpText)
   213  }
   214  
   215  func (c *PlanCommand) Synopsis() string {
   216  	return "Generate and show an execution plan"
   217  }