Going to AWS Summit London? 🇬🇧🇬🇧

Meet us there →


Terraform Apply – When to Run & Quick Usage Examples

Terraform apply

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:

  1. What is Terraform apply?
  2. Terraform apply quick usage options examples
  3. Tutorial: How to use Terraform apply
  4. Running Terraform apply in automation
  5. Common questions about the Terraform apply command
  6. Best practices for running Terraform apply

What is Terraform apply?

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.

Terraform apply quick usage options examples

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.

Tutorial: How to use Terraform apply

To use terraform apply, you will need to: 

  1. Define a Terraform configuration – E.G:
provider "aws" {
 region = "us-east-1"

resource "aws_s3_bucket" "my_bucket" {
 bucket = "my-awesome-bucket-710"
  1. 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)
  2. Run a terraform init to download all the necessary providers, and modules and get things up and running in your environment.
  3. 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.
  1. 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

Running Terraform apply in automation

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!

Common questions about the Terraform apply command

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.

Best practices for running Terraform apply

When it comes to running terraform apply, a couple of things have to be taken into consideration:

  1. Always run a plan first and have multiple individuals review it.
  2. Use version control for your code – track changes and collaborate with others.
  3. 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.
  4. 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.
  5. Limit scope changes – break down large changes into smaller ones to ensure that you are not breaking your environments.
  6. Regularly review and refactor your code.
  7. Use OPA policies to ensure standardization and governance all around.
  8. Leverage security vulnerability scanning tools and liners to ensure your code is top-notch.

Key Points

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.

Start free trial
Terraform CLI Commands Cheatsheet

Initialize/ plan/ apply your IaC, manage modules, state, and more.

Share your data and download the cheatsheet