In this post, I will explain what theĀ terraform apply
command is used for in Infrastructure as Code (IaC), what it does, the 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 is used to apply the changes to your infrastructure to reach the state you have described in the code. It compares the state of your infrastructure with the desired state and makes changes to resources, creating, updating, or deleting them.
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
.
If theĀ 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.
TheĀ apply
command can also be used with a previously generated plan file, from theĀ terraform plan -out=<path to file>
.
1. terraform apply
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
Apply changes without having to interactively type āyesā to the plan. Useful in automation CI/CD pipelines.
3. terraform apply <planfilename>
Provide the file generated 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"
Pass in a variable value.
5. terraform apply -var-file="varfile.tfvars"
Pass in variables contained in a file.
6. terraform apply -target=āmodule.appgw.0"
Apply changes only to the targeted resource. Read more about Terraform target option.
7. terraform apply -lock=false
Do not hold a state lock during the Terraform apply operation. Use with caution if other engineers might run concurrent commands against the same workspace.
8. terraform apply -parallelism=<n>
Specify the number of operations run in parallel.
9. terraform apply -compact-warnings
Condenses the warnings into a more concise format, which can be useful for improving the readability of Terraform output.
10. 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
ā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.
12. terraform apply -lock-timeout=DURATION
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 in a format like “30s” (30 seconds), “5m” (5 minutes), “1h” (1 hour).
13. terraform apply -no-color
ā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.
To use terraform apply
, you will need to:Ā
- 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 by running
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.
Is it safe to run terraform apply
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. Terraform is a declarative language, so it is absolutely safe to run theĀ apply
Ā command multiple times.
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.
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 to run a 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 if you are using a CI/CD pipeline, as a best practice, 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. OpenTofu retained all the features and functionalities that had made Terraform popular among developers while also introducing improvements and enhancements. OpenTofu works with your existing Terraform state file, so you wonāt have any issues when you are migrating to it.
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.
Terraform CLI Commands Cheatsheet
Initialize/ plan/ apply your IaC, manage modules, state, and more.