[Terraform] How to config multiple ec2 private_ips in cidr_blocks of an aws_security_group resource
1 min readJun 26, 2020
Let’s say we need to configure cidr_blocks
of an aws_security_group
resource with the private IPs of several aws EC2 instance retrieve from data resources in Terraform.
However, cidr_blocks
only accept a standard CIDR format with /32
. We can accomplish it through formatlist syntax, adding a /32
string after each private_ips
resources.
Example configuration:
data "aws_instances" "ec2-example" {
filter {
name = "tag:Name"
values = ["ec2-example-*"]
}
}resource "aws_security_group" "example" {
vpc_id = "vpc_example"
name = "example"
description = "example"ingress {
protocol = "tcp"
from_port = 80
to_port = 80cidr_blocks = ["${formatlist("%s/32", daws_instances.ec2-example.private_ips)}"]
}egress {
protocol = "-1"
from_port = 0
to_port = 0
cidr_blocks = ["0.0.0.0/0"]
}tags {
Name = "example"
}
}