【问题标题】:putting security group ids of a vpc in a list using terraform使用 terraform 将 vpc 的安全组 ID 放入列表中
【发布时间】:2021-08-20 23:54:45
【问题描述】:

在尝试创建 vpc 端点时,我必须在 vpc 中动态创建安全组,然后将其附加到同一 terraform 计划中的 vpc 端点。有没有办法可以使用 terraform 将 VPC 的所有安全组 ID 放入列表中?

【问题讨论】:

  • 进展如何?还是不清楚怎么做?

标签: amazon-web-services terraform aws-security-group


【解决方案1】:

如下图所示创建vpc

resource "aws_vpc" "main" {
id = var.vpc_id
cidr_block = "10.0.0.0/16"
}

创建安全组

resource "aws_security_group" "sg1" {
name        = "allow_tls"
description = "Allow TLS inbound traffic"
vpc_id      = aws_vpc.main.id

ingress {
description      = "TLS from VPC"
from_port        = 443
to_port          = 443
protocol         = "tcp"
cidr_blocks      = [aws_vpc.main.cidr_block]
ipv6_cidr_blocks = [aws_vpc.main.ipv6_cidr_block]
}

egress {
from_port        = 0
to_port          = 0
protocol         = "-1"
cidr_blocks      = ["0.0.0.0/0"]
ipv6_cidr_blocks = ["::/0"]
}

tags = {
Name = "allow_tls"
}
}

创建 vpc 端点,从上述安全组资源块中动态获取安全组 ID

resource "aws_vpc_endpoint" "endpoint_vpc" {
vpc_id            = aws_vpc.main.id
service_name      = "com.amazonaws.us-west-2.ec2"
vpc_endpoint_type = "Interface"

security_group_ids = [
aws_security_group.sg1.id,
]

private_dns_enabled = true
}

您始终可以在 output.tf 文件中获取结果,如下所述

output "security_groups_id's" {
value = aws_security_groups.sg1.ids
}

【讨论】:

    【解决方案2】:

    有没有一种方法可以使用 terraform 将 VPC 的所有安全组 ID 放入一个列表中?

    可以,可以使用aws_security_groups数据源:

    data "aws_security_groups" "test" {
      filter {
        name   = "vpc-id"
        values = ["your-vpc-id"]
      }
    }
    
    output "test" {
      value = data.aws_security_groups.test.ids
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-10
      • 2019-02-05
      • 2020-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      • 2023-03-29
      相关资源
      最近更新 更多