Don’t Be a Karen: Rebuilding the Terraform State File and Best Practices for Backend State File Storage
By: Brandon Prasnicki | Technical Architect
It happened. It finally happened. After talking to the manager, Contractor Karen quit. She was solely responsible for managing the project’s cloud architecture with Terraform. Now that Karen left, a new resource needs to take her place and continue managing and building the cloud infrastructure. Luckily, the terraform code was in a git repository (excluding the .terraform dir), but no one is sure if it is up to date, and the state file was local to Karen’s machine and not recoverable. What to do now?
- Don’t be a Karen. Make it a company policy to configure the backend. A Terraform backend is the configuration on how (and where) to store your Terraform state in a centralized, remote location.
- – A shared resource account or a production account is a good place to store terraform states.
- – Having a remote backend is also a must for shared development environments.
- Use a versioned bucket. State files can get corrupt, and you may need to revert to an old version of the state file.
- Configure the backend. For each unique terraform state, make sure to update the key path to be reflective of the workload architecture the state file is associated with:
If it’s already too late, and you have been victimized by a Karen, then it’s time to rebuild the state file.
- Depending on the size of your workload, this will be a time-consuming process.
- For each resource, you will need to identify the key needed to import into the state. For this key, reference the terraform documentation. For example:
- a. For a VPC you would reference this page and see that to import a VPC you would need the VPC ID:
terraform import aws_vpc.test_vpc vpc-a01106c2 - b. For an EC2 instance you would reference this page and see that to import an EC2 instance you would need the EC2 instance ID:
terraform import aws_instance.web i-12345678
- a. For a VPC you would reference this page and see that to import a VPC you would need the VPC ID:
- After each import, you should run a plan and make sure the plan does not expect any changes you are not anticipating and correct them in the code if applicable. This process will take time.
Contact us for more help on rebuilding Terraform State Files!