Terraform 0.11 get VPC CIDRs from data source and pass to security_group_ingress_rule resource

Viewed 117

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?

0 Answers
Related