Apply Terraform configuration
The core Terraform workflow consists of three main steps after you have written your Terraform configuration:
- Initialize prepares your workspace so Terraform can apply your configuration.
- Plan allows you to preview the changes Terraform will make before you apply them.
- Apply makes the changes defined by your plan to create, update, or destroy resources.
When you apply changes to your infrastructure, Terraform uses the providers and modules installed during initialization to execute the steps stored in an execution plan. These steps create, update, and delete infrastructure to match your resource configuration.
In this tutorial, you will apply example configuration and review the steps that
Terraform takes to apply changes. You will also learn how Terraform recovers
from errors during apply, and some common ways to use the apply
command.
Prerequisites
You can complete this tutorial using the same workflow with either Terraform Community Edition or HCP Terraform. HCP Terraform is a platform that you can use to manage and execute your Terraform projects. It includes features like remote state and execution, structured plan output, workspace resource summaries, and more.
Select the HCP Terraform tab to complete this tutorial using HCP Terraform.
This tutorial assumes that you are familiar with the Terraform workflow. If you are new to Terraform, complete the Get Started tutorials first.
In order to complete this tutorial, you will need the following:
- Terraform v1.6+ installed locally.
- An AWS account with local credentials configured for use with Terraform.
- The jq command line utility.
Clone the example repository
In your terminal, clone the learn-terraform-apply
repository.
Navigate to the cloned repository.
Review configuration
The example configuration in this repository creates an EC2 instance through
resources and local and public modules. The modules/aws-ec2-instance
subdirectory contains the local module used to create the instance.
Terraform uses the provider versions specified in the terraform.tf
file.
Open the main.tf
file. This file defines configuration for an EC2 instance and an S3 bucket.
In this example configuration, the aws_instance.main
resource depends on the
random_pet.instance
resource and the aws_ami.ubuntu
data source. When you
apply this configuration, Terraform will create the random_pet
resource and
populate the aws_ami
data source before it creates the instance.
Initialize your configuration
In order to generate your execution plan, Terraform needs to install the providers and modules referenced by your configuration. Then, it will reference them to create your plan.
Initialize the Terraform configuration with terraform init
.
Apply configuration
Apply the configuration.
Since you did not provide a saved plan, Terraform created a plan and asked you to approve it before making any changes to your resources.
When you approve the plan and apply this configuration, Terraform will:
- Lock your workspace's state, so that no other instances of Terraform will
attempt to modify your state or apply changes to your resources. If Terraform
detects an existing lock file (
.terraform.tfstate.lock.info
), it will report an error and exit. - Create a plan, and wait for you to approve it. Alternatively, you can provide
a saved plan created with the
terraform plan
command, in which case Terraform will not prompt for approval. - Execute the steps defined in the plan using the providers you installed when you initialized your configuration. Terraform executes steps in parallel when possible, and sequentially when one resource depends on another.
- Update your workspace's state with a snapshot of the new state of your resources.
- Unlock your workspace's state.
- Report the changes it made, as well as any output values defined in your configuration.
Respond to the confirmation prompt with a yes
to apply the proposed execution
plan.
When you applied the example configuration, Terraform created the random pet name and image resources first, and then created the four containers which depend on them in parallel. When Terraform creates a plan, it analyzes the dependencies between your resources so that it makes changes to your resources in the correct order, and in parallel when possible. When it applies your configuration, Terraform reports its progress as it creates, updates, and deletes your resources.
Errors during apply
When Terraform encounters an error during an apply step, it will:
- Log the error and report it to the console.
- Update the state file with any changes to your resources.
- Unlock the state file.
- Exit.
Your infrastructure may be in an invalid state after a Terraform apply step errors out. Terraform does not support automatically rolling back a partially-completed apply. After you resolve the error, you must apply your configuration again to update your infrastructure to the desired state.
To review how Terraform handles errors, introduce an intentional error during an apply.
Add the following configuration to main.tf
to create a new S3 object.
Create a saved plan for the new configuration.
Now, remove the bucket outside of Terraform. This will cause Terraform to error when you apply the plan since the plan assumes the bucket exists. Use either the AWS Console or the AWS CLI to remove the bucket.
Now apply the plan. Terraform will error out when it tries to create the
aws_s3_object.example
object.
Because you removed the S3 bucket after you created the plan, AWS was unable to create the object, so the AWS provider reported the error to Terraform.
Common reasons for apply errors include:
- A change to a resource outside of Terraform's control.
- Networking or other transient errors.
- An expected error from the upstream API, such as a duplicate resource name or reaching a resource limit.
- An unexpected error from the upstream API, such as an internal server error.
- A bug in the Terraform provider code, or Terraform itself.
Depending on the cause of the error, you may need to resolve the underlying issue by either modifying your configuration or diagnosing and resolving the error from the cloud provider API. Your Terraform project is still tracking the image resource because Terraform has not yet refreshed your resource's state.
Print out the state of your S3 bucket with terraform show
.
Terraform stores it's current understanding of the state of your resources,
either locally in the terraform.tfstate
file, or on a remote backend such as
HCP Terraform. You can use the terraform show
command to print out your
state. This command does not refresh your state, so the information in your
state can be out of date. In this case, your project's state reports the
existence of the S3 bucket you manually deleted earlier in this tutorial. When
you apply a plan, Terraform will only make changes defined in the plan. Because
of this, changes to your resources between the time you plan you changes and
attempt to apply them can cause Terraform to error if the plan can no longer be
applied as writted. To resolve this error, you must create and apply a new plan
that takes the missing bucket into account.
The next time you plan a change to this project, Terraform will update the
current state of your resources from the underlying APIs using the providers you
have installed. Terraform will notice that the bucket represented by the
aws_s3_bucket.example
resource no longer exists, and generate a plan to create
it before creating the new aws_s3_object.example
object.
Apply your configuration. Terraform will referesh your workspace's state to reflect the fact that the S3 bucket no longer exists. Next it will create a plan to reconcile your configuration with that state by creating both the S3 bucket and object. Resources can change outside of Terraform's control for any number of reasons. In most cases, Terraform can handle these differences automatically by creating, destroying, or updating resources to make them match your configuration. Terraform will create a plan to do so, and wait for you to confirm it.
Respond to the confirmation prompt with a yes
to provision the S3 bucket and
object.
In this case, you were able to recover from the error by re-applying your configuration. Depending on the underlying cause of the error, you may need to resolve the error outside of Terraform or by changing your Terraform configuration. For example, if Terraform reports a resource limit error from your cloud provider's API, you may need to work with your cloud provider to increase that limit before applying your configuration.
Replace Resources
When using Terraform, you will usually apply an entire configuration change at
once. Terraform and its providers will determine the changes to make and the
order to make them in. However, there are some cases where you may need to
replace or modify individual resources. Terraform provides two arguments to the
plan
and apply
commands that allow you to interact with specific resources:
-replace
and -target
.
Use the -replace
argument when a resource has become unhealthy or stops
working in ways that are outside of Terraform's control. For instance, an error
in your EC2 instance's OS configuration could require that the instance be
replaced. There is no corresponding change to your Terraform configuration, so
you want to instruct Terraform to reprovision the resource using the same
configuration.
The -replace
argument requires a resource address. List the resources in your
configuration with terraform state list
.
Replace the second EC2 instance. Respond to the confirmation prompt with a
yes
.
The second case where you may need to partially apply configuration is when
troubleshooting an error that prevents Terraform from applying your entire
configuration at once. This type of error may occur when a target API or
Terraform provider error leaves your resources in an invalid state that
Terraform cannot resolve automatically. Use the -target
command line argument
when you apply to target individual resources rather than apply the entire
configuration. Refer to the Target
resources tutorial for more
information.
Clean up infrastructure
Now that you have learned how Terraform applies changes to your infrastructure,
remove the resources you provisioned in this tutorial. Confirm the operation
with a yes
.
The terraform destroy
command is a shortcut which creates a destroy plan to
remove all of your resources, waits for your confirmation, and then applies the
plan.
Next steps
In this tutorial, you learned how Terraform applies changes to your infrastructure. You also reviewed how Terraform handles errors by reproducing an error during the apply step. Check out the following resources to learn more about managing your Terraform projects:
- Learn how to Customize Terraform Configuration with Variables.
- Learn how to work on Terraform projects with your team with the Store Remote State tutorial and the HCP Terraform get started tutorials.
- Learn about Running Terraform in Automation.