English

Share with friends

Note

In this terraform apply tutorial, we will go through everything from what is terraform apply, when to use it, command variations, and examples.

When to Use Terraform Apply Command with Examples cover image

You're probably wondering when it's the right time to hit that terraform apply command, right? Before jumping into it, here are a few scenarios where you'd want to use the 'terraform apply'.

Let's say you've just written some new infrastructure code and you're eager to see it in action.

That's the perfect moment to run 'terraform apply' and watch your creations come to life.

Another scenario is when you've made changes to your existing infrastructure and you want those changes to take effect.

Just run 'terraform apply' and let it work its magic.

So, go ahead and give it a try when you're ready. Let's dive right into this tutorial.

What is Terraform Apply?

terraform apply is like the boss command in Terraform. It's the one that takes all your carefully crafted infrastructure code and applies it. When you run terraform apply, Terraform compares the current state of your infrastructure with the desired state defined in your code. It figures out what needs to be created, modified, or destroyed to bring your infrastructure in line with your code.

But here's the coolest part: Terraform doesn't just go ahead and make all those changes without your say-so.

It's soft-hearted like that.

It shows you a plan first - a preview of what it's about to do. You get to see all the actions Terraform will take, like creating a shiny new server or updating a network configuration.

Once you've reviewed the plan and made sure everything looks good, you give Terraform the green light by typing "yes."

Terraform springs into action, talking to your cloud provider's API and making the changes necessary to create or update your infrastructure.

Here's what the syntax of the terraform apply command looks like.

terraform apply [options] [plan file]

Also Read: Differences between Terraform and Pulumi

What Does Terraform Apply Do?

When you run the terraform apply command, Terraform goes through your configuration files, figures out what resources need to be created, updated, or destroyed, and then takes action to make your infrastructure match the desired state you defined.

Let's back up a little and fully understand what this means.

Let's say you're into building some cool side project with cloud services like Amazon Web Services (AWS) or Microsoft Azure and you have all the resources you need to create, like virtual machines, storage buckets, and networks.

Now, managing all of these resources manually can be a real pain in the you-know-what.

Here's how Terraform would be useful.

Terraform is an open-source tool that helps you manage your infrastructure as code. It does so by allowing you to define and provision your cloud resources using simple, human-readable configuration files.

This means you can describe your desired infrastructure in a language that looks a lot like plain English (or something close to it).

Pretty neat, huh?

So, what does terraform apply do?

It applies something.

What?

As mentioned above, when you run this command, Terraform goes through your configuration files, figures out what resources need to be created, updated, or destroyed, and then takes that action.

Let's say you want to set up a basic web application.

You might have a Terraform configuration file that describes the necessary components, like a virtual machine, a database, and a load balancer.

When you run terraform apply, Terraform reads that file, talks to the cloud provider's API (of course, on its own), and starts creating the resources.

It's like having your own personal army of cloud Yodas doing your powerlifting!

But it doesn't stop there.

Terraform is also smart enough to detect changes you make to your configuration files.

Let's say you decide to increase the size of your virtual machine or add more storage.

When you run terraform apply again, Terraform will identify the differences between your desired state and the actual state of your infrastructure.

It will then make the necessary changes to bring everything back in line with what you've specified.

Note

With Terraform, you can plan your changes before actually applying them, giving you a chance to review what you did. It's like a safety net that prevents you from stepping on a landmine.

Also Read: A List of Terrform Commands

Terraform Apply Example

Let's consider an example of a sample Terraform configuration file plan.out with the following content:

provider "aws" {
  region  = "us-west-1"
}
resource "aws_ssm_parameter" "json_parameter" {
  name        = "test-parameter"
  type        = "String"
  value       = "testing"
}

When you run the command $ terraform apply plan.out, you will get the following output:

aws_ssm_parameter.json_parameter: Creating...
aws_ssm_parameter.json_parameter: Creation complete after 4s [id=test-parameter]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
The state of your infrastructure has been saved to the path below. This state is required to modify and destroy your infrastructure, so keep it safe. To inspect the complete state use the `terraform show` command.
State path: terraform.tfstate

Let's break down this example.

In the given Terraform configuration file, we have defined a provider block for AWS, specifying the region as 'us-west-1'. This tells Terraform that we want to create resources in the AWS US West 1 region.

Next, we have a resource block for an AWS SSM (Systems Manager) parameter named 'json_parameter'.

This resource represents a parameter that will be stored in AWS SSM Parameter Store.

We've given it the name of 'test-parameter', set the type to 'String', and the value to 'testing'.

Now, when you run the terraform apply plan.out command, Terraform takes the plan file 'plan.out' as input.

This plan file is generated when you run the terraform plan command, and it contains the changes Terraform will apply to your infrastructure.

In this case, it creates the AWS SSM parameter 'json_parameter'.

The output you see is the progress and completion status of the resource creation.

In this case, it tells you that the creation of the 'json_parameter' resource is complete after 4 seconds, and it provides you with the resource ID - 'test-parameter'.

The output line which states 'State path: terraform.tfstate' informs you that the current state of your infrastructure has been saved to the 'terraform.tfstate' file.

This state file is for Terraform to track and manage your infrastructure.

Additionally, use the terraform show command to inspect the complete state if you wish.

Variations of Terraform Apply Command with Examples

Now that we looked at what the terraform apply command does, let's look at an exhaustive list of sample commands.

-auto-approve

This command marches ahead with the application of changes without requiring interactive approval of the plan.

Here's how you can use it.

terraform apply -auto-approve

-compact-warnings

This flag displays warning messages in a concise format, showing only the summary messages unless there are accompanying errors where the warning text can provide useful context.

Let's look at how to use the -compact-warnings flag in a terraform apply command.

terraform apply -compact-warnings

-input=false

This flag disables all interactive prompts from Terraform, which also includes the approval prompt for the plan.

Without input, Terraform assumes the plan should not be applied, causing your intended operation to fail.

Here's an example of this flag.

terraform apply -input=false

-json

Using this flag will enable machine-readable JSON output for Terraform's user interface.

It requires no unassigned variable values in the configuration. The -auto-approve flag or a previously-saved plan must also be specified.

Here's a sample command and corresponding output.

terraform apply -json

Sample output:

{"@level":"info","@message":"Terraform 0.15.4","@module":"terraform.ui","@timestamp":"2021-05-25T13:32:41.275359-04:00","terraform":"0.15.4","type":"version","ui":"0.1.0"}
{"@level":"info","@message":"random_pet.animal: Plan to create","@module":"terraform.ui","@timestamp":"2021-05-25T13:32:41.705503-04:00","change":{"resource":{"addr":"random_pet.animal","module":"","resource":"random_pet.animal","implied_provider":"random","resource_type":"random_pet","resource_name":"animal","resource_key":null},"action":"create"},"type":"planned_change"}

-lock=false

This flag avoids acquiring a state lock during the operation. Caution should be exercised when using this option in a shared workspace to prevent conflicts.

Here's how to use this flag.

terraform apply -lock=false

Also Read: Kubernetes Cheatsheet

-lock-timeout=DURATION

When locking is enabled, this flag allows Terraform to retry acquiring a lock for a specified period of time before returning an error.

The syntax for the duration is a number followed by a letter denoting the time unit ("3s", for example, for three seconds).

Let's look at a terraform apply command example with this flag.

terraform apply -lock-timeout=5m

-no-color

This flag disables terminal formatting sequences in the output, useful when running Terraform in an environment that cannot interpret terminal formatting.

Here's an example of this terraform apply flag.

terraform apply -no-color

-parallelism=n

Using this flag limits the number of concurrent operations as Terraform processes the infrastructure graph. The default value is 10.

terraform apply -parallelism=5

-var

When executing the terraform plan and terraform apply commands, use the -var flag to specify specific variables on the command line:

Here's an example.

terraform apply -var="image_id=ami-abc123"
terraform apply -var='image_id_list=["ami-abc123","ami-def456"]' -var="instance_type=t2.micro"
terraform apply -var='image_id_map={"us-east-1":"ami-abc123","us-east-2":"ami-def456"}'

-var-file

This flag sets variables from a variable file in the Terraform configuration.

If the current directory contains a t_erraform.tfvars_ or any .auto.tfvars files, they will be loaded automatically.

The .auto.tfvars files are loaded in alphabetical order following the loading of terraform.tfvars. Values set automatically from files in the working directory are overridden by any files given by the -var-file option. This flag may be used more than once.

Here's how to use this

terraform apply -var-file="testing.tfvars"

-target

This terraform apply flag applies changes to only the targeted resource.

Here's an example

terraform apply -target="module.abcd.0"

-replace

When a resource degrades or ceases to function for reasons outside Terraform's control, use the -replace parameter.

Here's an example.

terraform apply -replace "docker_container.nginx[1]"
Note

Run terraform state list to get the list of all running docker containers.

Planning Modes and Options

These options allow customization of the planning phase when using terraform apply without a saved plan file. They enable fine-tuning of how Terraform generates the execution plan.

Here are a few examples.

terraform apply -refresh-only
terraform apply -target=module.example

Legacy Options for Local Backend

For configurations using the local backend, the following legacy options are accepted: -state, -state-out, and -backup. These options provide additional functionality related to state management.

Here's a sample terraform apply command.

terraform apply -state=terraform.tfstate

Also Read: Differences between Ansible and Terraform

How to Stop Terraform Apply?

If the Terraform CLI is interrupted (such as by pressing ctrl+c or receiving a SIGINT signal) during the apply phase, it will send a request to all the providers involved to cancel any ongoing requests and halt their operations as quickly as possible.

But, the effectiveness of this cancellation process depends on how each individual provider has implemented it.

Ideally, a provider should be able to immediately stop its operations and return an error.

However, not all providers and upstream APIs are capable of supporting such rapid cancellation.

If the command is already in executing state, you can stop it by running the command terraform state rm RESOURCE followed by the resource identifier (e.g., aws_ebs_volume.volume).

This operation tells Terraform to forget about the resource and not manage it anymore. After removing the resource from the state, running terraform apply again will not apply changes to that specific resource.

You can try to directly interact with your cloud provider's console or API to delete the resource that Terraform is managing.

What Action Does the Terraform Apply Command Perform in GCP?

In GCP, you can get started with Terraform by using it to create a basic web server on Google's Compute Engine. You can do things like:

  • Use Terraform to create a VM in Google Cloud.

  • Start a basic Flask / Node, tec server

  • Many more things.

Let's see an example of deployment.

Step 1: Make a "main.tf ' file with the following contents

resource "google_compute_network" "vpc_network" {
  name                    = "my-custom-mode-network"
  auto_create_subnetworks = false
  mtu                     = 1460
}
resource "google_compute_subnetwork" "default" {
  name          = "my-custom-subnet"
  ip_cidr_range = "10.0.1.0/24"
  region        = "us-west1"
  network    = google_compute_network.vpc_network.id
}

Step 2: Then add the following configurations to your 'main.tf ' file.

  • Create a single Compute Engine instance
  • Install Flask

Step 3: Run 'terraform init' to add the required plugins and build the '.terraform' directory.

Step 4: This will be the sample output after running the above command

Initializing the backend...
Initializing provider plugins......
Terraform has been successfully initialized!

Step 5: Next, validate the Terraform configuration by running the 'terraform plan' command. This command:

  1. Confirms that the syntax of the 'main.tf' file is correct, and

  2. Provides a sneak peek of the upcoming materials.

Step 6: Sample output

...
Plan: 1 to add, 0 to change, 0 to destroy.
Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.

Step 7: Apply the configuration to create the VM, run:

terraform apply

Step 8: When prompted, enter yes.

Also Read: What is Configuration as Code?

What Happens behind the Scenes?

To create the new VM, Terraform uses Google Cloud APIs. To see the new VM, visit the page for VM instances.

Note

For a look at the outcomes, open your Google Cloud project. Verify that Terraform has modified or generated your resources by navigating to them in the Google Cloud console.

Also Read: Docker Commands Cheat Sheet

When Does Terraform Apply Reflect Changes in the Cloud Environment?

When you use the 'terraform apply' command, Terraform builds a new execution plan by comparing the state file for the current state to the configuration's specified desired state.

Following the creation of the execution plan, Terraform provides the suggested changes and requests approval before implementing them.

When you give your approval for the changes, Terraform replaces the state file with the new state that reflects the changes.

In order to implement the intended changes in the cloud environment, Terraform subsequently submits the change requests to the resource provider.

Depending on the resources being updated, the time it takes the resource provider to fulfill requests may differ.

What Happens if Terraform Apply Fails?

When Terraform gets an error during an apply step, it:

  1. Records the issue and sends a console message.

  2. Any alterations to your resources are updated in the state file.

  3. Releases the state file's lock.

  4. Exits.

The rolling back of a partially finished application is not supported by Terraform. Because of this, if a terraform apply step fails, your infrastructure can be in an invalid condition.

You must apply your configuration once again to update your infrastructure to the appropriate state after fixing the mistake.

When using GCP, Terraform returns an error if a necessary API isn't enabled. There is a link to enable the API in the error message. You can rerun terraform apply after enabling the API.

Terraform Plan vs Apply

Terraform Plan Command

When you enter terraform plan command, the following steps are involved:

  1. Checks and refreshes the state data, which contains the mapping between resource addresses in the code and their unique IDs in the target environment.

  2. Compares the state data to the code to identify necessary changes.

  3. Prints the proposed changes to the console.

What is state data?

The state data represents the current state of the infrastructure being managed by Terraform. The code and state data are compared to determine if resources need to be created, updated, or destroyed.

Attributes of resources can be set through arguments in the Terraform code, but some attributes managed by the target environment cannot be changed.

Terraform Apply Command

When you perform terraform apply command, the following steps are involved:

  1. Similar to terraform plan, it checks and refreshes the state data.

  2. Compares the state data to the code to identify necessary changes.

  3. Prints the proposed changes.

  4. Asks for confirmation before proceeding.

  5. If changes are approved, it executes the changes on the target environment and updates the state data.

If you want to make Terraform apply changes without asking for confirmation, you can use the '-auto-approve' flag.

This means that it will automatically assume your answer is "yes" and proceed with the changes.

Another option is to provide a 'tfplan' file generated from a previous terraform plan command. The adjustments will be applied based on the contents of that file.

You can use the following command to generate a Terraform plan.

terraform plan

To save the planned changes, enter the following command.

terraform plan -out=tfplan

Here's how you can apply the changes interactively.

terraform apply

To apply the changes without confirmation, use the '-auto-approve' flag.

terraform apply -auto-approve

To apply changes using a saved tfplan file:

terraform apply tfplan
Note

Remember to generate a new plan if the state data has changed before executing the changes.

Use your own plan file instead of relying solely on the -auto-approve flag. It allows you to have better control and understanding of the changes being made to your infrastructure.

Share with friends

Priyansh Khodiyar's profile

Written by Priyansh Khodiyar

Priyansh is the founder of UnYAML and a software engineer with a passion for writing. He has good experience with writing and working around DevOps tools and technologies, APMs, Kubernetes APIs, etc and loves to share his knowledge with others.

Further Reading

Life is better with cookies 🍪

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt out if you wish. Cookie Policy