How to Create Terraform State file for current Resources

2024/01/032 min read
bookmark this
Responsive image

Switch to the correct workspace environments

For example, we can run below command to create qa workspace environment.

terraform workspace new qa
or
terraform workspace select qa

pull latest state file

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

terraform state pull

This is what I get when I run the terraform state pull, basically nothing 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 run the terraform plan

if at this point run the terraform plan, you'll see some changes if you have active resources at local file, which is wrong if the same resource already exist at the GCP, and you don't want to run terraform apply which will end up create duplicate resources or throw errors.

run import to update state file

For instance, I have current create GCP BQ schedule query, you can run below command to sync the state file.

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

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