How to Create Terraform State File for Current Resources

2024/01/032 min read
bookmark this
Responsive image

Table of Contents

  1. Introduction
  2. Switch to the Correct Workspace Environment
  3. Pull Latest State File
  4. Test by Running Terraform Plan
  5. Run Import to Update State File
  6. Conclusion

Introduction

When working with Terraform and existing cloud resources, you may need to import those resources into your Terraform state file. This blog shows how to do that.

Switch to the Correct Workspace Environment

For example, you can run the following command to create a QA workspace environment:

terraform workspace new qa
or
terraform workspace select qa

Pull Latest State File

Run this command to get the latest state file for the environment from storage:

terraform state pull

This is what you get when you run terraform state pull — basically nothing is saved to the current workspace state:

{
  "version": 4,
  "terraform_version": "1.4.6",
  "serial": 1,
  "lineage": "59eb4435-e702-29bf-71de-1231231",
  "outputs": {},
  "resources": [],
  "check_results": null
}

Test by Running Terraform Plan

If at this point you run terraform plan, you'll see some changes if you have active resources in your local files. This is incorrect if the same resource already exists in GCP, and you don't want to run terraform apply, which would end up creating duplicate resources or throwing errors.

Run Import to Update State File

For instance, if you have an existing GCP BigQuery schedule query, you can run the following command to sync the state file:

terraform import google_bigquery_data_transfer_config.job projects/1233/locations/us/transferConfigs/12312312

The above command should update the state file, and if you run terraform plan again, you should not see any changes.

Conclusion

Importing existing resources into your Terraform state file ensures that Terraform is aware of your current infrastructure. This prevents duplicate resource creation and keeps your state file in sync with your actual cloud resources.