Terraform force apply

Terraform force apply DEFAULT

» Command: refresh

The command reads the current settings from all managed remote objects and updates the Terraform state to match.

Warning: This command is deprecated, because its default behavior is unsafe if you have misconfigured credentials for any of your providers. See below for more information and recommended alternatives.

This won't modify your real remote objects, but it will modify the the Terraform state.

You shouldn't typically need to use this command, because Terraform automatically performs the same refreshing actions as a part of creating a plan in both the and commands. This command is here primarily for backward compatibility, but we don't recommend using it because it provides no opportunity to review the effects of the operation before updating the state.

» Usage


This command is effectively an alias for the following command:

Consequently, it supports all of the same options as except that it does not accept a saved plan file, it doesn't allow selecting a planning mode other than "refresh only", and is always enabled.

Automatically applying the effect of a refresh is risky, because if you have misconfigured credentials for one or more providers then the provider may be misled into thinking that all of the managed objects have been deleted, and thus remove all of the tracked objects without any confirmation prompt.

Instead, we recommend using the following command in order to get the same effect but with the opportunity to review the the changes that Terraform has detected before committing them to the state:

This alternative command will present an interactive prompt for you to confirm the detected changes.

The option for and was introduced in Terraform v0.15.4. For prior versions you must use directly if you need this behavior, while taking into account the warnings above. Wherever possible, avoid using explicitly and instead rely on Terraform's behavior of automatically refreshing existing objects as part of creating a normal plan.

Sours: https://www.terraform.io/docs/cli/commands/refresh.html

» Command: plan

Hands-on: Try the Terraform: Get Started collection on HashiCorp Learn.

The command creates an execution plan. By default, creating a plan consists of:

  • Reading the current state of any already-existing remote objects to make sure that the Terraform state is up-to-date.
  • Comparing the current configuration to the prior state and noting any differences.
  • Proposing a set of change actions that should, if applied, make the remote objects match the configuration.

The plan command alone will not actually carry out the proposed changes, and so you can use this command to check whether the proposed changes match what you expected before you apply the changes or share your changes with your team for broader review.

If Terraform detects that no changes are needed to resource instances or to root module output values, will report that no actions need to be taken.

If you are using Terraform directly in an interactive terminal and you expect to apply the changes Terraform proposes, you can alternatively run directly. By default, the "apply" command automatically generates a new plan and prompts for you to approve it.

You can use the optional option to save the generated plan to a file on disk, which you can later execute by passing the file to as an extra argument. This two-step workflow is primarily intended for when running Terraform in automation.

If you run without the option then it will create a speculative plan, which is a description of a the effect of the plan but without any intent to actually apply it.

In teams that use a version control and code review workflow for making changes to real infrastructure, developers can use speculative plans to verify the effect of their changes before submitting them for code review. However, it's important to consider that other changes made to the target system in the meantime might cause the final effect of a configuration change to be different than what an earlier speculative plan indicated, so you should always re-check the final non-speculative plan before applying to make sure that it still matches your intent.

» Usage


The subcommand looks in the current working directory for the root module configuration.

Because the plan command is one of the main commands of Terraform, it has a variety of different options, described in the following sections. However, most of the time you should not need to set any of these options, because a Terraform configuration should typically be designed to work with no special additional options for routine work.

The remaining sections on this page describe the various options:

  • Planning Modes: There are some special alternative planning modes that you can use for some special situations where your goal is not just to change the remote system to match your configuration.
  • Planning Options: Alongside the special planning modes, there are also some options you can set in order to customize the planning process for unusual needs.
    • Resource Targeting is one particular special planning option that has some important caveats associated with it.
  • Other Options: These change the behavior of the planning command itself, rather than customizing the content of the generated plan.

» Planning Modes

The section above described Terraform's default planning behavior, which is intended for changing the remote system to match with changes you've made to your configuration.

Terraform has two alternative planning modes, each of which creates a plan with a different intended outcome:

  • Destroy mode: creates a plan whose goal is to destroy all remote objects that currently exist, leaving an empty Terraform state. This can be useful for situations like transient development environments, where the managed objects cease to be useful once the development task is complete.

    Activate destroy mode using the command line option.

  • Refresh-only mode: creates a plan whose goal is only to update the Terraform state and any root module output values to match changes made to remote objects outside of Terraform. This can be useful if you've intentionally changed one or more remote objects outside of the usual workflow (e.g. while responding to an incident) and you now need to reconcile Terraform's records with those changes.

    Activate refresh-only mode using the command line option.

In situations where we need to discuss the default planning mode that Terraform uses when none of the alternative modes are selected, we refer to it as "Normal mode". Because these alternative modes are for specialized situations only, some other Terraform documentation only discusses the normal planning mode.

The planning modes are all mutually-exclusive, so activating any non-default planning mode disables the "normal" planning mode, and you can't use more than one alternative mode at the same time.

Note: In Terraform v0.15 and earlier, the option is supported only by the command, and not by the command. To create and apply a plan in destroy mode in earlier versions you must run .

Note: The option is available only in Terraform v0.15.4 and later.

» Planning Options

In addition to the planning modes described above, there are also several additional options that can modify details of the behavior of the planning step.

When you use without passing it a saved plan file, it incorporates the command functionality and so the planning options in this section, along with the planning mode selection options in the previous section, are also available with the same meanings on .

  • - Disables the default behavior of synchronizing the Terraform state with remote objects before checking for configuration changes.

    This option can potentially make the planning operation faster by reducing the number of remote API requests, but it comes at the expense of having Terraform not take into account any changes that might've happened outside of Terraform, and thus the resulting plan may not be complete or correct.

    This option is not available in the "refresh only" planning mode, because it would effectively disable the entirety of the planning operation in that case.

  • - Instructs Terraform to plan to replace the single resource instance with the given address. If the given instance would normally have caused only an "update" action, or no action at all, then Terraform will choose a "replace" action instead.

    You can use this option if you have learned that a particular remote object has become degraded in some way. If you are using immutable infrastructure patterns then you may wish to respond to that by replacing the malfunctioning object with a new object that has the same configuration.

    This option is allowed only in the normal planning mode, so this option is incompatible with the option.

    The option is available only from Terraform v0.15.2 onwards. For earlier versions, you can achieve a similar effect (with some caveats) using .

  • - Instructs Terraform to focus its planning efforts only on resource instances which match the given address and on any objects that those instances depend on.

    This command is for exceptional use only. See Resource Targeting below for more information.

  • - Sets a value for a single input variable declared in the root module of the configuration. Use this option multiple times to set more than one variable. For more information see Input Variables on the Command Line, below.

  • - Sets values for potentially many input variables declared in the root module of the configuration, using definitions from a "tfvars" file. Use this option multiple times to include values from more than one file.

There are several other ways to set values for input variables in the root module, aside from the and options. For more information, see Assigning Values to Root Module Variables.

» Input Variables on the Command Line

You can use the command line option to specify values for input variables declared in your root module.

However, to do so will require writing a command line that is parsable both by your chosen command line shell and Terraform, which can be complicated for expressions involving lots of quotes and escape sequences. In most cases we recommend using the option instead, and write your actual values in a separate file so that Terraform can parse them directly, rather than interpreting the result of your shell's parsing.

To use on a Unix-style shell on a system like Linux or macOS we recommend writing the option argument in single quotes to ensure the shell will interpret the value literally:

If your intended value also includes a single quote then you'll still need to escape that for correct interpretation by your shell, which also requires temporarily ending the quoted sequence so that the backslash escape character will be significant:

When using Terraform on Windows, we recommend using the Windows Command Prompt (). When you pass a variable value to Terraform from the Windows Command Prompt, use double quotes around the argument:

If your intended value includes literal double quotes then you'll need to escape those with a backslash:

PowerShell on Windows cannot correctly pass literal quotes to external programs, so we do not recommend using Terraform with PowerShell when you are on Windows. Use Windows Command Prompt instead.

The appropriate syntax for writing the variable value is different depending on the variable's type constraint. The primitive types , , and all expect a direct string value with no special punctuation except that required by your shell, as shown in the above examples. For all other type constraints, including list, map, and set types and the special keyword, you must write a valid Terraform language expression representing the value, and write any necessary quoting or escape characters to ensure it will pass through your shell literally to Terraform. For example, for a type constraint:

Similar constraints apply when setting input variables using environment variables. For more information on the various methods for setting root module input variables, see Assigning Values to Root Module Variables.

» Resource Targeting

Hands-on: Try the Target resources tutorial on HashiCorp Learn.

You can use the option to focus Terraform's attention on only a subset of resources. You can use resource address syntax to specify the constraint. Terraform interprets the resource address as follows:

  • If the given address identifies one specific resource instance, Terraform will select that instance alone. For resources with either or set, a resource instance address must include the instance index part, like .

  • If the given address identifies a resource as a whole, Terraform will select all of the instances of that resource. For resources with either or set, this means selecting all instance indexes currently associated with that resource. For single-instance resources (without either or ), the resource address and the resource instance address are identical, so this possibility does not apply.

  • If the given address identifies an entire module instance, Terraform will select all instances of all resources that belong to that module instance and all of its child module instances.

Once Terraform has selected one or more resource instances that you've directly targeted, it will also then extend the selection to include all other objects that those selections depend on either directly or indirectly.

This targeting capability is provided for exceptional circumstances, such as recovering from mistakes or working around Terraform limitations. It is not recommended to use for routine operations, since this can lead to undetected configuration drift and confusion about how the true state of resources relates to configuration.

Instead of using as a means to operate on isolated portions of very large configurations, prefer instead to break large configurations into several smaller configurations that can each be independently applied. Data sources can be used to access information about resources created in other configurations, allowing a complex system architecture to be broken down into more manageable parts that can be updated independently.

» Other Options

The command also has some other options that are related to the input and output of the planning command, rather than customizing what sort of plan Terraform will create. These commands are not necessarily also available on , unless otherwise stated in the documentation for that command.

The available options are:

  • - Shows any warning messages in a compact form which includes only the summary messages, unless the warnings are accompanied by at least one error and thus the warning text might be useful context for the errors.

  • - Returns a detailed exit code when the command exits. When provided, this argument changes the exit codes and their meanings to provide more granular information about what the resulting plan contains:

    • 0 = Succeeded with empty diff (no changes)
    • 1 = Error
    • 2 = Succeeded with non-empty diff (changes present)
  • - Disables Terraform's default behavior of prompting for input for root module input variables that have not otherwise been assigned a value. This option is particular useful when running Terraform in non-interactive automation systems.

  • - Enables the machine readable JSON UI output. This implies , so the configuration must have no unassigned variable values to continue.

  • - Don't hold a state lock during the operation. This is dangerous if others might concurrently run commands against the same workspace.

  • - Unless locking is disabled with , instructs Terraform to retry acquiring a lock for a period of time before returning an error. The duration syntax is a number followed by a time unit letter, such as "3s" for three seconds.

  • - Disables terminal formatting sequences in the output. Use this if you are running Terraform in a context where its output will be rendered by a system that cannot interpret terminal formatting.

  • - Writes the generated plan to the given filename in an opaque file format that you can later pass to to execute the planned changes, and to some other Terraform commands that can work with saved plan files.

    Terraform will allow any filename for the plan file, but a typical convention is to name it . Do not name the file with a suffix that Terraform recognizes as another file format; if you use a suffix then Terraform will try to interpret the file as a configuration source file, which will then cause syntax errors for subsequent commands.

    The generated file is not in any standard format intended for consumption by other software, but the file does contain your full configuration, all of the values associated with planned changes, and all of the plan options including the input variables. If your plan includes any sort of sensitive data, even if obscured in Terraform's terminal output, it will be saved in cleartext in the plan file. You should therefore treat any saved plan files as potentially-sensitive artifacts.

  • - Limit the number of concurrent operation as Terraform walks the graph. Defaults to 10.

For configurations using the backend only, accepts the legacy command line option .

» Passing a Different Configuration Directory

Terraform v0.13 and earlier accepted an additional positional argument giving a directory path, in which case Terraform would use that directory as the root module instead of the current working directory.

That usage was deprecated in Terraform v0.14 and removed in Terraform v0.15. If your workflow relies on overriding the root module directory, use the global option instead, which works across all commands and makes Terraform consistently look in the given directory for all files it would normaly read or write in the current working directory.

If your previous use of this legacy pattern was also relying on Terraform writing the subdirectory into the current working directory even though the root module directory was overridden, use the environment variable to direct Terraform to write the directory to a location other than the current working directory.

Sours: https://www.terraform.io/docs/cli/commands/plan.html
  1. Hand water pump tractor supply
  2. Seeker trolling rod
  3. Home depot cabinet refacing colors

» Command: taint

The command informs Terraform that a particular object has become degraded or damaged. Terraform represents this by marking the object as "tainted" in the Terraform state, in which case Terraform will propose to replace it in the next plan you create.

Warning: This command is deprecated, because there are better alternatives available in Terraform v0.15.2 and later. See below for more details.

If your intent is to force replacement of a particular object even though there are no configuration changes that would require it, we recommend instead to use the option with . For example:

Creating a plan with the "replace" option is superior to using because it will allow you to see the full effect of that change before you take any externally-visible action. When you use to get a similar effect, you risk someone else on your team creating a new plan against your tainted object before you've had a chance to review the consequences of that change yourself.

The option to is only available from Terraform v0.15.2 onwards, so if you are using an earlier version you will need to use to force object replacement, while considering the caveats described above.

» Usage


The argument is the address of the resource to mark as tainted. The address is in the resource address syntax syntax, as shown in the output from other commands, such as:

This command accepts the following options:

  • - If specified, the command will succeed (exit code 0) even if the resource is missing. The command might still return an error for other situations, such as if there is a problem reading or writing the state.

  • - Disables Terraform's default behavior of attempting to take a read/write lock on the state for the duration of the operation.

  • - Unless locking is disabled with , instructs Terraform to retry acquiring a lock for a period of time before returning an error. The duration syntax is a number followed by a time unit letter, such as "3s" for three seconds.

For configurations using the backend only, also accepts the option .

For configurations using the backend only, also accepts the legacy options , , and .

Sours: https://www.terraform.io/docs/cli/commands/taint.html
Talk #37 - Terraform: infraestrutura como código

» Viewing and Managing Runs

Each workspace in Terraform Cloud includes a list of its current, pending, and historical runs. You can view information about these runs in the UI, and sometimes interact with them.

Additionally, you can lock workspaces to temporarily prevent new runs.

» Navigating Runs

Each workspace has two ways to view and navigate runs:

  • A "Runs" link, which goes to the full list of runs.
  • A "Current Run" link, which goes to the most recent active run. (This might not be the most recently initiated run, since runs in the "pending" state remain inactive until the current run is completed.)

runs list

From the list of runs, you can click to view or interact with an individual run.

» The Run Page

An individual run page shows the progress and outcomes of each stage of the run.

a run page

Most importantly, it shows:

  • The current status of the run.
  • The code commit associated with the run.
  • How the run was initiated, when, and which user initiated it (if applicable).
  • A timeline of events related to the run.
  • The output from both the and commands, if applicable. You can hide or reveal these as needed; they default to visible if the command is currently running, and hidden if the command has finished.

» Interacting with Runs

In workspaces where you have permission to apply runs, run pages include controls for interacting with the run at the bottom of the page. (More about permissions.) Depending on the state of the run, the following buttons might be available:

ButtonAvailable when:
Add CommentAlways.
Confirm & ApplyA plan needs confirmation.
Override & ContinueA soft-mandatory policy failed. Requires permission to manage policy overrides for the organization. (More about permissions.)
Discard RunA plan needs confirmation or a soft-mandatory policy failed.
Cancel RunA plan or apply is currently running.
Force Cancel RunA plan or apply was canceled, but something went wrong and Terraform Cloud couldn't end the run gracefully. Requires admin access to the workspace. (More about permissions.)

If a plan needs confirmation (with manual apply enabled) or a soft-mandatory policy failed, the run will remain paused until a user with appropriate permissions uses these buttons to continue or discard the run. For more details, see Run States and Stages.

» Canceling Runs

If a run is currently planning or applying, users with permission to apply runs for the workspace can cancel the run before it finishes, using the "Cancel Run" button on the run's page. (More about permissions.)

Canceling a run is roughly equivalent to hitting ctrl+c during a Terraform plan or apply on the CLI. The running Terraform process is sent an INT signal, which instructs Terraform to end its work and wrap up in the safest way possible. (This gives Terraform a chance to update state for any resources that have already been changed, among other things.)

In rare cases, a cancelled run can fail to end gracefully, and will continue to lock the workspace without accomplishing anything useful. These stuck runs can be force-canceled, which immediately terminates the running Terraform process and unlocks the workspace.

Since force-canceling can have dangerous side-effects (including loss of state and orphaned resources), it requires admin access to the workspace. (More about permissions.) Additionally, the "Force Cancel Run" button only appears after the normal cancel button has been used and a cool-off period has elapsed, to ensure Terraform Cloud has a chance to terminate the run safely.

» Locking Workspaces (Preventing Runs)

If you need to temporarily stop runs from being queued, you can lock the workspace.

A lock prevents Terraform Cloud from performing any plans or applies in the workspace. This includes automatic runs due to new commits in the VCS repository, manual runs queued via the UI, runs started on the command line with and , and runs created with the API. New runs remain in the "Pending" state until the workspace is unlocked.

The current lock status is shown in the workspace header, near the "Actions" menu.

You can find the lock button in the "Actions" menu in a workspace's header, or in the workspace settings page. Locking a workspace requires permission to lock and unlock the workspace. (More about permissions.)

Sours: https://www.terraform.io/docs/cloud/run/manage.html

Apply terraform force

Running Terraform in Automation

This is an advanced guide! When getting started with Terraform, it's recommended to use it locally from the command line. Automation can become valuable once Terraform is being used regularly in production, or by a larger team, but this guide assumes familiarity with the normal, local CLI workflow.

For teams that use Terraform as a key part of a change management and deployment pipeline, it can be desirable to orchestrate Terraform runs in some sort of automation in order to ensure consistency between runs, and provide other interesting features such as integration with version control hooks.

Automation of Terraform can come in various forms, and to varying degrees. Some teams continue to run Terraform locally but use wrapper scripts to prepare a consistent working directory for Terraform to run in, while other teams run Terraform entirely within an orchestration tool such as Jenkins.

This tutorial covers some things that should be considered when implementing such automation, both to ensure safe operation of Terraform and to accommodate some current limitations in Terraform's workflow that require careful attention in automation. It assumes that Terraform will be running in an non-interactive environment, where it is not possible to prompt for input at the terminal. This is not necessarily true for wrapper scripts, but is often true when running in orchestration tools.

This tutorial's goal is to give an overview of things to consider when automating the standard Terraform workflows. The other tutorials in this collection will guide you through implementing the concepts discussed in this tutorial.

  1. The Deploy Terraform infrastructure with CircleCI tutorial guides you through automating the standard Terraform workflow using AWS S3 as a backend. This approach uses the Docker image to run Terraform locally in each CircleCI job.

  2. The Automate Terraform with GitHub Actions tutorial guides you through automating the standard Terraform Cloud workflow. This approach leverages Terraform Cloud for remote runs and state management. While Terraform Cloud offers version control system integrations, including GitHub, this approach enables you to add status checks before or after Terraform Cloud remote runs are triggered, better adapting Terraform Cloud to your use case.

»Automated Terraform CLI Workflow

When running Terraform in automation, the focus is usually on the core plan/apply cycle. The main path, then, is broadly the same as for CLI usage:

  1. Initialize the Terraform working directory.
  2. Produce a plan for changing resources to match the current configuration.
  3. Have a human operator review that plan, to ensure it is acceptable.
  4. Apply the changes described by the plan.

Steps 1, 2 and 4 can be carried out using the familiar Terraform CLI commands, with some additional options:

The option indicates that Terraform should not attempt to prompt for input, and instead expect all necessary values to be provided by either configuration files or the command line. It may therefore be necessary to use the and options on to specify any variable values that would traditionally have been manually-entered under interactive usage.

It is strongly recommended to use a backend that supports remote state, since that allows Terraform to automatically save the state in a persistent location where it can be found and updated by subsequent runs. Selecting a backend that supports state locking will additionally provide safety against race conditions that can be caused by concurrent Terraform runs.

»Controlling Terraform Output in Automation

By default, some Terraform commands conclude by presenting a description of a possible next step to the user, often including a specific command to run next.

An automation tool will often abstract away the details of exactly which commands are being run, causing these messages to be confusing and un-actionable, and possibly harmful if they inadvertently encourage a user to bypass the automation tool entirely.

When the environment variable is set to any non-empty value, Terraform makes some minor adjustments to its output to de-emphasize specific commands to run. The specific changes made will vary over time, but generally-speaking Terraform will consider this variable to indicate that there is some wrapping application that will help the user with the next step.

To reduce complexity, this feature is implemented primarily for the main workflow commands described above. Other ancillary commands may still produce command line suggestions, regardless of this setting.

»Plan and Apply on different machines

When running in an orchestration tool, it can be difficult or impossible to ensure that the and subcommands are run on the same machine, in the same directory, with all of the same files present.

Running and on different machines requires some additional steps to ensure correct behavior. A robust strategy is as follows:

  • After completes, archive the entire working directory, including the subdirectory created during , and save it somewhere where it will be available to the apply step. A common choice is as a "build artifact" within the chosen orchestration tool.
  • Before running , obtain the archive created in the previous step and extract it at the same absolute path. This re-creates everything that was present after plan, avoiding strange issues where local files were created during the plan step.

Terraform currently makes some assumptions which must be accommodated by such an automation setup:

  • The saved plan file can contain absolute paths to child modules and other data files referred to by configuration. Therefore it is necessary to ensure that the archived configuration is extracted at an identical absolute path. This is most commonly achieved by running Terraform in some sort of isolation, such as a Docker container, where the filesystem layout can be controlled.
  • Terraform assumes that the plan will be applied on the same operating system and CPU architecture as where it was created. For example, this means that it is not possible to create a plan on a Windows computer and then apply it on a Linux server.
  • Terraform expects the provider plugins that were used to produce a plan to be available and identical when the plan is applied, to ensure that the plan is interpreted correctly. An error will be produced if Terraform or any plugins are upgraded between creating and applying a plan.
  • Terraform can't automatically detect if the credentials used to create a plan grant access to the same resources used to apply that plan. If using different credentials for each (e.g. to generate the plan using read-only credentials) it is important to ensure that the two are consistent in which account on the corresponding service they belong to.

The plan file contains a full copy of the configuration, the state that the plan applies to, and any variables passed to . If any of these contain sensitive data then the archived working directory containing the plan file should be protected accordingly. For provider authentication credentials, it is recommended to use environment variables instead where possible since these are not included in the plan or persisted to disk by Terraform in any other way.

»Interactive Approval of Plans

Another challenge with automating the Terraform workflow is the desire for an interactive approval step between plan and apply. To implement this robustly, it is important to ensure that either only one plan can be outstanding at a time or that the two steps are connected such that approving a plan passes along enough information to the apply step to ensure that the correct plan is applied, as opposed to some later plan that also exists.

Different orchestration tools address this in different ways, but generally this is implemented via a build pipeline feature, where different steps can be applied in sequence, with later steps having access to data produced by earlier steps.

The recommended approach is to allow only one plan to be outstanding at a time. When a plan is applied, any other existing plans that were produced against the same state are invalidated, since they must now be recomputed relative to the new state. By forcing plans to be approved (or dismissed) in sequence, this can be avoided.

»Auto-Approval of Plans

While manual review of plans is strongly recommended for production use-cases, it is sometimes desirable to take a more automatic approach when deploying in pre-production or development situations.

Where manual approval is not required, a simpler sequence of commands can be used:

This variant of the command implicitly creates a new plan and then immediately applies it. The option tells Terraform not to require interactive approval of the plan before applying it.

When Terraform is empowered to make destructive changes to infrastructure, manual review of plans is always recommended unless downtime is tolerated in the event of unintended changes. Use automatic approval only with non-critical infrastructure.

»Testing Pull Requests with terraform plan

can be used as a way to perform certain limited verification of the validity of a Terraform configuration, without affecting real infrastructure. Although the plan step updates the state to match real resources, thus ensuring an accurate plan, the updated state is not persisted, and so this command can safely be used to produce "throwaway" plans that are created only to aid in code review.

When implementing such a workflow, hooks can be used within the code review tool in question (for example, Github Pull Requests) to trigger an orchestration tool for each new commit under review. Terraform can be run in this case as follows:

As in the "main" workflow, it may be necessary to provide or as appropriate. The option is not used in this scenario because a plan produced for code review purposes will never be applied. Instead, a new plan can be created and applied from the primary version control branch once the change is merged.

Beware that passing sensitive/secret data to Terraform via variables or via environment variables will make it possible for anyone who can submit a PR to discover those values, so this flow must be used with care on an open source project, or on any private project where some or all contributors should not have direct access to credentials, etc.

»Multi-environment Deployment

Automation of Terraform often goes hand-in-hand with creating the same configuration multiple times to produce parallel environments for use-cases such as pre-release testing or multi-tenant infrastructure. Automation in such a situation can help ensure that the correct settings are used for each environment, and that the working directory is properly configured before each operation.

The two most interesting commands for multi-environment orchestration are and . The former can be used with additional options to tailor the backend configuration for any differences between environments, while the latter can be used to safely switch between multiple states for the same config stored in a single backend.

Where possible, it's recommended to use a single backend configuration for all environments and use the command to switch between workspaces:

In this usage model, a fixed naming scheme is used within the backend storage to allow multiple states to exist without any further configuration.

Alternatively, the automation tool can set the environment variable to an existing workspace name, which overrides any selection made with the command. Using this environment variable is recommended only for non-interactive usage, since in a local shell environment it can be easy to forget the variable is set and apply changes to the wrong state.

In some more complex situations it is impossible to share the same backend configuration across environments. For example, the environments may exist in entirely separate accounts within the target service, and thus need to use different credentials or endpoints for the backend itself. In such situations, backend configuration settings can be overridden via the option to .

»Pre-installed Plugins

In default usage, downloads and installs the plugins for any providers used in the configuration automatically, placing them in a subdirectory of the directory. This affords a simpler workflow for straightforward cases, and allows each configuration to potentially use different versions of plugins.

In automation environments, it can be desirable to disable this behavior and instead provide a fixed set of plugins already installed on the system where Terraform is running. This then avoids the overhead of re-downloading the plugins on each execution, and allows the system administrator to control which plugins are available.

To use this mechanism, create a directory somewhere on the system where Terraform will run and place into it the plugin executable files. The plugin release archives are available for download on releases.hashicorp.com. Be sure to download the appropriate archive for the target operating system and architecture.

After extracting the necessary plugins, the contents of the new plugin directory will look something like this:

$ls -lah /usr/lib/custom-terraform-plugins-rwxrwxr-x 1 user user 84M Jun 13 15:13 terraform-provider-aws-v1.0.0-x3-rwxrwxr-x 1 user user 84M Jun 13 15:15 terraform-provider-rundeck-v2.3.0-x3-rwxrwxr-x 1 user user 84M Jun 13 15:15 terraform-provider-mysql-v1.2.0-x3

The version information at the end of the filenames is important so that Terraform can infer the version number of each plugin. Multiple versions of the same provider plugin can be installed, and Terraform will use the newest one that matches the provider version constraints in the Terraform configuration.

With this directory populated, the usual auto-download and plugin discovery behavior can be bypassed using the option to :

When this option is used, only the plugins in the given directory are available for use. This gives the system administrator a high level of control over the execution environment, but on the other hand it prevents use of newer plugin versions that have not yet been installed into the local plugin directory. Which approach is more appropriate will depend on unique constraints within each organization.

Plugins can also be provided along with the configuration by creating a directory, which will be searched before automatically downloading additional plugins. The flag can be used to prevent Terraform from automatically downloading additional plugins.

»Terraform Cloud

As an alternative to home-grown automation solutions, Hashicorp offers Terraform Cloud.

Internally, Terraform Cloud runs the same Terraform CLI commands described above, using the same release binaries offered for download on this site.

Terraform Cloud builds on the core Terraform CLI functionality to add additional features such as role-based access control, orchestration of the plan and apply lifecycle, a user interface for reviewing and approving plans, and much more.

It will always be possible to run Terraform via in-house automation, to allow for usage in situations where Terraform Cloud is not appropriate. It is recommended to consider Terraform Cloud as an alternative to in-house solutions, since it provides an out-of-the-box solution that already incorporates the best practices described in this guide and can thus reduce time spent developing and maintaining an in-house alternative.

Sours: https://learn.hashicorp.com/tutorials/terraform/automate-terraform
Terraform explained in 15 mins - Terraform Tutorial for Beginners

» Provisioning Infrastructure with Terraform

Terraform's primary function is to create, modify, and destroy infrastructure resources to match the desired state described in a Terraform configuration.

When people refer to "running Terraform," they generally mean performing these provisioning actions in order to affect real infrastructure objects. The Terraform binary has many other subcommands for a wide variety of administrative actions, but these basic provisioning tasks are the core of Terraform.

Terraform's provisioning workflow relies on three commands: , , and . All of these commands require an initialized working directory, and all of them act only upon the currently selected workspace.

» Planning

The command evaluates a Terraform configuration to determine the desired state of all the resources it declares, then compares that desired state to the real infrastructure objects being managed with the current working directory and workspace. It uses state data to determine which real objects correspond to which declared resources, and checks the current state of each resource using the relevant infrastructure provider's API.

Once it has determined the difference between the current state and the desired state, presents a description of the changes necessary to achieve the desired state. It does not perform any actual changes to real world infrastructure objects; it only presents a plan for making changes.

Plans are usually run to validate configuration changes and confirm that the resulting actions are as expected. However, can also save its plan as a runnable artifact, which can use to carry out those exact changes.

For details, see the command.

» Applying

The command performs a plan just like does, but then actually carries out the planned changes to each resource using the relevant infrastructure provider's API. It asks for confirmation from the user before making any changes, unless it was explicitly told to skip approval.

By default, performs a fresh plan right before applying changes, and displays the plan to the user when asking for confirmation. However, it can also accept a plan file produced by in lieu of running a new plan. You can use this to reliably perform an exact set of pre-approved changes, even if the configuration or the state of the real infrastructure has changed in the minutes since the original plan was created.

For details, see the command.

» Destroying

The command destroys all of the resources being managed by the current working directory and workspace, using state data to determine which real world objects correspond to managed resources. Like , it asks for confirmation before proceeding.

A destroy behaves exactly like deleting every resource from the configuration and then running an apply, except that it doesn't require editing the configuration. This is more convenient if you intend to provision similar resources at a later date.

For details, see the command.

Sours: https://www.terraform.io/docs/cli/run/index.html

Similar news:

» Command: apply

Hands-on: Try the Terraform: Get Started collection on HashiCorp Learn.

The command executes the actions proposed in a Terraform plan.

The most straightforward way to use is to run it without any arguments at all, in which case it will automatically create a new execution plan (as if you had run ) and then prompt you to approve that plan, before taking the indicated actions.

Another way to use is to pass it the filename of a saved plan file you created earlier with , in which case Terraform will apply the changes in the plan without any confirmation prompt. This two-step workflow is primarily intended for when running Terraform in automation.

» Usage


The behavior of differs significantly depending on whether you pass it the filename of a previously-saved plan file.

» Automatic Plan Mode

In the default case, with no saved plan file, creates its own plan of action, in the same way that would.

Terraform will propose the plan to you and prompt you to approve it before taking the described actions, unless you waive that prompt by using the option.

When performing its own plan, supports all of the same planning modes and planning options that would accept, so you can customize how Terraform will create the plan.

» Saved Plan Mode

If you pass the filename of a previously-saved plan file, performs exactly the steps specified by that plan file. It does not prompt for approval; if you want to inspect a plan file before applying it, you can use .

When using a saved plan, none of the planning modes or planning options linked above are supported; these options only affect Terraform's decisions about which actions to take, and the plan file contains the final results of those decisions.

» Plan Options

When run without a saved plan file, supports all of 's planning modes and planning options. For details, see:

» Apply Options

The following options allow you to change various details about how the apply command executes and reports on the apply operation. If you are running without a previously-saved plan file, these options are in addition to the planning modes and planning options described for .

  • - Skips interactive approval of plan before applying. This option is ignored when you pass a previously-saved plan file, because Terraform considers you passing the plan file as the approval and so will never prompt in that case.

  • - Shows any warning messages in a compact form which includes only the summary messages, unless the warnings are accompanied by at least one error and thus the warning text might be useful context for the errors.

  • - Disables all of Terraform's interactive prompts. Note that this also prevents Terraform from prompting for interactive approval of a plan, so Terraform will conservatively assume that you do not wish to apply the plan, causing the operation to fail. If you wish to run Terraform in a non-interactive context, see Running Terraform in Automation for some different approaches.

  • - Enables the machine readable JSON UI output. This implies , so the configuration must have no unassigned variable values to continue. To enable this flag, you must also either enable the flag or specify a previously-saved plan.

  • - Don't hold a state lock during the operation. This is dangerous if others might concurrently run commands against the same workspace.

  • - Unless locking is disabled with , instructs Terraform to retry acquiring a lock for a period of time before returning an error. The duration syntax is a number followed by a time unit letter, such as "3s" for three seconds.

  • - Disables terminal formatting sequences in the output. Use this if you are running Terraform in a context where its output will be rendered by a system that cannot interpret terminal formatting.

  • - Limit the number of concurrent operation as Terraform walks the graph. Defaults to 10.

For configurations using the backend only, also accepts the legacy options , , and .

» Passing a Different Configuration Directory

Terraform v0.13 and earlier also accepted a directory path in place of the plan file argument to , in which case Terraform would use that directory as the root module instead of the current working directory.

That usage was deprecated in Terraform v0.14 and removed in Terraform v0.15. If your workflow relies on overriding the root module directory, use the global option instead, which works across all commands and makes Terraform consistently look in the given directory for all files it would normaly read or write in the current working directory.

If your previous use of this legacy pattern was also relying on Terraform writing the subdirectory into the current working directory even though the root module directory was overridden, use the environment variable to direct Terraform to write the directory to a location other than the current working directory.

Sours: https://www.terraform.io/docs/cli/commands/apply.html

1258 1259 1260 1261 1262