Shashi Techlogues

Terraform: Understanding Desired & Current State

In this post, we will learn in detail what is Terraform desired and current state.

Terraform’s responsibility is to create, update, or destroy infrastructure resources to match the desired state as described in the configuration.

Desired State

For example, if our desired state is as below:

resource "aws_instance" "myec2" {
  ami           = "ami-0ca285d4c2cda3300"
  instance_type = "t2.medium"
}

This should result in an AWS EC2 t2.medium instance.

The code you saw above is the desired state that we want.

Current State

The current state is the actual state of a resource that is deployed.

For example, if our desired state is:

resource "aws_instance" "myec2" {
  ami           = "ami-0ca285d4c2cda3300"
  instance_type = "t2.medium"
}

Our desired state is a t2.medium instance, but let’s say the current instance running is t2.micro. This means our desired state and the current state do not match.

Try It Out

Let’s first deploy a t2.micro EC2 instance using the below code.

provider "aws" {
  region     = "us-west-2"
  access_key = "<access_key>"
  secret_key = "<secret_key>"
}

resource "aws_instance" "myec2" {
  ami           = "ami-0ca285d4c2cda3300"
  instance_type = "t2.micro"
}

This will deploy an AWS EC2 t2.micro instance.

Learn how to deploy from the link: Terraform — 101

Changing the Desired State

Now let’s modify the instance_type to t2.medium:

provider "aws" {
  region     = "us-west-2"
  access_key = "<access_key>"
  secret_key = "<secret_key>"
}

resource "aws_instance" "myec2" {
  ami           = "ami-0ca285d4c2cda3300"
  instance_type = "t2.medium"
}

Run:

terraform plan

Terraform will detect the changes between the desired state (t2.medium) and the current state (t2.micro).

# aws_instance.myec2 will be updated in-place
~ resource "aws_instance" "myec2" {
      id            = "i-0a84f30f5656d7800"
    ~ instance_type = "t2.micro" -> "t2.medium"
      tags          = {
          "Name" = "terraform"
      }
      # (28 unchanged attributes hidden)
  }

# (6 unchanged blocks hidden)

Plan: 0 to add, 1 to change, 0 to destroy.

As we can see, Terraform has detected the change.

Remember: Terraform tries to ensure that the deployed infrastructure is based on the desired state. If there is a difference between the two, terraform plan will show the necessary changes required to achieve the desired state.

Applying the Change

Let’s run:

terraform apply

This will update the instance type from t2.micro to t2.medium.

Hope this clarifies what the desired state and current state are and how Terraform handles the difference between them.


In the subsequent article, we will explore more of Terraform.

Thanks for reading. If you have some feedback, please provide your response or reach out to me on Twitter or Github.

Happy Coding!!!