在 terraform 中使用局部变量进行棘手的变量转换

Tricky conversion of variable using locals in terraform

寻找可能的 solution/approach 满足以下要求。

我有一个变量如下

nodes= {
  "type1" = { 
     max_size = 4
     tags = { "key1" = "value1" 
               "key2" = "value2"   }  # structure of tags can be changed as needed
}

然后我有一个当地人会引用这个标签在 asg

中使用
locals {
    for nodetype, nodeconfig in var.nodes
    ..
    ..
      node_tags = nodeconfig.tags
}

local.node_tags 必须采用下面的最终形式

{
  "key" = "key1"
  "value" = "value1"
  "propagate_at_launch" = "true"
},
{
 "key" = "key2"
  ...
  ...
}

我需要在 asg 中使用这些

resource "aws_autoscaling_group" "nodes" {
  for_each = { for i in local.nodes ....
...
...
tags = each.value.node_tags

 }

类似用例 - https://github.com/terraform-aws-modules/terraform-aws-autoscaling#tags

我尝试了下面的方法..看起来很丑而且不起作用。

locals {
    for nodetype, nodeconfig in var.nodes
    ..
    ..
      node_tags = {for i in nodeconfig.tags : "{i}" => { 
          "key" = keys(i),
          "value" = values(i),
          "propagate_at_launch" = "true"
           } 
     }
}

这个怎么样:

variable "nodes" {

    default = {
        "type1" = { 
           max_size = 4
           tags = { "key1" = "value1" 
                     "key2" = "value2"
                  } 
       },
       
        "type2" = { 
           max_size = 4
           tags = { "key11" = "value11" 
                    "key22" = "value22"
                  } 
       },       
    }
}


locals {

  node_tags = values(merge([for nodetype, nodeconfig in var.nodes: 
                 {for tag_key , tag_value in nodeconfig.tags:
                    "${nodetype}-${tag_key}-${tag_value}" => 
                                {key = tag_key
                                 value = tag_value
                                "propagate_at_launch" = "true"}
                 }                          
              ]...))

}




output "test" {

  value = local.node_tags

}

给出:

test = [
  {
    "key" = "key1"
    "propagate_at_launch" = "true"
    "value" = "value1"
  },
  {
    "key" = "key2"
    "propagate_at_launch" = "true"
    "value" = "value2"
  },
  {
    "key" = "key11"
    "propagate_at_launch" = "true"
    "value" = "value11"
  },
  {
    "key" = "key22"
    "propagate_at_launch" = "true"
    "value" = "value22"
  },
]