将yaml用于地形tfvars



Im使用带有terraform的yaml,并尝试从yaml文件中检索值。这是我的yaml文件:

private_subnets :
projectName1 :
- cidr : "x.x.x.x/24"
az : "us-east-2"
- cidr : "x.x.x.x/24"
az : "us-east-2"
projectName2 :
- cidr : "x.x.x.x/24"
az : "us-east-2"

这是我的地形代码:

locals {
priv_subnets = yamldecode(file("./subnets.yaml"))["projectName1"]
priv_subnets_list = flatten([for subnet in local.priv_subnets :
{
"cidr"  =  subnet.cidr
"az"    =  subnet.az 
}
])
}
resource "aws_subnet" "private" {
for_each = {
for subnet in local.priv_subnets_list : subnet.cidr => subnet
}
vpc_id            = var.vpc_id
cidr_block        = each.value.cidr
availability_zone = each.value.az
}

我一次可以创建一个资源,你看到有什么选项可以优化这个代码来用相同的aws资源创建project1和project2子网吗(yaml文件将来可能会有更多的项目(

提前谢谢你,

你走在了正确的轨道上。您必须压平您的private_subnets,但有点不同:

locals {
priv_subnets = yamldecode(file("./subnets.yaml"))["private_subnets"]
priv_subnets_list = merge([
for project, subnets in local.priv_subnets: {
for idx, subnet in subnets: 
"${project}-${idx}" => {
cidr  =  subnet.cidr
az    =  subnet.az          
}
}
]...) # please, do NOT remove the dots
}

以上结果导致priv_subnets_list为:

{
"projectName1-0" = {
"az" = "us-east-2"
"cidr" = "x.x.x.x/24"
}
"projectName1-1" = {
"az" = "us-east-2"
"cidr" = "x.x.x.x/24"
}
"projectName2-0" = {
"az" = "us-east-2"
"cidr" = "x.x.x.x/24"
}
}

然后按如下方式使用:

resource "aws_subnet" "private" {
for_each          = local.priv_subnets_list 
vpc_id            = var.vpc_id
cidr_block        = each.value.cidr
availability_zone = each.value.az
}

相关内容

  • 没有找到相关文章

最新更新