What is Terraform State and Terraform State File Examples

What is Terraform State and Terraform State File Examples

After running terraform plan, In order to effectively determine the changes that it needs to make our desired configuration. Terraform must know the current state of resources and Terraform must store state about our managed infrastructure and configuration. To ensure correct operation, Terraform retains a copy of the most recent set of dependencies within the state.

Terraform stores the state of our infrastructure in a file called “terraform.tfstate”. When we provision our infrastructure with terraform, this terraform.tfstate state file will be created in the local workspace. Terraform will sync all resources in the state file for every plan and apply commands. 

The below example shows how the terraform will store the state of ec2 configuration in terraform.tfstate file.

Create Ec2 instance With Terraform

To create ec2 instance with terraform we need two files one for aws provider and another one is ec2 configuration file. let me show you the files.

provider.tf

root@ip-172-31-37-35:~/devops#

cat provider.tf


provider "aws" {
access_key = "DFNIAERUQQNWFJNFJE"
secret_key = "J6nd8dOOFNFDNJFDNDNDNNDNFbwbqa+FFFjg"
region = "us-east-1"
}

ec2.tf

root@ip-172-31-37-35:~/devops# cat ec2.tf


resource "aws_instance" "web" {
ami = "ami-00068cd7555f543d5"
instance_type = "t2.micro"

tags = {
Name = "HelloWorld"
}
}

Let Run Terraform apply

terraform apply command will create our infrastructure in aws.

root@ip-172-31-37-35:~/devops# terraform apply

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_instance.web will be created
  + resource "aws_instance" "web" {
      + ami                          = "ami-00068cd7555f543d5"
      + arn                          = (known after apply)
      + associate_public_ip_address  = (known after apply)
      + availability_zone            = (known after apply)
      + cpu_core_count               = (known after apply)
      + cpu_threads_per_core         = (known after apply)
      + get_password_data            = false
      + host_id                      = (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                     = (known after apply)
      + 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" = "HelloWorld"
        }
      + tenancy                      = (known after apply)
      + volume_tags                  = (known after apply)
      + vpc_security_group_ids       = (known after apply)

      + ebs_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + snapshot_id           = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }

      + ephemeral_block_device {
          + device_name  = (known after apply)
          + no_device    = (known after apply)
          + virtual_name = (known after apply)
        }

      + metadata_options {
          + http_endpoint               = (known after apply)
          + http_put_response_hop_limit = (known after apply)
          + http_tokens                 = (known after apply)
        }

      + network_interface {
          + delete_on_termination = (known after apply)
          + device_index          = (known after apply)
          + network_interface_id  = (known after apply)
        }

      + root_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }
    }

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

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

  Enter a value: yes

aws_instance.web: Creating...
aws_instance.web: Still creating... [10s elapsed]
aws_instance.web: Still creating... [20s elapsed]
aws_instance.web: Creation complete after 22s [id=i-0f956a7e34f8b8204]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Verify the files in local workspace

root@ip-172-31-37-35:~/devops# ls -ltr
total 12

-rw-r--r-- 1 root root  133 Nov  8 02:08 provider.tf
-rw-r--r-- 1 root root  123 Nov  8 02:10 ec2.tf
-rw-r--r-- 1 root root 3187 Nov  8 02:13 terraform.tfstate

you can see now terraform.tfstate is created after creating infrastructure in aws. lets see how terraform state file looks like

Terraform State File Example

root@ip-172-31-37-35:~/devops# cat terraform.tfstate

{
  "version": 4,
  "terraform_version": "0.12.18",
  "serial": 1,
  "lineage": "e75f09d7-abc0-31fb-ea16-32ec0db4c90e",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "aws_instance",
      "name": "web",
      "provider": "provider.aws",
      "instances": [
        {
          "schema_version": 1,
          "attributes": {
            "ami": "ami-00068cd7555f543d5",
            "arn": "arn:aws:ec2:us-east-1:787645912603:instance/i-0f956a7e34f8b8204",
            "associate_public_ip_address": true,
            "availability_zone": "us-east-1d",
            "cpu_core_count": 1,
            "cpu_threads_per_core": 1,
            "credit_specification": [
              {
                "cpu_credits": "standard"
              }
            ],
            "disable_api_termination": false,
            "ebs_block_device": [],
            "ebs_optimized": false,
            "ephemeral_block_device": [],
            "get_password_data": false,
            "hibernation": false,
            "host_id": null,
            "iam_instance_profile": "",
            "id": "i-0f956a7e34f8b8204",
            "instance_initiated_shutdown_behavior": null,
            "instance_state": "running",
            "instance_type": "t2.micro",
            "ipv6_address_count": 0,
            "ipv6_addresses": [],
            "key_name": "",
            "metadata_options": [
              {
                "http_endpoint": "enabled",
                "http_put_response_hop_limit": 1,
                "http_tokens": "optional"
              }
            ],
            "monitoring": false,
            "network_interface": [],
            "outpost_arn": "",
            "password_data": "",
            "placement_group": "",
            "primary_network_interface_id": "eni-09fc1f3a198a22b3f",
            "private_dns": "ip-172-31-81-162.ec2.internal",
            "private_ip": "172.31.81.162",
            "public_dns": "ec2-3-87-198-31.compute-1.amazonaws.com",
            "public_ip": "3.87.198.31",
            "root_block_device": [
              {
                "delete_on_termination": true,
                "device_name": "/dev/xvda",
                "encrypted": false,
                "iops": 100,
                "kms_key_id": "",
                "volume_id": "vol-01f1dbb565c4aa130",
                "volume_size": 8,
                "volume_type": "gp2"
              }
            ],
            "secondary_private_ips": [],
            "security_groups": [
              "default"
            ],
            "source_dest_check": true,
            "subnet_id": "subnet-99c291b7",
            "tags": {
              "Name": "HelloWorld"
            },
            "tenancy": "default",
            "timeouts": null,
            "user_data": null,
            "user_data_base64": null,
            "volume_tags": {},
            "vpc_security_group_ids": [
              "sg-5184d50a"
            ]
          },
          "private": "eyJlsasMmJmYsasjczMC1lYsasa2FdshLTExZTYtOasasGY4OC0zNDM2M2JjN2Mfffs0YzAiOnsiY3JlYXRlIjo2MDAwMDAwMDAwdadaMDAsImRMDAwMCwidXBkYXRlIjdfdfo2MDAwMDAwMDAwMDBfdfd9LCJzY2hlbWFfdmVyc2lvbsdsiI6IjEifQ=="
        }
      ]
    }
  ]
}

Terraform state file will have all configuration details about our newly created ec2 instance. If you change anything in the ec2.tf and apply the terraform, terraform will compare the changes with this terraform.tfstate statefile and apply the changes only.

Leave a Reply

Your email address will not be published. Required fields are marked *