如何用Terraform将多个YAML安全组配置合并为对象变量?
问题
我有两个存储安全组配置的YAML文件:
security_group_1.yaml
description: "description 1" sg_rule: - { type: "ingress", from_port: 1433, to_port: 1433, protocol: "TCP", cidr_block: ["10.0.0.0/24"] } - { type: "egress", from_port: 1433, to_port: 1433, protocol: "TCP", cidr_block: ["10.0.0.0/24"] }
security_group_2.yaml
description: "description 2" sg_rule: - { type: "ingress", from_port: 1433, to_port: 1433, protocol: "TCP", cidr_block: ["10.0.0.0/24"] } - { type: "egress", from_port: 1433, to_port: 1433, protocol: "TCP", cidr_block: ["10.0.0.0/24"] }
需要通过Terraform读取这两个文件并合并为如下结构的对象,最终能通过output["security_group_1"]["description"]这类方式访问对应安全组的属性:
{ security_group_1 = { description = "description 1" sg_rule = [ { type = "ingress", from_port = 1433, to_port = 1433, protocol = "TCP", cidr_block = ["10.0.0.0/24"] }, { type = "egress", from_port = 1433, to_port = 1433, protocol = "TCP", cidr_block = ["10.0.0.0/24"] } ] }, security_group_2 = { description = "description 2" sg_rule = [ { type = "ingress", from_port = 1433, to_port = 1433, protocol = "TCP", cidr_block = ["10.0.0.0/24"] }, { type = "egress", from_port = 1433, to_port = 1433, protocol = "TCP", cidr_block = ["10.0.0.0/24"] } ] } }
解决方案
步骤1:修正YAML语法错误
原YAML文件存在语法问题(用.代替冒号、;代替逗号),会导致Terraform解析失败,需先修正为标准YAML格式(如上述问题中给出的修正后文件)。
步骤2:Terraform配置实现
通过file()读取文件内容,yamldecode()解析YAML为对象,再合并成目标嵌套结构:
# 读取并解析YAML文件为本地变量 locals { security_group_1 = yamldecode(file("${path.module}/security_group_1.yaml")) security_group_2 = yamldecode(file("${path.module}/security_group_2.yaml")) # 合并为目标结构 merged_security_groups = { security_group_1 = local.security_group_1 security_group_2 = local.security_group_2 } } # 输出合并后的完整结构 output "merged_security_groups" { value = local.merged_security_groups } # 示例:单独输出security_group_1的描述 output "sg1_description" { value = local.merged_security_groups["security_group_1"]["description"] }
验证效果
执行terraform apply后,可通过以下方式访问属性:
- 访问security_group_1的描述:
local.merged_security_groups["security_group_1"]["description"] - 访问security_group_2的第一条规则:
local.merged_security_groups["security_group_2"]["sg_rule"][0]
内容的提问来源于stack exchange,提问作者minnie
相关产品推荐
相关产品推荐

