This is a really simple Terraform tip, but it is a real time saver when you need to create multiple resources of the same type.
Let’s take my previous article as an example. Throughout it I enable a number of Google services in my project using the google_project_service
resource:
resource "google_project_service" "pubsub" {
project = google_project.project.project_id
service = "pubsub.googleapis.com"
}
resource "google_project_service" "cloudbuild" {
project = google_project.project.project_id
service = "cloudbuild.googleapis.com"
}
resource "google_project_service" "cloudfunctions" {
project = google_project.project.project_id
service = "cloudfunctions.googleapis.com"
}
Instead of of declaring the resources one by one, you can iterate over a list using a for_each
statement:
resource "google_project_service" "services" {
project = google_project.project.project_id
service = each.value
for_each = toset([
"pubsub.googleapis.com",
"cloudbuild.googleapis.com",
"cloudfunctions.googleapis.com",
])
}
Basically, what we do is convert the list to a set, and then create a service resource for every value in the list. In case you need to add a depends_on
reference, you can still reference the inidividual resources like thus: google_project_service.services["pubsub.googleapis.com"]
.
You can do a lot of other things with for_each
and sets, so make sure to check out the docs. Combining it with input variables makes it really easy to create really flexible, and reusable, modules.