简体   繁体   中英

Terraform: How to get the VPC CIDR from VPC id?

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?

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]}"
}

As for today, you don't need to use the list approach anymore, it is not specified in the documentation but you can do something like this:

data "aws_vpc" "main" {
  id = <your_vpc_id>
}

And then you can access it data.aws_vpc.main.cidr_block , it is not specified in the attributes referece , but it is there.

Terraform version: 1.0.11

AWS Provider version: 4.9.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM