简体   繁体   中英

Terraform trouble with list in a map using for_each

I'm trying to take each value from the list in the map and iterate over it with the description in a map for a prefix list but can't work out how.

Variable:

users = {
  "user1" = {
    description = ""
    secret_key_value = {
      username       = "user1"
      home_directory = "/user1/"
    }
    allowlist = ["200.0.0.1/32"]
  },
  "user2" = {
    description = ""
    secret_key_value = {
      username       = "user2"
      home_directory = "/user2/"
    }
    allowlist = ["200.0.0.5/32", "200.0.0.10/32"]
  }

Resource:

resource "aws_ec2_managed_prefix_list" "sftp" {
  count = local.prefix_list_enabled ? 1 : 0

  name           = "User Whitelist"
  address_family = "IPv4"
  max_entries    = 10

  dynamic "entry" {
    for_each = { 
      for k, v in var.users : k => v 
      if v.allowlist != "" || v.description != ""
    }

    content {
      cidr        = entry.value.allowlist
      description = entry.value.description
    }
  }
}

With the above, I'm getting "Inappropriate value for attribute "cidr": string required.". I need to break up the list values in the allowlist variable key and iterate through them with the description. Does anyone know how I can achieve this?

You have to flatten your users :

locals {
  users_flat = merge([
    for k,v in var.users: {
      for cidr in v.allowlist:
        "${k}-${cidr}" => {
            description = v.description
            secret_key_value = v.secret_key_value
            "cidr"  = cidr
        }
      }
  ]...)   
}

then

  dynamic "entry" {
    for_each = local.users_flat

    content {
      cidr        = entry.value.cidr
      description = entry.value.description
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM