Terraform 嵌套模块调用和输出
Terraform Nested Module Calling and Outputs
我正在处理基础设施供应,所以我将模块称为嵌套。
这是我的文件系统树。
├── main.tf
└── modules
├── client.tf
└── in
└── main.tf
我的文件显示如下。
#main.tf
module "my_vpc" {
source = "./modules"
}
# modules/client.tf
provider "aws" {
region = "us-east-2"
}
module "inner" {
source = "./in"
}
# in/main.tf
provider "aws" {
region = "us-east-2"
}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
output "vpc_id" {
value = "${aws_vpc.main.id}"
}
所以在我的例子中,我想获得来自 in/main.tf 的资源创建模块的输出。但是当我 运行 terraform apply 命令没有输出时。
我该如何解决这个问题?
您使用了两个模块,但只有一个输出语句。
./main.tf
从 ./modules/client.tf
创建模块 my_vpc
在 client.tf
中,您从 ./modules/in/main.tf
创建模块 inner
模块 inner
具有在 ./modules/in/main.tf
中定义的单个输出 vpc_id
您还需要在 ./modules/client.tf
级别进行输出语句。您想要输出的任何模块都必须具有该变量的输出语句,即使输出链接了内部模块的输出。
# ./modules/client.tf
provider "aws" {
region = "us-east-2"
}
module "inner" {
source = "./in"
}
output "vpc_id" {
value = "${modules.inner.vpc_id}"
}
现在./modules/client.tf
中定义的模块在顶层输出你想要的值。您可以像这样在 ./main.tf
中与它互动:
#main.tf
module "my_vpc" {
source = "./modules"
}
locals {
vpc_id = "${modules.my_vpc.vpc_id}"
}
# output the vpc id if you need to
output "vpc_id" {
value = "${modules.my_vpc.vpc_id}"
}
附带说明一下,随着您扩大 Terraform 和模块的使用,保持一致会有所帮助。如果您要在另一个模块中包含一个模块,我建议使用如下一致的文件夹结构。
├── main.tf
└── modules
├── vpc
├── modules
├ └── in
├ └── main.tf
└── client.tf
└── another_module
└── main.tf
我正在处理基础设施供应,所以我将模块称为嵌套。
这是我的文件系统树。
├── main.tf
└── modules
├── client.tf
└── in
└── main.tf
我的文件显示如下。
#main.tf
module "my_vpc" {
source = "./modules"
}
# modules/client.tf
provider "aws" {
region = "us-east-2"
}
module "inner" {
source = "./in"
}
# in/main.tf
provider "aws" {
region = "us-east-2"
}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
output "vpc_id" {
value = "${aws_vpc.main.id}"
}
所以在我的例子中,我想获得来自 in/main.tf 的资源创建模块的输出。但是当我 运行 terraform apply 命令没有输出时。
我该如何解决这个问题?
您使用了两个模块,但只有一个输出语句。
./main.tf
从 ./modules/client.tf
创建模块 my_vpc
在 client.tf
中,您从 ./modules/in/main.tf
inner
模块 inner
具有在 ./modules/in/main.tf
中定义的单个输出 vpc_id
您还需要在 ./modules/client.tf
级别进行输出语句。您想要输出的任何模块都必须具有该变量的输出语句,即使输出链接了内部模块的输出。
# ./modules/client.tf
provider "aws" {
region = "us-east-2"
}
module "inner" {
source = "./in"
}
output "vpc_id" {
value = "${modules.inner.vpc_id}"
}
现在./modules/client.tf
中定义的模块在顶层输出你想要的值。您可以像这样在 ./main.tf
中与它互动:
#main.tf
module "my_vpc" {
source = "./modules"
}
locals {
vpc_id = "${modules.my_vpc.vpc_id}"
}
# output the vpc id if you need to
output "vpc_id" {
value = "${modules.my_vpc.vpc_id}"
}
附带说明一下,随着您扩大 Terraform 和模块的使用,保持一致会有所帮助。如果您要在另一个模块中包含一个模块,我建议使用如下一致的文件夹结构。
├── main.tf
└── modules
├── vpc
├── modules
├ └── in
├ └── main.tf
└── client.tf
└── another_module
└── main.tf