我正在尝试使用AWS上的Hashicorp Terraform为新项目设置一些IaC . 我正在使用模块,因为我希望能够在多个环境(staging,prod,dev等)中重用东西 .
I'm struggling to understand where I have to set an output variable within a module, and how I then use that in another module. Any pointers to this would be greatly appreciated!
在创建EC2机器时,我需要使用在我的VPC模块中创建的一些东西(子网ID) . 我的理解是你不能从另一个模块中引用某些东西,所以我试图使用VPC模块中的输出变量 .
我的网站main.tf中有以下内容
module "myapp-vpc" {
source = "dev/vpc"
aws_region = "${var.aws_region}"
}
module "myapp-ec2" {
source = "dev/ec2"
aws_region = "${var.aws_region}"
subnet_id = "${module.vpc.subnetid"}
}
dev/vpc
只需设置一些值并使用我的vpc模块:
module "vpc" {
source = "../../modules/vpc"
aws_region = "${var.aws_region}"
vpc-cidr = "10.1.0.0/16"
public-subnet-cidr = "10.1.1.0/24"
private-subnet-cidr = "10.1.2.0/24"
}
在我的vpc main.tf中,在 aws_vpc
和 aws_subnet
资源(显示子网资源)之后,我在最后有以下内容:
resource "aws_subnet" "public" {
vpc_id = "${aws_vpc.main.id}"
map_public_ip_on_launch = true
availability_zone = "${var.aws_region}a"
cidr_block = "${var.public-subnet-cidr}"
}
output "subnetid {
value = "${aws_subnet.public.id}"
}
当我运行 terraform plan
时,我收到以下错误消息:
Error: module 'vpc': "subnetid" is not a valid output for module "vpc"
1 回答
每次都需要明确地向上传递每个模块的输出 .
例如,如果你想从嵌套在另一个模块下面的模块向屏幕输出一个变量,你需要这样的东西:
child-module.tf
parent-module.tf
main.tf