我正在使用 terraform-aws-modules/vpc/aws 创建一个 vpc,我想单独标记 vpc 的每个子网,并在最后将其 availability_zone 连接起来。我尝试在子网标签属性中使用自我引用,但我收到错误:无效的“自我”引用,因为我正在使用该模块。
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
name = "${var.app_name}-vpc"
cidr = var.vpc_cird
azs = var.vpc_azc
private_subnets = var.vpc_private_subnets
public_subnets = var.vpc_public_subnets
create_vpc = local.create_vpc
enable_ipv6 = true
enable_dns_hostnames = true
tags = merge(
{
Name = "${var.app_name}-${terraform.workspace}"
},
local.default_tags,
var.vpc_tags,
)
private_subnet_tags = {
Name = "vpc-private-subnet-${self.availability_zone}"
}
public_subnet_tags = {
Name = "vpc-public-subnet-${self.availability_zone}"
}
}
有没有办法在创建后引用 vpc 的子网并更改它的标签?像这样:
for instance in module.vpc.outputs.private_subnets:
instance.tags = { Name = "vpc-private-subnet-${self.availability_zone}"}
答案 0 :(得分:0)
我的做法如下。
我尝试在代码中添加注释以提供所有步骤的说明:
## Create the VPC and the subnets
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
name = "my-vpc"
cidr = "10.0.0.0/16"
azs = ["eu-west-1a", "eu-west-1b", "euw1-az3"]
private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
public_subnets = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]
enable_ipv6 = true
enable_dns_hostnames = true
}
## Extract the subnets using the vpc id from the module
data "aws_subnet_ids" "my_vpc" {
vpc_id = module.vpc.vpc_id
}
## Extract the subnets (to get the az values)
data "aws_subnet" "subnets" {
for_each = data.aws_subnet_ids.my_vpc.ids
id = each.value
}
## Then tag your subnets automatically with the local-exec and the aws-cli (modify the region if required)
resource "null_resource" "tagging_subnets" {
for_each = data.aws_subnet.subnets
provisioner "local-exec" {
command = "aws ec2 create-tags --resources ${each.value.id} --tags Key=az,Value=${each.value.availability_zone} --region=eu-west-1"
}
}
第一次运行
terraform apply target=module.vpc
在那之后
terraform apply
这将根据需要标记子网