Managing Infra using Terraform State files

Jigar R
2 min readJan 23, 2025

--

In the post managing-infra-with-terraform, I mentioned that Terraform state file keeps an inventory of resources managed by Terraform. Terraform helps to automate infrastructure on various cloud providers.

Securely store the State file

By default, Terraform generates “terraform.tfstate” file. This is fine for small personal projects. However, for big organizations it would make sense to put terraform.tfstate file in a central location.

How about Github/Gitlab?

The terraform state has password/token etc in plaintext. Therefore, one needs to store it securely. This is why, It is recommended to use encrypted place to store the state file. Additionally, Terraform uses locking mechanism to prevent multiple people from making changes to the state file at the same time. In the case of AWS, the combination of S3 and DynamoDB can be used to store the state file. Alternatively, one can also use Terraform cloud.

Fetch information from the State file

Assume, project-A has been setup and user has ran “terraform init; terraform apply” command. You can use terraform command to get the full list of resources that are managed by terraform.

 ➜  terraform state list
aws_instance.test_vm_1
aws_s3_bucket.test_bucket
....

What if someone created resources by other means?

On one hand, Project-A consists of various resources. On the other hand, we have cloud-infrastructure.

  • If a new resource was added to our cloud-infrastructure using other methods then Terraform would not know about those changes. Terraform can only manage resources that are specified in the Project.
  • If a new resource is added to Project-A then upon running “terraform apply”, it would get created.

When a resource is created, ID gets generated which can be different in each run. Terraform stores ID information in terraform.tf file. Using ID, Terraform can find if the resource has been generated or not.

Assume we created a virtual-machine using Terraform. If we delete it using website and run “terraform apply” command; it would create a new virtual-machine.

Add resource to the State file

If a resource was created on the cloud-infrastructure by command-line or website directly then Terraform State file would not have any information about such resources. But we can add them to state file in 2 steps:

  1. Add resource in the project
  2. Run “terraform import ” command

--

--

Jigar R
Jigar R

Written by Jigar R

DevOps Engineer | feel free to reach out to me | LinkedIn — https://www.linkedin.com/in/jigarrathod/

No responses yet