获取 AWS 安全组 Terraform 模块的 ID

Get ID of AWS Security Group Terraform Module

我使用 this module 在 VPC 中创建了一个安全组。输出之一是 security_group_id,但我收到此错误:

│ Error: Unsupported attribute
│ 
│   on ecs.tf line 39, in resource "aws_ecs_service" "hello_world":
│   39:     security_groups = [module.app_security_group.security_group_id]
│     ├────────────────
│     │ module.app_security_group is a object, known only after apply
│ 
│ This object does not have an attribute named "security_group_id".

我需要 ECS 服务的安全组:

resource "aws_ecs_service" "hello_world" {
  name            = "hello-world-service"
  cluster         = aws_ecs_cluster.container_service_cluster.id
  task_definition = aws_ecs_task_definition.hello_world.arn
  desired_count   = 1
  launch_type     = "FARGATE"

  network_configuration {
    security_groups = [module.app_security_group.security_group_id]
    subnets         = module.vpc.private_subnets
  }

  load_balancer {
    target_group_arn = aws_lb_target_group.loadbalancer_target_group.id
    container_name   = "hello-world-app"
    container_port   = 3000
  }

  depends_on = [aws_lb_listener.loadbalancer_listener, module.app_security_group]
}

我明白安全组ID只有创建后才能知道。这就是为什么我在 ECS 节上添加了 depends_on 部分,但它一直返回相同的错误。

更新

我在 app_security_group 模块上将 count 指定为 1,这是我现在遇到的错误。

│ Error: Unsupported attribute
│ 
│   on ecs.tf line 39, in resource "aws_ecs_service" "hello_world":
│   39:     security_groups = module.app_security_group.security_group_id
│     ├────────────────
│     │ module.app_security_group is a list of object, known only after apply
│ 
│ Can't access attributes on a list of objects. Did you mean to access an attribute for a specific element of the list, or across all elements of the list?

更新二

这是模块声明:

module "app_security_group" {
  source  = "terraform-aws-modules/security-group/aws//modules/web"
  version = "3.17.0"

  name        = "${var.project}-web-sg"
  description = "Security group for web-servers with HTTP ports open within VPC"
  vpc_id      = module.vpc.vpc_id

  #   ingress_cidr_blocks = module.vpc.public_subnets_cidr_blocks
  ingress_cidr_blocks = ["0.0.0.0/0"]
}

我看了一下那个模块。问题是模块的版本 3.17.0 根本没有 security_group_id 的输出。您使用的是非常旧的版本。

site 的最新版本是 4.7.0,您可能想升级到这个版本。事实上,4.0.0 以上的任何版本都有 security_group_id,因此您至少需要 4.0.0

由于您正在使用计数,请尝试以下。

network_configuration {
    security_groups = [module.app_security_group[0].security_group_id]
    subnets         = module.vpc.private_subnets
  }