我正在使用AWS VPC Terraform module来创建一个VPC。此外,我想使用aws_internet_gateway resource创建并连接到此VPC的Internet网关。
这是我的代码:
module "vpc" "vpc_default" {
source = "terraform-aws-modules/vpc/aws"
name = "${var.env_name}-vpc-default"
cidr = "10.0.0.0/16"
enable_dns_hostnames = true
}
resource "aws_internet_gateway" "vpc_default_igw" {
vpc_id = "${vpc.vpc_default.id}"
tags {
Name = "${var.env_name}-vpc-igw-vpcDefault"
}
}
当我运行terraform init
时,我收到以下错误:
初始化模块... - module.vpc
错误:资源'aws_internet_gateway.vpc_default_igw'配置:变量vpc.vpc_default.id中引用的未知资源'vpc.vpc_default'
如何引用Terraform模块创建的资源?
由于您使用的是模块,因此需要稍微更改引用的格式。 Module Outputs使用${module.<module name>.<output name>}
形式。同样重要的是要注意,您只能参考模块输出的值。
在你的具体情况下,这将成为基于${module.vpc.vpc_id}
的VPC Module's Outputs。
请注意,您可以在单个文件中包含多个模块实例:
module "vpc1" "vpc_default" {}
module "vpc2" "vpc_default" {}
module "vpc3" "vpc_default" {}
module "vpc4" "vpc_default" {}
${module.vpc1.vpc_id}
${module.vpc2.vpc_id}
${module.vpc3.vpc_id}
${module.vpc4.vpc_id}