DEV Community

Sergei
Sergei

Posted on • Originally published at aicontentlab.xyz

Terraform Plan vs Apply: Understanding the Difference

Terraform Plan vs Apply: Understanding the Difference

Introduction

As a DevOps engineer, have you ever found yourself wondering what the difference is between terraform plan and terraform apply? You're not alone. Many engineers struggle to understand the nuances of these two commands, leading to confusion and potential errors in production environments. In this article, we'll delve into the basics of Terraform, explore the differences between plan and apply, and provide a step-by-step guide on how to use them effectively. By the end of this article, you'll have a solid understanding of how to use Terraform to manage your infrastructure, and you'll be able to confidently deploy changes to your production environment.

Understanding the Problem

At its core, Terraform is a powerful tool for managing infrastructure as code. It allows you to define your infrastructure in a human-readable configuration file, and then uses that configuration to create and manage your infrastructure. However, when it comes to making changes to your infrastructure, things can get complicated. That's where terraform plan and terraform apply come in. Terraform plan is used to generate an execution plan, which shows you what changes will be made to your infrastructure if you were to apply the current configuration. On the other hand, terraform apply is used to actually apply those changes to your infrastructure. But what happens if you don't use terraform plan before applying changes? You might end up with unexpected results, or even worse, downtime.

Let's consider a real-world scenario. Suppose you're managing a cluster of web servers using Terraform, and you need to add a new server to the cluster. You update your Terraform configuration file to include the new server, but you don't run terraform plan before applying the changes. When you run terraform apply, Terraform creates the new server, but it also inadvertently deletes one of the existing servers, causing downtime for your application. This is just one example of how not understanding the difference between terraform plan and terraform apply can lead to problems in production.

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 configuration files
  • A Terraform configuration file for your infrastructure
  • A terminal or command prompt

You don't need to have any prior experience with terraform plan or terraform apply, as we'll cover everything you need to know in this article.

Step-by-Step Solution

Step 1: Diagnosis

The first step in understanding the difference between terraform plan and terraform apply is to run terraform plan and see what changes Terraform is proposing to make to your infrastructure. To do this, navigate to the directory where your Terraform configuration file is located and run the following command:

terraform plan
Enter fullscreen mode Exit fullscreen mode

This will generate an execution plan, which will show you what changes Terraform will make to your infrastructure if you were to apply the current configuration. The output will look something like this:

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.web_server will be created
  + resource "aws_instance" "web_server" {
      + 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"
      + 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)
      + secondary_private_ips       = (known after apply)
      + security_groups              = (known after apply)
      + source_dest_check            = true
      + subnet_id                   = (known after apply)
      + tags                         = {
          + "Name" = "web-server"
        }
      + tenancy                      = (known after apply)
      + vpc_security_group_ids       = (known after apply)
    }

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

Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.
Enter fullscreen mode Exit fullscreen mode

As you can see, Terraform is proposing to create a new AWS instance.

Step 2: Implementation

Now that we've run terraform plan and seen what changes Terraform is proposing to make, it's time to apply those changes using terraform apply. To do this, run the following command:

terraform apply
Enter fullscreen mode Exit fullscreen mode

This will apply the changes proposed by terraform plan to your infrastructure. You'll see output similar to the following:

aws_instance.web_server: Creating...
aws_instance.web_server: Still creating... [10s elapsed]
aws_instance.web_server: Creation complete after 15s [id=i-0123456789abcdef0]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Enter fullscreen mode Exit fullscreen mode

As you can see, Terraform has successfully created the new AWS instance.

Step 3: Verification

To verify that the changes were applied successfully, you can use the terraform show command to display the current state of your infrastructure:

terraform show
Enter fullscreen mode Exit fullscreen mode

This will display the current state of your infrastructure, including the new AWS instance that we just created.

Code Examples

Here are a few examples of Terraform configuration files that you can use to get started:

# Example 1: Create an AWS instance
provider "aws" {
  region = "us-west-2"
}

resource "aws_instance" "web_server" {
  ami           = "ami-abc123"
  instance_type = "t2.micro"
  tags = {
    Name = "web-server"
  }
}
Enter fullscreen mode Exit fullscreen mode
# Example 2: Create a Kubernetes deployment
provider "kubernetes" {
  config_path    = "~/.kube/config"
  config_context = "default"
}

resource "kubernetes_deployment" "example" {
  metadata {
    name = "example-deployment"
  }

  spec {
    replicas = 2

    selector {
      match_labels = {
        app = "example"
      }
    }

    template {
      metadata {
        labels = {
          app = "example"
        }
      }

      spec {
        container {
          image = "nginx:latest"
          name  = "example-container"
        }
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
# Example 3: Create an Azure virtual machine
provider "azurerm" {
  version = "2.34.0"
  subscription_id = "your_subscription_id"
  client_id      = "your_client_id"
  client_secret = "your_client_secret"
  tenant_id      = "your_tenant_id"
}

resource "azurerm_virtual_machine" "example" {
  name                  = "example-vm"
  location              = "West US"
  resource_group_name = "example-resource-group"
  vm_size               = "Standard_DS2_v2"

  storage_image_reference {
    publisher = "Canonical"
    offer     = "UbuntuServer"
    sku       = "16.04-LTS"
    version   = "latest"
  }

  os_profile {
    computer_name  = "example-vm"
    admin_username = "example-user"
    admin_password = "example-password"
  }

  os_profile_linux_config {
    disable_password_authentication = false
  }
}
Enter fullscreen mode Exit fullscreen mode

These examples demonstrate how to create an AWS instance, a Kubernetes deployment, and an Azure virtual machine 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 running terraform plan before applying changes: This can lead to unexpected results or downtime.
  • Not specifying an output file when running terraform plan: This can make it difficult to track changes over time.
  • Not verifying the results of terraform apply: This can lead to errors or inconsistencies in your infrastructure.
  • Not using version control to track changes to your Terraform configuration files: This can make it difficult to collaborate with team members or track changes over time.

To avoid these pitfalls, make sure to always run terraform plan before applying changes, specify an output file when running terraform plan, verify the results of terraform apply, and use version control to track changes to your Terraform configuration files.

Best Practices Summary

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

  • Always run terraform plan before applying changes to your infrastructure.
  • Specify an output file when running terraform plan to track changes over time.
  • Verify the results of terraform apply to ensure that changes were applied successfully.
  • Use version control to track changes to your Terraform configuration files.
  • Test your Terraform configuration files thoroughly before applying changes to production.
  • Use a consistent naming convention and tagging scheme to make it easier to manage your infrastructure.

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 two commands and using them effectively, you can avoid common pitfalls and ensure that your infrastructure is running smoothly and efficiently. Remember to always run terraform plan before applying changes, specify an output file when running terraform plan, verify the results of terraform apply, and use version control to track changes to your Terraform configuration files.

Further Reading

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

  • Terraform modules: Terraform modules are pre-built configurations that can be used to manage common infrastructure components, such as databases or load balancers.
  • Terraform state: Terraform state refers to the current state of your infrastructure, including the resources that have been created and their current configuration.
  • Infrastructure as code best practices: There are many best practices to keep in mind when using infrastructure as code tools like Terraform, including testing, version control, and continuous integration and continuous deployment (CI/CD).
  • Terraform and Kubernetes: Terraform can be used to manage Kubernetes clusters and deployments, making it a powerful tool for managing containerized applications.
  • Terraform and cloud providers: Terraform supports a wide range of cloud providers, including AWS, Azure, Google Cloud, and more.

🚀 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)