Issue
I'm trying to source the PIV4_CIDR for a given VPC, using the aws_vpcs data-source to identify the VPC first and get the CIDR from ID - is it possible?
Just a bit of background, for some design reason, we have services in different VPC. Say, eg. I have three VPCs: xxxprod-n
, xxxprod-l
and xxxprod-h
and I want to add a SG rule for the entire subnet to allow access to a specific port. This is what I tried:
data "aws_vpcs" "prod" {
tags = {
Name = "${var.project}prd-*"
}
}
resource "aws_security_group_rule" "pa-allow" {
count = length(data.aws_vpcs.prod.ids)
type = "ingress"
from_port = 8140
to_port = 8140
protocol = "tcp"
cidr_blocks = [sort(data.aws_vpcs.prod.ids)[count.index].cidr_block]
security_group_id = aws_security_group.secg.id
description = "allow from ${sort(data.aws_vpcs.prod.ids)[count.index]}"
}
I get the error:
Error: Unsupported attribute
on ../../modules/mgt/ec2.tf line 42, in resource "aws_security_group_rule" "pa-allow": 42: cidr_blocks = [sort(data.aws_vpcs.prod.ids)[count.index].cidr_block]
This value does not have any attributes.
I tried that, based on this page: https://www.terraform.io/docs/providers/aws/d/vpc.html
, thinking aws_vpc and aws_vpcs will do similar sort of thing but it seem doesn't. Any idea how do I do that?
Solution
You can get SET
(not list) of vpcs using data.aws_vpcs. (I think the document is wrong...)
Then you can get data.aws_vpc list using data.aws_vpcs, and you can get cidr blocks of them.
data "aws_vpcs" "prod" {
tags = {
Name = "${var.project}prd-*"
}
}
data "aws_vpc" "prod" {
count = length(data.aws_vpcs.prod.ids)
id = tolist(data.aws_vpcs.prod.ids)[count.index]
}
resource "aws_security_group_rule" "pa-allow" {
count = length(data.aws_vpcs.prod.ids)
type = "ingress"
from_port = 8140
to_port = 8140
protocol = "tcp"
cidr_blocks = [data.aws_vpc.prod[count.index].cidr_block]
security_group_id = aws_security_group.secg.id
description = "allow from ${tolist(data.aws_vpcs.prod.ids)[count.index]}"
}
Answered By - RyanKim Answer Checked By - Clifford M. (WPSolving Volunteer)