While trying to create vpc endpoint , i have to dynamically create the security groups within the vpc and then attach it to the vpc endpoints in the same terraform plan . Is there a way I can put all the security group ids of a VPC in a list using terraform?
Asked
Active
Viewed 1,731 times
-3
-
How did it go? Still unclear how to do it? – Marcin Jun 04 '21 at 00:55
2 Answers
3
Is there a way I can put all the security group ids of a VPC in a list using terraform?
Yes, you can use aws_security_groups data source:
data "aws_security_groups" "test" {
filter {
name = "vpc-id"
values = ["your-vpc-id"]
}
}
output "test" {
value = data.aws_security_groups.test.ids
}

Marcin
- 215,873
- 14
- 235
- 294
1
create the vpc as shown below
resource "aws_vpc" "main" {
id = var.vpc_id
cidr_block = "10.0.0.0/16"
}
create the security group
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"
}
}
creating vpc endpoint fetching security group ID's dynamically from the above security group resource block
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
}
you can always get the results in outputs.tf file like mentioned below
output "security_groups_id's" {
value = aws_security_groups.sg1.ids
}

Shwetha Ballari
- 19
- 2