gpt4 book ai didi

amazon-web-services - 具有动态内容的 Terraform 动态 block

转载 作者:行者123 更新时间:2023-12-05 03:40:57 25 4
gpt4 key购买 nike

我正在尝试为 aws_route_table 创建一个 terraform 模块,这里是这个资源定义的一个例子:

resource "aws_route_table" "example" {
vpc_id = aws_vpc.example.id

route {
cidr_block = "10.0.1.0/24"
gateway_id = aws_internet_gateway.example.id
}

route {
ipv6_cidr_block = "::/0"
egress_only_gateway_id = aws_egress_only_internet_gateway.example.id
}

tags = {
Name = "example"
}
}

我正在尝试通过使用动态 block 使其更具动态性。问题是我总是必须在内容 block 中定义键

resource "aws_route_table" "example" {
...

dynamic "route" {
for_each = var.route
content {
cidr_block = route.value.cidr_block
gateway_id = route.value.gateway_id
}
}

...
}

所以在这种情况下,我需要编写两个动态 block ,一个用于包含 cidr_blockgateway_id 的内容,一个用于包含 ipv6_cidr_block< 的内容egress_only_gateway_id

有没有办法在不显式定义键的情况下做到这一点。像这样:

   dynamic "route" {
for_each = var.route
content {
var.route.map
}
}

最佳答案

是的,您可以动态创建route,因为 block route 充当Attributes as Blocks .所以你可以做(​​例子)

# define all your routes in a variable (example content)

variable "routes" {

default = [
{
cidr_block = "0.0.0.0/0"
gateway_id = "igw-0377483faa64bf010"
},
{
cidr_block = "172.31.0.0/20"
instance_id = "i-043fc97db72ad1b59"
}
]
}


# need to provide default values (null) for all possibilities
# in route

locals {

routes_helper = [
for route in var.routes: merge({
carrier_gateway_id = null
destination_prefix_list_id = null
egress_only_gateway_id = null
ipv6_cidr_block = null
local_gateway_id = null
nat_gateway_id = null
network_interface_id = null
transit_gateway_id = null
vpc_endpoint_id = null
instance_id = null
gateway_id = null
vpc_peering_connection_id = null
}, route)
]

}


resource "aws_route_table" "example" {
vpc_id = aws_vpc.example.id

# route can be attribute, instead of blocks
route = local.routes_helper

tags = {
Name = "example"
}
}

文档一般不建议使用它,但我认为路由是一个很好的例子,它可以接受。

关于amazon-web-services - 具有动态内容的 Terraform 动态 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67947772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com