【问题标题】:Terraform dynamic blockTerraform 动态块
【发布时间】:2020-08-18 19:51:38
【问题描述】:

我在 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_config 变量时创建一个network_configiration 块。如果我没有定义它,我希望模块不要打扰创建块。 我收到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 中使用动态块,但我希望能够理解它。 谢谢

【问题讨论】:

    标签: amazon-ecs terraform-provider-aws terraform0.12+


    【解决方案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)
        }
    }
    

    希望对你有帮助

    【讨论】:

    • 只需将变量 network_config 默认设置为空列表 []。如果你不将该值传递给模块,它将不会被配置
    • 您的建议出现以下错误:An argument named "network_config" is not expected here. 看来我无法以这种方式指定块
    • Network_config 是您需要指定的变量。而且ecs service terraform资源肯定支持network_configuration的配置
    猜你喜欢
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 2022-07-07
    • 2021-12-31
    • 2021-09-29
    • 2021-09-02
    • 2021-08-11
    相关资源
    最近更新 更多