My requirement is I need to get the CIDR address for vpc-foo and vpc-bar and pass on to the resource "aws_security_group_rule" "ingress"
I tried with the below code:
- data "aws_vpcs" -> Get the ID for a given VPC
- data "aws_vpc" -> make a list with VPC ids
- resource "aws_security_group_rule" "ingress" -> pass VPC CIRDs as an ingress
variable "list_of_vps"{
type = "list"
default = ["vpc-foo", "vpc-bar"]
}
variable "sg_name" {
default = "sg-test"
}
data "aws_vpcs" "get_vpc"{
count = "$length(var.list_of_vps)"
filter {
name = "tag:Name"
values = ["vpc-${element(var.list_of_vps, count.index)}"]
}
}
data "aws_vpc" "get_vpc_ids" {
count = "${length(data.aws_vpcs.get_vpc.ids)}"
id = "${tolist(data.aws_vpcs.prod.ids)[count.index]}"
}
resource "aws_security_group_rule" "ingress" {
count = "${length(var.list_of_vps)}"
type = "ingress"
from_port = 22
to_port = 22
protocol = "TCP"
cidr_blocks = ["${element(data.aws_vpc.get_vpc_ids.*.cidr_block, count.index)}"]
security_group_id = "${var.sg_name}
}
Can someone help with this, please?
Renamed the variable list_of_vps to list_of_vpcs to be more descriptive. Removed the unnecessary data "aws_vpc" block since you can get the CIDR block directly from the aws_vpcs data source. Modified the cidr_blocks argument for the aws_security_group_rule resource to use the element function to access the CIDR block from the data.aws_vpcs.get_vpc data source.