我无法在Terraform中创建动态块。我正在尝试使用模块创建ECS服务。在模块中,我想指定仅当存在变量时才创建network_configuration
块。
这是我的模块代码:
resource "aws_ecs_service" "service" {
name = var.name
cluster = var.cluster
task_definition = var.task_definition
desired_count = var.desired_count
launch_type = var.launch_type
load_balancer {
target_group_arn = var.lb_target_group
container_name = var.container_name
container_port = var.container_port
}
dynamic "network_configuration" {
for_each = var.network_config
content {
subnets = network_configuration.value["subnets"]
security_groups = network_configuration.value["security_groups"]
assign_public_ip = network_configuration.value["public_ip"]
}
}
}
接下来是实际服务的代码:
module "fargate_service" {
source = "./modules/ecs/service"
name = "fargate-service"
cluster = module.ecs_cluster.id
task_definition = module.fargate_task_definition.arn
desired_count = 2
launch_type = "FARGATE"
lb_target_group = module.target_group.arn
container_name = "fargate_definition"
container_port = 8000
network_config = local.fargate_network_config
}
最后,我的本地文件如下所示:
locals {
fargate_network_config = {
subnets = module.ec2_vpc.private_subnet_ids
public_ip = "false"
security_groups = [module.fargate_sg.id]
}
}
使用上述配置,我希望仅在存在network_configiration
变量时创建一个network_config
块。如果我没有定义它,我希望模块不要麻烦创建该块。
我收到Invalid index
错误。
network_configuration.value is tuple with 3 elements
The given key does not identify an element in this collection value: a number
is required.
我的代码有什么问题?这是我第一次在Terraform中使用动态块,但我希望能够理解它。 谢谢
答案 0 :(得分:1)
所以您的本地人应该如下:
locals {
fargate_network_config = [
{
subnets = module.ec2_vpc.private_subnet_ids
public_ip = "false"
security_groups = [module.fargate_sg.id]
}
]
}
然后将变量network_config
固定为列表。
最后,您的动态区块:
dynamic "network_configuration" {
for_each = var.network_config
content {
subnets = lookup(network_configuration.value, "subnets", null)
security_groups = lookup(network_configuration.value, "security_groups", null)
assign_public_ip = lookup(network_configuration.value, "public_ip", null)
}
}
希望有帮助