[Terraform] How to config multiple ec2 private_ips in cidr_blocks of an aws_security_group resource

Kun-Hung Tsai
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 = 80
cidr_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"
}
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Kun-Hung Tsai
Kun-Hung Tsai

No responses yet