DEV Community

Sergei
Sergei

Posted on • Originally published at aicontentlab.xyz

Terraform Plan vs Apply: Infrastructure Management

Terraform Plan vs Apply: Understanding the Difference

Terraform is a powerful tool for managing infrastructure as code, but even experienced DevOps engineers can get confused about the difference between terraform plan and terraform apply. Imagine you're working on a critical project, and you've made changes to your Terraform configuration. You want to verify that the changes will be applied correctly before actually making them. This is where terraform plan and terraform apply come in. In this article, we'll explore the basics of Terraform, the difference between terraform plan and terraform apply, and provide a step-by-step guide on how to use them in a production environment.

Introduction

Have you ever made changes to your Terraform configuration and wondered what exactly would happen when you apply them? Or have you ever applied changes without verifying them first, only to find out that they had unintended consequences? This is a common problem in production environments, where infrastructure changes can have significant impacts on applications and services. In this article, we'll delve into the world of Terraform and explore the difference between terraform plan and terraform apply. By the end of this article, you'll have a deep understanding of how to use these commands to manage your infrastructure as code and avoid common pitfalls.

Understanding the Problem

The root cause of the confusion between terraform plan and terraform apply lies in the fact that both commands are used to manage infrastructure changes, but they serve different purposes. terraform plan is used to preview the changes that will be made to your infrastructure, while terraform apply is used to actually apply those changes. Common symptoms of not understanding the difference between these commands include applying changes without verifying them first, which can lead to unintended consequences, such as downtime or security vulnerabilities. For example, let's say you're working on a project that uses Terraform to manage a Kubernetes cluster. You make changes to the Terraform configuration to add a new node pool, but you don't verify the changes before applying them. When you apply the changes, you realize that the new node pool is not configured correctly, which causes the entire cluster to become unstable.

Prerequisites

To follow along with this article, you'll need to have the following tools and knowledge:

  • Terraform installed on your machine
  • A basic understanding of Terraform and its configuration files
  • A Terraform configuration file (e.g., main.tf) that defines your infrastructure
  • A Terraform state file (e.g., terraform.tfstate) that keeps track of your infrastructure's current state To set up your environment, you can follow these steps:
  • Install Terraform on your machine by downloading the binary from the official Terraform website.
  • Create a new Terraform configuration file (e.g., main.tf) that defines your infrastructure.
  • Initialize your Terraform working directory by running terraform init.
  • Apply your Terraform configuration to create your infrastructure by running terraform apply.

Step-by-Step Solution

Step 1: Diagnosis

To understand the difference between terraform plan and terraform apply, let's start by running terraform plan. This command will preview the changes that will be made to your infrastructure without actually applying them.

terraform plan
Enter fullscreen mode Exit fullscreen mode

This will output a detailed summary of the changes that will be made, including any additions, modifications, or deletions. For example:

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create
  - destroy
  ~ update in-place

Terraform will perform the following actions:

  # aws_instance.example will be created
  + resource "aws_instance" "example" {
      + ami                          = "ami-abc123"
      + arn                          = (known after apply)
      + availability_zone           = (known after apply)
      + id                            = (known after apply)
      + instance_state               = (known after apply)
      + instance_type                = "t2.micro"
      + ipv6_address_count           = (known after apply)
      + ipv6_addresses               = (known after apply)
      + key_name                      = "my_key"
      + outpost_arn                  = (known after apply)
      + password_data                 = (known after apply)
      + placement_group              = (known after apply)
      + primary_network_interface_id = (known after apply)
      + private_dns                   = (known after apply)
      + private_ip                    = (known after apply)
      + public_dns                    = (known after apply)
      + public_ip                     = (known after apply)
      + security_groups               = (known after apply)
      + source_dest_check             = true
      + subnet_id                    = (known after apply)
      + tags                          = {
          + "Name" = "example"
        }
      + tenancy                       = (known after apply)
      + vpc_security_group_ids         = (known after apply)
      + vpc_tags                       = (known after apply)
    }

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

Enter fullscreen mode Exit fullscreen mode

As you can see, terraform plan provides a detailed summary of the changes that will be made, including the creation of a new AWS instance.

Step 2: Implementation

Now that we've verified the changes using terraform plan, we can apply them using terraform apply. This command will actually make the changes to our infrastructure.

terraform apply
Enter fullscreen mode Exit fullscreen mode

This will output a confirmation prompt, asking you to confirm that you want to apply the changes. For example:

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: 
Enter fullscreen mode Exit fullscreen mode

Type yes to confirm that you want to apply the changes.

Step 3: Verification

After applying the changes, we can verify that they were successful by running terraform show. This command will display the current state of our infrastructure.

terraform show
Enter fullscreen mode Exit fullscreen mode

This will output a detailed summary of our infrastructure, including the new AWS instance that we created. For example:

# aws_instance.example:
resource "aws_instance" "example" {
  ami                          = "ami-abc123"
  arn                          = "arn:aws:ec2:us-west-2:123456789012:instance/i-abc123"
  availability_zone           = "us-west-2a"
  id                            = "i-abc123"
  instance_state               = "running"
  instance_type                = "t2.micro"
  ipv6_address_count           = 0
  key_name                      = "my_key"
  outpost_arn                  = ""
  password_data                 = ""
  placement_group              = ""
  primary_network_interface_id = "eni-abc123"
  private_dns                   = "ip-10-0-1-100.us-west-2.compute.internal"
  private_ip                    = "10.0.1.100"
  public_dns                    = "ec2-54-183-123-123.us-west-2.compute.amazonaws.com"
  public_ip                     = "54.183.123.123"
  security_groups               = [
    "sg-abc123",
  ]
  source_dest_check             = true
  subnet_id                    = "subnet-abc123"
  tags                          = {
    "Name" = "example"
  }
  tenancy                       = "default"
  vpc_security_group_ids         = [
    "sg-abc123",
  ]
  vpc_tags                       = {}
}
Enter fullscreen mode Exit fullscreen mode

As you can see, terraform show provides a detailed summary of our infrastructure, including the new AWS instance that we created.

Code Examples

Here are a few examples of Terraform configuration files that demonstrate the difference between terraform plan and terraform apply:

# Example 1: Creating a new AWS instance
provider "aws" {
  region = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-abc123"
  instance_type = "t2.micro"
  tags = {
    Name = "example"
  }
}
Enter fullscreen mode Exit fullscreen mode
# Example 2: Updating an existing AWS instance
provider "aws" {
  region = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-abc123"
  instance_type = "t2.micro"
  tags = {
    Name = "example"
  }
}

resource "aws_security_group" "example" {
  name        = "example"
  description = "Example security group"
  vpc_id      = "vpc-abc123"

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
Enter fullscreen mode Exit fullscreen mode
# Example 3: Deleting an existing AWS instance
provider "aws" {
  region = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-abc123"
  instance_type = "t2.micro"
  tags = {
    Name = "example"
  }
}

resource "null_resource" "example" {
  provisioner "local-exec" {
    command = "aws ec2 terminate-instances --instance-ids ${aws_instance.example.id}"
  }
}
Enter fullscreen mode Exit fullscreen mode

These examples demonstrate how to create, update, and delete AWS instances using Terraform.

Common Pitfalls and How to Avoid Them

Here are a few common pitfalls to watch out for when using terraform plan and terraform apply:

  • Not verifying changes before applying them: This can lead to unintended consequences, such as downtime or security vulnerabilities. To avoid this, always run terraform plan before running terraform apply.
  • Not understanding the difference between terraform plan and terraform apply: This can lead to confusion and mistakes. To avoid this, make sure you understand the difference between these commands and use them correctly.
  • Not using version control: This can lead to lost changes and confusion. To avoid this, use version control (e.g., Git) to manage your Terraform configuration files.
  • Not testing changes in a staging environment: This can lead to unintended consequences in production. To avoid this, test changes in a staging environment before applying them to production.

Best Practices Summary

Here are some best practices to keep in mind when using terraform plan and terraform apply:

  • Always run terraform plan before running terraform apply to verify changes.
  • Use version control (e.g., Git) to manage your Terraform configuration files.
  • Test changes in a staging environment before applying them to production.
  • Use terraform show to verify the current state of your infrastructure.
  • Use terraform destroy to delete resources that are no longer needed.

Conclusion

In conclusion, terraform plan and terraform apply are two powerful commands that can help you manage your infrastructure as code. By understanding the difference between these commands and using them correctly, you can avoid common pitfalls and ensure that your infrastructure is properly configured and managed. Remember to always verify changes before applying them, use version control to manage your configuration files, and test changes in a staging environment before applying them to production.

Further Reading

If you're interested in learning more about Terraform and infrastructure as code, here are a few topics to explore:

  • Terraform modules: These are pre-built Terraform configurations that can be used to manage common infrastructure components, such as AWS instances or Kubernetes clusters.
  • Terraform state: This is a critical component of Terraform that keeps track of the current state of your infrastructure. Understanding how Terraform state works is essential for managing your infrastructure effectively.
  • Infrastructure as code (IaC) best practices: These are guidelines for managing your infrastructure as code, including tips for writing effective Terraform configurations, managing state, and testing changes.

🚀 Level Up Your DevOps Skills

Want to master Kubernetes troubleshooting? Check out these resources:

📚 Recommended Tools

  • Lens - The Kubernetes IDE that makes debugging 10x faster
  • k9s - Terminal-based Kubernetes dashboard
  • Stern - Multi-pod log tailing for Kubernetes

📖 Courses & Books

  • Kubernetes Troubleshooting in 7 Days - My step-by-step email course ($7)
  • "Kubernetes in Action" - The definitive guide (Amazon)
  • "Cloud Native DevOps with Kubernetes" - Production best practices

📬 Stay Updated

Subscribe to DevOps Daily Newsletter for:

  • 3 curated articles per week
  • Production incident case studies
  • Exclusive troubleshooting tips

Found this helpful? Share it with your team!


Originally published at https://aicontentlab.xyz

Top comments (0)