This is Part 7 of the Terraform Associate Exam Cram. It covers the following Terraform Associate Certification exam objectives:
< Prev:
Objective 6 - Use the core Terraform workflow
Next >:
Objective 8 - Read, generate, and modify configuration
local
backendThe primary purpose of Terraform state is to store bindings between objects in a remote system and resource instances declared in your configuration. When Terraform creates a remote object it will associate the identity of that remote object with a particular resource instance.
Backend defines where Terraform's state snapshots are stored. A given Terraform configuration can either specify a backend, integrate with HCP Terraform, or do neither and default to storing state locally.
If a configuration includes no backend
or cloud
block, Terraform defaults to using
the local
backend, which stores state in a file named terraform.tfstate
in the
current working directory.
Example local
Backend Configuration:
State locking happens automatically on all operations that could update Terraform state. This prevents potential corruptions caused by simultaneous write operations.
Locking is supported by most remote backends (e.g., S3 with DynamoDB, GCS, Terraform Cloud, Consul, AzureRM).
If state locking fails, Terraform will not continue and display an error.
The terraform force-unlock LOCK_ID
command allows you to manually remove a state lock, for example,
when automatic unlocking fails. Use the -force
option to proceed without a confirmation prompt.
Remote backends, cloud providers, and HCP Terraform generally require access credentials and some form of authentication.
Commonly used methods for providing credentials include:
Hard-coding credentials directly in Terraform configuration (inside required_providers
or
backend
blocks) is not recommended.
Backend Credentials
Use partial backend configuration when supplying backend access credentials.
That is, leave credential-related arguments unset in the backend
block and provide them using
other methods, such as:
~/.aws/credentials
.AWS_ACCESS_KEY_ID
/
AWS_SECRET_ACCESS_KEY
, GOOGLE_APPLICATION_CREDENTIALS
,
GOOGLE_BACKEND_CREDENTIALS
.terraform.tfvars
)
specified via the terraform init -backend-config=PATH
command line.
The values from the file are merged with what is in the configuration's backend
block.
Note that Terraform will include these values in both the backend configuration file
.terraform/terraform.tfstate
and plan files.terraform init -backend-config="KEY=VALUE"
command. The -backend-config="KEY=VALUE"
flag can be specified multiple times. Keep in
mind that many shells retain entered commands in a history file.-input=false
flag.
Note:
The local backend configuration file .terraform/terraform.tfstate
is different and entirely separate
from the Terraform state file terraform.tfstate
. Terraform stores the state file
(terraform.tfstate
) in the location defined by the backend configuration.
Provider Credentials
Terraform provider's documentation in the public Terraform Registry describes how
to configure credentials in the required_providers
block for any given provider.
Typically, resource providers can obtain necessary credentials from several sources, including:
HCP Terraform
The terraform login
command obtains an API token for HCP Terraform, Terraform Enterprise, or other host
that offers Terraform services. Use this command only in interactive scenarios.
Usage: terraform login [hostname]
If no hostname is provided, the default hostname is app.terraform.io
(HCP Terraform).
If not overridden by credentials helper settings in the CLI configuration, the terraform login
command writes credentials to local file .terraform.d/credentials.tfrc.json
.
The terraform logout [hostname]
command removes locally-stored credentials for specified hostname.
For unattended automated deployments configure credentials manually in the CLI configuration file.
Alternatively, use a host-specific environment variable to provide an API token.
Environment variable names should have the prefix TF_TOKEN_
added to the domain name, with periods
encoded as underscores. For example, the value of a variable named TF_TOKEN_app_terraform_io
will be
used when the CLI makes service requests to the hostname app.terraform.io
.
CLI Configuration File
The CLI configuration file configures per-user settings customizing Terraform CLI behaviors, which apply across all Terraform working directories.
The following credential settings can be set in the CLI configuration file (.terraformrc
or
terraform.rc
):
credentials
- configures credentials for use with HCP Terraform or Terraform Enterprise.credentials_helper
- configures an external helper program for the storage and retrieval of
credentials for HCP Terraform or Terraform Enterprise.Backends define where Terraform's state snapshots are stored. A given Terraform configuration can either specify a backend, integrate with HCP Terraform, or default to storing state locally.
Use remote backend when multiple individuals or teams need access to the infrastructure state data.
Backends
Terraform includes a selection of built-in backends:
Terraform v1.3 removed support for the following backends:
Additional backends cannot be added as plugins.
Backends are configured with a backend
block nested within the top-level terraform
block:
The block label of the backend
block indicates which backend type to use (s3
). The arguments
used in the block's body are specific to the chosen backend type (bucket
, key
, region
).
They configure where and how the backend will store the configuration's state, and in some cases configure other behavior.
A configuration can only include one backend
block.
A backend block cannot refer to named values (like input variables, locals, or data source attributes).
Terraform Cloud / HCP Terraform
HCP Terraform offers secure remote state storage and makes it easier to collaborate on infrastructure development.
To use HCP Terraform as a backend, include a cloud
block within the top-level terraform
block:
A configuration can only include one cloud
block and the cloud
block cannot refer to named
values like input variables, locals, or data source attributes.
Drift occurs when real infrastructure gets out of sync with Terraform state, usually due to manual changes, external updates, etc.
By default, Terraform compares the state file to real infrastructure every time terraform plan
or
terraform apply
is invoked. First, Terraform performs in-memory state refresh to reflect
the actual configuration of the infrastructure. This ensures that Terraform determines the correct changes to
include in the plan. When the plan is applied (with terraform apply
), Terraform will update both,
the infrastructure and the state file.
The -refresh-only
and -refresh
plan customization options alow to control
Terraform refresh behavior.
The -refresh-only
options instructs Terraform to create a plan that updates the Terraform state
to match changes made to remote infrastructure objects outside of Terraform (i.e., a plan to bring the changes
into state). This allows you to review the proposed changed before applying.
Run terraform plan -refresh-only
to determine the drift between the current state file and actual
infrastructure.
Update the state with terraform apply -refresh-only
. Applying a refresh-only plan does not result
in changes to the infrastructure.
The -refresh=false
options disables the default behavior of refreshing state while creating the plan.
This can potentially make planning faster, but with the risk of planning against an outdated state.
Related Command:
The terraform refresh
command reads the current settings from all managed remote objects and
updates the Terraform state to match. It automatically overwrite the state file without giving you the
option to review the modifications first. This command is deprecated. Instead, use the -refresh-only
flag with terraform apply
and terraform plan
commands.
backend
block and cloud integration in configurationBackends
Backends are configured with a backend
block nested within the top-level terraform
block:
The block label of the backend
block indicates which backend type to use. The arguments used in the
block's body are specific to the chosen backend type. They configure where and how the backend will store the
configuration's state, access credentials, and other backend-specific parameters.
The following should be taken into account when configuring backends:
backend
block.backend
block cannot refer to named values (e.g., variables, locals, or data source attributes).terraform init -migrate-state
).backend
blocks is not recommended.
Use partial backend configuration and supply the sensitive values through environment variables, credential files, etc.Terraform Cloud / HCP Terraform
The cloud
block is a nested block within the top-level terraform
block. It specifies which
HCP Terraform workspaces to use for the current working directory.
The following should be taken into account when configuring cloud
blocks:
cloud
block.cloud
block cannot be used with state backends. A configuration can use one or the other, but not both.cloud
block cannot refer to named values (e.g., input variables, locals, data source attributes).Workspaces
The Terraform CLI workspaces are different from workspaces in HCP Terraform. Terraform CLI workspaces allow multiple state files to exist within a single directory, letting you use one configuration for multiple environments. HCP Terraform workspaces contain everything needed to manage a given set of infrastructure, and function like separate working directories.
Terraform CLI workspaces
default
.prefix
or key
attribute.${terraform.workspace}
.terraform workspace
commands.
terraform workspace
commands:
terraform workspace new NAME
- Create a new workspace. Use the -state=path
flag to copy an existing state file into the new workspace.terraform workspace list
- Show all workspaces.terraform workspace show
- Display the name of the current workspace.terraform workspace select NAME
- Switch to an existing workspace.terraform workspace delete NAME
- Delete a workspace (except default
).HCP Terraform workspaces
Terraform stores the state as plain text, including variable values, even if you have flagged them as
sensitive
.
Recommendations for handling sensitive data in state:
Note, Terraform masks the outputs with sensitive = true
, but still stores the values in state in plain text.
terraform workspace
command?
terraform workspace new <name>
?
terraform workspace select
command?
terraform state show
command do?
terraform state mv
command?
terraform state pull
command do?
< Prev:
Objective 6 - Use the core Terraform workflow
Next >:
Objective 8 - Read, generate, and modify configuration
More Terraform Tutorials:
Terraform Associate Exam Cram
Understanding Terraform Variable Precedence
Terraform Value Types Tutorial
Terraform count
Explained with Practical Examples
Terraform for_each
Tutorial with Practical Examples
Exploring Terraform dynamic
Blocks with GCP Examples
Working with External Data in Terraform
Terraform Modules FAQ