Retrieving Resource IDs in Terraform – The Terraform Data Block
Also read – Terraform external data querying
The Terraform Data Block – Retrieving a Project Id for a GCP project
data “google_project” “project” {
}
output "project_number" {
value = data.google_project.project.number
}
Terraform Destroy and the Data Block
When executing the terraform destroy command on our Terraform configuration, Terraform does not perform a destroy action on the resource called by the data block. It is a read only block.
The data block is also called when executing the terraform plan command, so your external resource must be present before you execute the terraform plan and terraform apply commands.
Searching for Projects using the terraform data block
One can apply a filter to search for specific projects – e.g. projects about to be deleted
data "google_projects" "my-organization-projs" {
filter = "parent.id:23232323 lifecycleState:DELETE_REQUESTED"
}
data "google_project" "deletion-candidate" {
project_id = data.google_projects.my-organization-projs.projects[0].project_id
}
Summary
Instead of hard coding IDs of resources, the terraform data block allows dynamic retrieval of resource IDs. It also allows searching / filtering based a filter inside the data block.
Need an experienced Cloud Networking or a Cloud Data Protection Expert? Anuj has successfully delivered over a dozen deployments on each of the public clouds (AWS/GCP/Azure) including several DevSecOps engagements. Set up a time with Anuj Varma.
Leave a Reply