Terraform,创建列表元素为值的地图

问题描述 投票:0回答:1

我正在尝试在 terraform 中解析这个变量。主要目标是创建“group”=“member”类型的地图。我在变量中设置的类型正确吗?下面提供了所需的输出。

variable "iam" "this"{
  type = map(map(list(string)))
  default = {
    "admins" = {
      "user" = [
        "[email protected]",
        "[email protected]"
      ]
      "service_principal" = [
        "dpaf2-dev-sa"
      ]
    }
    "dev"   = {
      "user" = [
        "[email protected]",
        "[email protected]"
      ]
      "service_principal" = []
    }
    "ops"   = {
      "user" = [
        "[email protected]",
      ]
      "service_principal" = [
        "dpaf2-dev-sa",
        "dpaf2-iacda-app-id",
      ]
    }
  }
}

所需输出:

{
"admins" = "[email protected]"
"admins" = "[email protected]"
"admins" = "dpaf2-dev-sa"
"dev"    = "[email protected]"
"dev"    = "[email protected]"
"ops"    = "[email protected]"
"ops"    = "dpaf2-dev-sa"
"ops"    = "dpaf2-iacda-app-id"
}
list azure loops dictionary terraform
1个回答
1
投票

从此开始并操纵它以满足您的确切需求。使用映射、数组和嵌套来构造资源的方法有很多。

locals {
  service_principal = {
    admin = ["dpaf2-dev-sa"]
    dev   = []
    ops = [
      "dpaf2-dev-sa",
      "dpaf2-iacda-app-id",
    ]
  }
  users = {
    admin = [
      "[email protected]",
      "[email protected]"
    ]
    dev = [
      "[email protected]"
    ]
    ops = [
      "[email protected]"
    ]
  }
  result = flatten([for role in keys(local.users) : [for user in local.users[role] :
  { role = role, user = user, principals = local.service_principal[role] }]])
}

resource "null_resource" "users" {
  count = length(local.result)
  provisioner "local-exec" {
    command = "echo user: $USER has role: $ROLE and principals: $SERVICE_PRINCIPAL >> ouput.txt"

    environment = {
      USER              = local.result[count.index].user
      ROLE              = local.result[count.index].role
      SERVICE_PRINCIPAL = join(", ", local.result[count.index].principals)
    }
  }
}

如果你跑步:

  1. terraform init
  2. terraform plan
  3. terraform apply --auto-approve

然后检查您的目录中是否有名为 output.txt 的文件,其中将包含

user:[email protected] has role:admin and principals: dpaf2-dev-sa
user:[email protected] has role:dev and principals:
user:[email protected] has role:ops and principals: dpaf2-dev-sa, dpaf2-iacda-app-id
user:[email protected] has role:admin and principals: dpaf2-dev-sa

我知道文本文件不是您想要的输出,但循环只是演示如何迭代局部变量。

同样,有多种排序和切片方法。我避免了您想要的输出,因为地图不能有重复的键,所以它永远不会工作。

如果您想单独查看

result
,您可以这样做:

  1. terraform console
  2. local.result

它将出现在终端中。要退出控制台,请输入

exit

© www.soinside.com 2019 - 2024. All rights reserved.