Loop over maps and assign value to local - Terraform

I am trying to pass the values s3 name and create_user into local block in main.tf so that both of them have the value in list and then I am passing list_of_bucket in local block in module s3 to create the buckets and looping of user_to_create in module s3_user to create the user if the boolean is set to true. All of these values are passed to variable.tf and then to main.tf

dev.tfvars

wea-nonprod = {
     
    services = {
     
      s3 = [
        sthree = {
          create_user = true,
        }
        sfour = {
          create_user = true,
        }
        sfive = {
          create_user = true,
        }
      ]
  }
}

variable.tf

variable "s3_buckets" {
  type = list(map)
}

main.tf

locals { 
  users_to_create = ""
  list_of_buckets = ""
}

module "s3" {
  source = "../../s3"
  name = join("-", [var.name_prefix, "s3"])    
  tags = merge(var.tags, {Name = join("-", [var.name_prefix, "s3"])})
  buckets = list_of_buckets
  sse_algorithm = "AES256"
  access_log_bucket_name = var.access_log_bucket_name
}

module "s3_user" {
  for_each = local.users_to_create 
  source = "./service-s3-bucket-user"
  name = join("-", [var.name_prefix, each.key])
  tags = var.tags
  bucket_arn = module.s3.bucket_arns[each.key]
  depends_on = [module.s3]
}

1 answer

  • answered 2021-07-27 15:57 Bryan Heden

    Just iterate over your wea-nonprod map:

    locals { 
      users_to_create = [ for name in var.wea-nonprod.services.s3 if name.create_user == true ]
      list_of_buckets = [ for bucket in var.wea-nonprod.services.s3 ]
    }
    

    And a few changes to your module blocks:

    
    module "s3" {
      source                 = "../../s3"
      name                   = "${var.name_prefix}-s3"
      tags                   = merge(var.tags, { Name = "${var.name_prefix}-s3" })
      buckets                = local.list_of_buckets
      sse_algorithm          = "AES256"
      access_log_bucket_name = var.access_log_bucket_name
    }
    
    module "s3_user" {
      count      = length(local.users_to_create)
      source     = "./service-s3-bucket-user"
      name       = "${var.name_prefix}${local.users_to_create[count.index]}"
      tags       = var.tags
      bucket_arn = module.s3.bucket_arns[local.users_to_create[count.index]]
      depends_on = [module.s3]
    }
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum