Terraform IAC: for_each & locals

GCP Terraform Series 2

for_each is a meta-argument defined by the Terraform language. It can be used with modules and with every resource type. The for_each meta-argument accepts a map or a set of strings and creates an instance for each item in that map or set.

Unlike variables found in programming languages, Terraform’s locals do not change values during or between Terraform runs such as plan, apply, or destroy. You can use locals to give a name to the result of any Terraform expression and re-use that name throughout your configuration.

locals {  
svc_roles = ["roles/compute.viewer", "roles/pubsub.viewer"]

Here I have created roles in locals for my service account and called it svc_roles. You need to use for_each as it is the list (svc_roles)

module "my_service_account" {  
source = "git::ssh://git@github.com/<your-company>/tf-module-gcp-cio-service-accounts?ref=v0.1.0"
project_id = "project_id"
display_name = "my test Service Account"
account_id = "my-service-account-name"
resource "google_project_iam_member" "my_service_acc_roles" {
for_each = toset(local.svc_roles)
project = "project_id"
member = serviceAccount:${module.my_service_account.email}"
role = each.value

Sometimes you need to apply condition statements in the locals.

my_labels = "${var.environment == "PROD" ? "<P>" : "D"}"
vm_labels = "${coalesce("tools-",local.my_labels)}"



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store