Skip to content

Terraform: How to import existing resources

Sometimes you want to get an identical resource from another project for testing purposes or you want to add an existing resource under Terraform management. Here's how you can import existing resources to your Terraform configurations:

GCP

Single resource

https://cloud.google.com/docs/terraform/resource-management/import 1. Identify the resource address to be imported 1. This justs means the resource type as defined by the Terraform Google module. For example google_compute_instance is a resource type. 2. Write the resource in Terraform:

resource "google_storage_bucket" "bucket123" {

}
  1. Construct the import statement by using the resource address and ID, as follows:
terraform import google_storage_bucket.bucket123 sample-project/my-bucket
  1. Copy the resource settings from the state to a .tf file:
terraform state show google_sql_database_instance.pg1_stable > create-db-instance-pg1-stable-imported.tf
  1. If you're only doing this for testing purposes, and not to move existing resources under Terraform management, remove the imported resource's state from the state file:
terraform state rm google_sql_database_instance.pg1_stable

Result:

Removed google_sql_database_instance.pg1_stable
Successfully removed 1 resource instance(s). 

Special cases

Importing IAM bindings (permissions)

The command always expects only two arguments: name of the local resoi

terraform import google_project_iam_member.confidential_sa_ops_agent "projects/attracs-services-195009 roles/monitoring.metricWriter serviceAccount:confidential@attracs-services-195009.iam.gserviceaccount.com"

GCP Troubleshooting

Import cannot find binding

Error: Cannot find binding for "project \"projects/attracs-services-195009\"" with role "roles/monitoring.metricsWriter", member "serviceAccount:confidential@attracs-services-195009.iam.gserviceaccount.com", and condition title ""

Make sure the details you have given are correct. Double-check how the role is written with gcloud iam roles list