首页 > 解决方案 > Terraform ECS 任务定义 - 动态嵌套 EFS 卷

问题描述

我正在尝试将 terraform 模块与 ECS 一起使用。问题是对于某些应用程序,我需要在任务定义中定义的 EFS 卷,而在其他应用程序中,我根本不需要它。我需要一种有条件地添加卷块的方法。我已经尝试过嵌套的动态块,但无法让它们工作。

这是动态嵌套卷配置块:

  dynamic "volume" {
    for_each = var.volumes
    content {
      name = volume.key
      host_path = volume.value.host_path

      dynamic "efs_volume_configuration" {
        for_each = volume.value.efs_volume_configuration
        content {
          file_system_id = efs_volume_configuration.value.file_system_id

          dynamic "authorization_config" {
            for_each = efs_volume_configuration.value.authorization_config
            content {
              access_point_id = authorization_config.value.access_point_id
              iam = authorization_config.value.iam
            }
          }
        }
      }
    }

这是我的变量(我已经更改了很多次,但仍然无法正确设置):

variable "volumes" {
  description = "(Optional) A set of volume blocks that containers in your task may use"
  type = list(object({
    host_path = string
    name      = string
    efs_volume_configuration = list(object({
      file_system_id          = string
      authorization_config = list(object({
        access_point_id = string
        iam             = string
      }))
    }))
  }))
  default = []
}

这是我在我想要的应用程序中声明卷块的值的地方:

  volumes = [{
    name      = "efs-storage-rasa"
    host_path = "/model"
    efs_volume_configuration = [{
      file_system_id         = aws_efs_file_system.filessystem.id
      authorization_config = [{
        access_point_id    = aws_efs_access_point.filessystem_access_point.id
        iam                = "ENABLED"
      }]
    }]
  }]

注意:这只是我快速拼凑的一个测试堆栈,看看我是否可以让它工作。我只需要能够有条件地将 EFS 卷块添加到 ECS 服务。我不想为 ECS 服务创建两个模块(一个用于需要卷时,一个用于不需要卷时)是我可以避免的。

谢谢你!

标签: terraform

解决方案


你可以做这样的事情。

dynamic "volume" {
    for_each = var.volumes == null ? [] : [1]
    content {
      name = volume.key
      host_path = volume.value.host_path

      dynamic "efs_volume_configuration" {
        for_each = volume.value.efs_volume_configuration
        content {
          file_system_id = efs_volume_configuration.value.file_system_id

          dynamic "authorization_config" {
            for_each = efs_volume_configuration.value.authorization_config
            content {
              access_point_id = authorization_config.value.access_point_id
              iam = authorization_config.value.iam
            }
          }
        }
      }
    }

推荐阅读