Terraform:将变量从一个模块传递到另一个模块

pka*_*mol 4 amazon-web-services terraform terraform-provider-aws

我正在为 AWS VPC 创建创建一个 Terraform 模块。

这是我的目录结构

?  tree -L 3
.
??? main.tf
??? modules
?   ??? subnets
?   ?   ??? main.tf
?   ?   ??? outputs.tf
?   ?   ??? variables.tf
?   ??? vpc
?       ??? main.tf
?       ??? outputs.tf
?       ??? variables.tf
??? variables.tf

3 directories, 12 files
Run Code Online (Sandbox Code Playgroud)

在子网模块中,我想获取 vpc(子)模块的 vpc id。

modules/vpc/outputs.tf我使用:

output "my_vpc_id" {
  value = "${aws_vpc.my_vpc.id}"
}
Run Code Online (Sandbox Code Playgroud)

这对我做以下事情就足够了modules/subnets/main.tf吗?

resource "aws_subnet" "env_vpc_sn" {
   ...
   vpc_id                  = "${aws_vpc.my_vpc.id}"
}
Run Code Online (Sandbox Code Playgroud)

yda*_*coR 8

main.tf(或您使用子网模块的任何地方)需要从 VPC 模块的输出中传递它,并且您的子网模块需要采用一个必需变量。

要访问模块的输出,您需要将其引用为module.<MODULE NAME>.<OUTPUT NAME>

在父模块中,子模块的输出在表达式中作为模块可用...例如,如果名为 web_server 的子模块声明了名为 instance_ip_addr 的输出,您可以访问该值作为 module.web_server.instance_ip_addr。

所以你main.tf会看起来像这样:

module "vpc" {
  # ...
}

module "subnets" {
  vpc_id = "${module.vpc.my_vpc_id}"
  # ...
}
Run Code Online (Sandbox Code Playgroud)

并且subnets/variables.tf是这样的:

variable "vpc_id" {}
Run Code Online (Sandbox Code Playgroud)