Featured image of post Diving Into Terraform State File: Your Friendly Guide - Terraform on Azure Part 4

Diving Into Terraform State File: Your Friendly Guide - Terraform on Azure Part 4

This article explores the concept of Terraform State File, illustrating its important role in tracking and managing infrastructure changes, with a hands-on example of managing Azure Virtual Machines, all explained in a playful, friendly tone

Diving Into Terraform State File: Your Friendly Guide 🌊

Introduction: Setting the Stage 🎭

Hello again, Everyone! 🌟 Welcome to the fourth installment of our Terraform on Azure series. In the previous articles, we’ve covered the fundamentals of Terraform (Part 1), set up our local development environment (Part 2), and even created our first Terraform project on Azure (Part 3). Today, we’ll be diving into the mysterious world of the Terraform State File. πŸ—ΊοΈ

Terraform State File

Meet the Terraform State File: Your Trusty Map πŸ—ΊοΈ

The Terraform State File is like a map that guides Terraform through the vast infrastructure landscape. Just as a map helps you navigate unfamiliar terrain, the State File helps Terraform understand what resources it has created, their current settings, and how they relate to each other. 🧭

This JSON file, usually named terraform.tfstate, is automatically created and updated by Terraform as it creates, modifies, or destroys infrastructure. It serves as the “single source of truth” πŸ“œ, linking the resources in your configuration files to their real-world counterparts, whether in the cloud or on-premises.

The Importance of the Terraform State File: A Guiding Light πŸ’‘

The Terraform State File is crucial for several reasons:

  1. Tracking Changes: The State File keeps a record of your infrastructure’s current state, allowing Terraform to determine what changes need to be made when you update your configuration. πŸ“
  2. Dependency Mapping: It maps out the dependencies between your resources, ensuring that Terraform can create, update, or delete them in the correct order. 🧩
  3. Collaboration: When working with a team, the State File provides a shared understanding of the current infrastructure state, enabling seamless collaboration. 🀝

Terraform and Its State File: A Dynamic Duo πŸ¦Έβ€β™‚οΈπŸ¦Έβ€β™€οΈ

Let’s take a closer look at how Terraform interacts with the State File:

  1. Initial Run: On its first run with a terraform apply command, Terraform identifies the resources to create based on your configuration file. It creates a fresh state file to store your infrastructure’s current state and keep tabs on new infrastructure.
  2. Subsequent Runs: On subsequent terraform apply runs, Terraform reads the existing state file to identify previously created resources. It contrasts your configuration file with the state file to pinpoint necessary changes.
  3. Updating Infrastructure: When you apply changes with terraform apply, Terraform updates the State File to mirror the latest infrastructure configuration. It records any infrastructure additions, removals, or alterations in the State File.

Hands-On Fun: Managing Azure Virtual Machines with Terraform πŸ› οΈ

Let’s roll up our sleeves and dive into a real-world example to see Terraform and the State File in action. Suppose we have a simplistic Terraform configuration file, main.tf, aiming to create a virtual machine on Azure:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "example" {
  name     = "example-resource-group"
  location = "East US"
}

resource "azurerm_virtual_machine" "example" {
  name                  = "example-vm"
  location              = "East US"
  resource_group_name   = "example-resource-group"
  # ... other VM configurations
}

Execute terraform apply, and Terraform determines the resources to create from your configuration file. A terraform.tfstate file is created after a successful terraform apply command. This JSON file encapsulates information on the freshly created resources.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
{
  "version": 4,
  "terraform_version": "1.6.0",
  "resources": [
    {
      "mode": "managed",
      "type": "azurerm_virtual_machine",
      "name": "example",
      "provider": "provider[\"registry.terraform.io/hashicorp/azurerm\"]",
      "instances": [
        {
          "attributes": {
            "name": "example-vm",
            "location": "East US",
            # ... other VM attributes
          },
        }
      ]
    }
  ]
}

A peek into the terraform.tfstate file reveals:

  • The version is the syntax version used by the terraform state file, ensuring backward compatibility between different Terraform versions.
  • The terraform_version shows the Terraform version used to create the state file.
  • The resources section lists out all managed resources, in this case, our Virtual Machine. It contains details like the resource type, name, and attributes (like VM name, type, location, etc.).

Now let’s add another VM to our infrastructure. Update the configuration file main.tf to add a new virtual machine:

1
2
3
4
5
6
7
8
# ... previous configuration

resource "azurerm_virtual_machine" "example2" {
  name                  = "example-vm2"
  location              = "East US"
  resource_group_name   = "example-resource-group"
  # ... other VM configurations
}

Execute terraform plan, and Terraform compares the updated configuration file with the State File. It recognizes that there’s already a VM (example-vm) but notices a new VM configuration (example-vm2). Terraform then knows that, upon running terraform apply, it should only create the second VM, leaving the first VM untouched. 🎯

The updated State File will now include both VMs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
{
  # ...previous content
  "resources": [
    # ...previous VM details
    {
      "mode": "managed",
      "type": "azurerm_virtual_machine",
      "name": "example2",
      "provider": "provider[\"registry.terraform.io/hashicorp/azurerm\"]",
      "instances": [
        {
          "attributes": {
            "name": "example-vm2",
            "location": "East US",
            # ... other VM attributes
          },
        }
      ]
    }
  ]
}

Cleaning Up: Avoiding Unexpected Bills 🧹

It’s always a good practice to clean up resources when you’re done experimenting. Running terraform destroy will remove both VMs and all related resources. Once executed, the state file will be empty, reflecting that no resources are managed by Terraform.

Remember, leaving resources running can lead to unexpected costs. πŸ’Έ By cleaning up after your experiments, you ensure responsible resource management and avoid any surprises on your bill. 😌

Wrapping Up: The Adventure Continues 🎁

In this article, we’ve explored how the Terraform State File acts as a trusty map πŸ—ΊοΈ, guiding Terraform through the infrastructure landscape. We’ve seen how it tracks changes, maps dependencies, and enables collaboration. 🀝

But the journey doesn’t end here! In the next article, we’ll dive even deeper into the world of Terraform, exploring advanced concepts and real-world use cases. 🌍 Stay tuned for more exciting adventures! πŸš€

Until then, keep exploring, keep learning, and Happy Terraforming! 🌟