amazon-ecs - Terraform 动态块
问题描述
我在 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 中使用动态块,但我希望能够理解它。谢谢
解决方案
所以你的本地人应该如下:
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)
}
}
希望有帮助
推荐阅读
- java - IntelliJ - Maven 添加外部 jar 文件但 java.lang.NoClassDefFoundError
- google-cloud-dataflow - 带有“lookbehind”的流式光束管道
- html - ionicons没有出现,它之前工作过
- sql - SQL根据同一ID内的值修改数据
- node.js - 创建订单时在 nodejs 上注册 webhook
- html - Input[type=number] 不带多个小数
- azure - AZCopy 可以从最近的文件和文件夹开始执行复制吗
- laravel - Laravel 8 上传下载文件
- javascript - iframe 可以访问主窗口对象 [如登录令牌] 吗?
- vb.net - VB.NET GroupBy 多个属性