In this post, I will explain what the terraform apply
command is, how it is used in Infrastructure as Code (IaC), what it does, examples of available options, and when to run it.
What we will cover:
The terraform apply
command is one of the core operations that you can do with Terraform. It updates your infrastructure to match the state described in your code. Terraform apply
assesses the current infrastructure state, identifies discrepancies, and adjusts resources by creating, updating, or deleting them as needed.
Terraform apply is one of the Terraform CLI commands — check out our Terraform Cheat Sheet to learn more!
What does the terraform apply
command do?
The terraform apply
command executes the actions proposed in a terraform plan
. It is used to deploy your infrastructure. Typically apply
should be run after terraform init
and terraform plan
.
The apply
command can also be used with a previously generated plan file from the terraform plan -out=<path to file>
.
What you should do before running terraform apply
?
Before running terraform apply
, you will need to:
- Define a Terraform configuration.
- Ensure you have defined the access to your cloud provider.
- Run a
terraform init
to download all the necessary providers and modules. - Create an execution plan by running
terraform plan
.
What happens after terraform apply
?
After running terraform apply
, Terraform will provision and create the resources defined in your configuration files on the specified provider(s). It’s important to review the apply output carefully, as it shows the real changes being made to your infrastructure.
If the terraform apply
command is run without any options, it will run a terraform plan
first, ask the user to confirm the planned actions and then execute those changes once confirmed.
By running terraform apply -auto-approve
, all the infrastructure resources you have defined in your configuration will get created in your cloud provider/database/k8s cluster.
Here are some examples of options that you can use with the terraform apply command.
1. terraform apply
Running terraform apply
by itself creates or updates infrastructure depending on the configuration files. By default, a plan will be generated first and will need to be approved before it is applied.
2. terraform apply -auto-approve
When you run terraform apply
with the -auto-approve
flag it automatically applies all changes without having to interactively type ‘yes’ to the plan. It is useful in CI/CD pipeline automation.
3. terraform apply <planfilename>
Add the file generated previously using the terraform plan -out
command. If provided, Terraform will take the actions in the plan without any confirmation prompts.
4. terraform apply -var="my_variable=test"
You can use terraform apply -var="my_variable=test"
option to pass in a variable value.
5. terraform apply -var-file="varfile.tfvars"
The -var-file="varfile.tfvars"
option passes in variables contained in a file.
6. terraform apply -target=”module.appgw.0"
The -target=”module.appgw.0"
flag lets you apply changes only to the targeted resource. Read more about the Terraform target option.
7. terraform apply -lock=false
If you need to disable the Terraform state locking feature during the apply operation you can run terraform apply
with the -lock=false
option. Remember to use it with caution as other engineers might run concurrent commands against the same workspace.
8. terraform apply -parallelism=<n>
terraform apply -parallelism=<n>
lets you specify the number of operations run in parallel. The -parallelism
option is useful when you want to limit the number of concurrent operations inside your cloud provider. Some cloud providers have rate limits, and you may receive throttling errors.
9. terraform apply -compact-warnings
When you want to improve the readability of Terraform output, you can use the terraform apply -compact-warnings
option to condense the warnings into a more concise format.
The -compact-warnings
option gives you clearer output when running terraform apply
, as it minimizes the warnings you see when you do this operation.
10. terraform apply -input=false
After you run terraform apply -input=false
, Terraform will not prompt you for any input during the apply process, and it will proceed with the plan using the existing values specified in your Terraform configuration files. This can be useful in scenarios where you want to automate the Terraform apply process without any manual intervention, especially in scripted or automated workflows, or when running Terraform in non-interactive environments, such as CI/CD pipelines.
11. terraform apply -json
terraform apply -json
provides a structured JSON output that includes the results of the operation, making it easier to parse and integrate into automated workflows or other tools.
To run terraform apply
with the -json
option, you need to either pass a plan file to the command or use -auto-approve
option. Let’s see it in action.
Using a plan file, we will first need to create it:
terraform plan -out=myplan.tfplan
Next, let’s run the apply command:
terraform apply -json myplan.tfplan
{"@level":"info","@message":"Terraform 1.5.7","@module":"terraform.ui","@timestamp":"2024-05-14T11:15:45.491343+03:00","terraform":"1.5.7","type":"version","ui":"1.1"}
{"@level":"info","@message":"aws_s3_bucket.my_bucket: Plan to create","@module":"terraform.ui","@timestamp":"2024-05-14T11:15:46.415746+03:00","change":{"resource":{"addr":"aws_s3_bucket.my_bucket","module":"","resource":"aws_s3_bucket.my_bucket","implied_provider":"aws","resource_type":"aws_s3_bucket","resource_name":"my_bucket","resource_key":null},"action":"create"},"type":"planned_change"}
{"@level":"info","@message":"aws_s3_bucket.my_bucket: Creating...","@module":"terraform.ui","@timestamp":"2024-05-14T11:15:47.472327+03:00","hook":{"resource":{"addr":"aws_s3_bucket.my_bucket","module":"","resource":"aws_s3_bucket.my_bucket","implied_provider":"aws","resource_type":"aws_s3_bucket","resource_name":"my_bucket","resource_key":null},"action":"create"},"type":"apply_start"}
{"@level":"info","@message":"aws_s3_bucket.my_bucket: Creation complete after 3s [id=my-awesome-bucket-32209]","@module":"terraform.ui","@timestamp":"2024-05-14T11:15:50.350278+03:00","hook":{"resource":{"addr":"aws_s3_bucket.my_bucket","module":"","resource":"aws_s3_bucket.my_bucket","implied_provider":"aws","resource_type":"aws_s3_bucket","resource_name":"my_bucket","resource_key":null},"action":"create","id_key":"id","id_value":"my-awesome-bucket-32209","elapsed_seconds":3},"type":"apply_complete"}
{"@level":"info","@message":"Apply complete! Resources: 1 added, 0 changed, 0 destroyed.","@module":"terraform.ui","@timestamp":"2024-05-14T11:15:50.375979+03:00","changes":{"add":1,"change":0,"import":0,"remove":0,"operation":"apply"},"type":"change_summary"}
{"@level":"info","@message":"Outputs: 0","@module":"terraform.ui","@timestamp":"2024-05-14T11:15:50.376392+03:00","outputs":{},"type":"outputs"}
Without the plan file, we could’ve simply ran:
terraform apply -json -auto-approve
12. terraform apply -lock-timeout=DURATION
With -lock-timeout=DURATION
option, you can set a duration for how long Terraform should wait to acquire a lock on the state file during an apply operation.
DURATION should be specified by a number with a time unit, such as “30s” (30 seconds), “5m” (5 minutes), or “1h” (1 hour).
13. terraform apply -no-color
The -no-color
option lets you disable colorized output in the console. By default, Terraform outputs information with color codes for better readability and to distinguish different types of messages (e.g., changes, warnings, and errors) with colors. This is useful when you are working in an environment that does not support or handle color codes properly or when you prefer plain text output for your specific use case.
For configurations using the local backend only, terraform apply
also accepts the legacy options -state, -state-out, and -backup.
Let’s now take a look at the practical use of the terraform apply
command.
- First, define a Terraform configuration – e.g.:
provider "aws" {
region = "us-east-1"
}
resource "aws_s3_bucket" "my_bucket" {
bucket = "my-awesome-bucket-710"
}
- Ensure you have defined the access to your cloud provider (for AWS set up the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY env vars or define them in the ~/.aws/credentials file).
- Run a
terraform init
to download all the necessary providers, and modules and get things up and running in your environment. - Create an execution plan using
terraform plan
:
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_s3_bucket.my_bucket will be created
+ resource "aws_s3_bucket" "my_bucket" {
+ acceleration_status = (known after apply)
+ acl = (known after apply)
+ arn = (known after apply)
+ bucket = "my-awesome-bucket-710"
+ bucket_domain_name = (known after apply)
+ bucket_prefix = (known after apply)
+ bucket_regional_domain_name = (known after apply)
+ force_destroy = false
+ hosted_zone_id = (known after apply)
+ id = (known after apply)
+ object_lock_enabled = (known after apply)
+ policy = (known after apply)
+ region = (known after apply)
+ request_payer = (known after apply)
+ tags_all = (known after apply)
+ website_domain = (known after apply)
+ website_endpoint = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
- Run
terraform apply -auto-approve
and make the changes.
Plan: 1 to add, 0 to change, 0 to destroy.
aws_s3_bucket.my_bucket: Creating...
aws_s3_bucket.my_bucket: Creation complete after 3s [id=my-awesome-bucket-710]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed
In automation terraform apply
can be run after the plan stage, passing in the plan output file. If there is no plan stage prior to the apply stage (not recommended), then the terraform apply -auto-approve
option can be used. Another useful option to avoid encoding issues when running pipelines in some CI/CD systems, i.e. Azure DevOps, is the terraform apply -no-color
option, as the colored output is not handled correctly by the build agents.
A more robust approach to automating your Terraform workflows end-to-end would be to use Spacelift, a collaborative infrastructure delivery tool. Spacelift provides a more mature way of automating the whole infrastructure provisioning lifecycle. Its flexible and robust workflow allows teams to get up to speed quickly and collaborate efficiently. Check out the documentation and start automating your infrastructure delivery easily!
Now, we will answer some of the questions you may have about this command.
How to pass yes to Terraform apply?
Generally, when a CLI tool offers a mechanism for bypassing confirmation, it is recommended that you use that flag.
In Linux, the “yes” command helps you to bypass confirmation. You can generally use it like so: yes | rm -r directory
.
This doesn’t work for Terraform, so you will need to use the mechanism for bypass confirmation, which is the -auto-approve
flag.
Is it safe to run terraform apply
multiple times?
Terraform is a declarative language, so it is absolutely safe to run the apply
command multiple times. If there are no changes in the configuration files compared to the current Terraform state, then no changes will be made to the infrastructure.
What happens if you run Terraform apply twice?
If you are running terraform apply
twice, and you haven’t changed your configuration, Terraform will show you there are no changes to be done. However, if you make changes to your codebase, Terraform will just make those changes.
What is the difference between plan
and apply
Terraform?
A terraform plan
shows you an execution plan of what Terraform will change in case of an apply. A terraform apply
also does the actual execution of the code.
You can find more details about Terraform plan vs. apply in the comparison table below:
Plan | Apply | |
Primary purpose | Creates an execution plan showing all the actions that will be taken to your infrastructure (create/change/delete) without making any changes | Applies changes to your infrastructure (create/change/delete) |
Output | Plan of proposed changes (create/change/delete) | Plan of proposed changes
Wait for confirmation [Optional] Modifies the infrastructure |
Usage | Used to review and see the impact of changes before applying | Changes the infrastructure as specified in the configuration |
State changes | No state changes | Changes according to the configuration |
Common scenario | Run in a CI/CD pipeline after initialization to validate changes | Run in a CI/CD pipeline after validation to make changes to your infrastructure. |
Safety | No changes are made to the infrastructure, so it is completely safe | It should be used with caution, as it makes changes to your infrastructure |
What is the difference between terraform apply
and terraform destroy
?
Terraform apply
checks the configuration and your actual state and does changes to your infrastructure resources (create/modify/destroy). Terraform destroy
checks your configuration and the actual state of your infrastructure and destroys all resources.
Should you run terraform apply
before or after a merging?
As a best practice, you should always see a terraform plan
on your pull request, and only apply the code after the pull request is merged.
What happens if terraform apply
fails?
Depending on when a terraform apply
command fails, some resources may have been successfully created, updated, or deleted, before the error was encountered. This means that your infrastructure reached a partially updated state, where some changes were applied and others have not been applied. The state file is updated to reflect the current state of the infrastructure with the partial updates.
Whenever you get an error, Terraform will let you know what failed and why, but sometimes, depending on how the error messages were defined inside of the providers you are using, these can be hard to debug.
Once you address the issues you’ve encountered, you can run terraform apply
again to solve the issues.
Can you run terraform apply
without plan
?
You don’t need terraform plan
to run terraform apply
, as if you don’t use the -auto-apply
option, Terraform will initially show a plan and you can take advantage of it before taking action. This can be useful in local environments, but as a best practice, if you are using a CI/CD pipeline, you should first create a plan, review it, and then run terraform apply
with the -auto-apply
”= option.
What is the opposite of terraform apply
?
The opposite of a terraform apply
is terraform destroy
, which destroys all the resources that are in the state. Some special resources, such as null_resources, can be created on destroy, but these are just exceptions.
How to stop terraform apply
?
After you have started a terraform apply
, and the requests are being sent, you cannot stop the apply without repercussions. You can send an interrupt signal (ctrl+c), and then you have the option to wait for a graceful shutdown or send another interrupt signal to force the shutdown. In both cases, some partial applies may happen, and in the force shutdown case, you may leave your infrastructure in an inconsistent state.
When it comes to running terraform apply
, a couple of things have to be taken into consideration:
- Always run a plan first and have multiple individuals review it.
- Use version control for your code — track changes and collaborate with others.
- Use a remote state with a locking mechanism in place — this will help you ensure that only one person can make changes at a time, hence reducing the chances of the state file getting corrupted.
- Use at least a CI/CD pipeline — ensure the changes are done through an automated system that has every measure in place to ensure the blast radius is kept to a minimum. A specialized IaC management platform such as Spacelift would be the best way for you to manage your infrastructure.
- Limit scope changes — break down large changes into smaller ones to ensure that you are not breaking your environments.
- Regularly review and refactor your code.
- Use OPA policies to ensure standardization and governance all around.
- Leverage security vulnerability scanning tools and liners to ensure your code is top-notch.
terraform apply
is a core command in the Terraform workflow, used for deploying infrastructure as described in your configuration files.
Note: New versions of Terraform will be placed under the BUSL license, but everything created before version 1.5.x stays open-source. OpenTofu is an open-source version of Terraform that will expand on Terraform’s existing concepts and offerings. It is a viable alternative to HashiCorp’s Terraform, being forked from Terraform version 1.5.6.
Manage Terraform Better and Faster
If you are struggling with Terraform automation and management, check out Spacelift. It helps you manage Terraform state, build more complex workflows, and adds several must-have capabilities for end-to-end infrastructure management.