我正在努力了解Terraform(v0.12.12)中数据进出模块的方式。我有一个非常简单的示例,但是无法理解数据应该如何在模块之间传递。我可以找到的大多数示例都是不完整的或过时的。
我创建了一个带有两个模块的简单示例。创建vpc和子网的网络模块,以及创建EC2实例的计算模块。我只是想为计算模块提供EC2实例应该进入的子网的ID。但我不明白:
基本结构如下
.
├── main.tf
└── modules
├── compute
│ └── main.tf
└── network
├── main.tf
└── output.tf
# main.tf
provider "aws" {
region = "eu-west-1"
}
module "m_network" {
source = "./modules/network"
}
# The problem is how to make that subnet id available to the compute module
# so the ec2 instance can be added to it?
module "m_compute" {
source = "./modules/compute"
# I wondered if the m_compute module should pass in a parameter, but
# Any attempt to pass a parameter gives an error: An argument "subnet_id" is not expected here.
#xxx = "xxx" # This fails to.
# subnet_id = module.m_network.subnet_id
}
resource "aws_vpc" "myvpc" {
cidr_block = "10.0.0.0/16"
}
# Create subnets in each availability zone to launch our instances into, each with address blocks within the VPC:
resource "aws_subnet" "myvpc_subnet" {
vpc_id = "${aws_vpc.myvpc.id}"
cidr_block = "10.0.1.0/24"
}
# Generates subnet attributes that can be passed to other modules
output "myvpc_subnet_id" {
description = "Subnet ID"
value = "${aws_subnet.myvpc_subnet.id}"
}
resource "aws_instance" "app" {
ami = "ami-13be557e"
instance_type = "t2.micro"
subnet_id = aws_subnet.myvpc_subnet_id # What should go here?
}
您需要将变量文件添加到compute
模块,以便它可以从subnet_id
模块接收network
。
检查variables.tf
文件的内容和main.tf
模块的compute
查看如何访问输入变量。
示例结构如下。
.
├── main.tf
└── modules
├── compute
│ ├── main.tf
│ └── variables.tf
└── network
├── main.tf
└── output.tf
然后在每个文件中,您可以执行以下操作。
# main.tf
provider "aws" {
region = "eu-west-1"
}
# Call network module and receive output
module "m_network" {
source = "./modules/network"
}
module "m_compute" {
source = "./modules/compute"
# pass the output of the network module
# as input variables for the compute module
subnet_id = module.m_network.subnet_id
}
# compute module | variables.tf
# declare a input variable for the compute module
variable "subnet_id" {
description = "The subnet ID from the network module"
# You can also enforce the type with
# type = string OR number OR etc.
}
# compute module | main.tf
resource "aws_instance" "app" {
ami = "ami-13be557e"
instance_type = "t2.micro"
# you can use variables with var.{name}
# access the subnet id variable
subnet_id = var.subnet_id
}
# network module | main.tf
resource "aws_vpc" "myvpc" {
cidr_block = "10.0.0.0/16"
}
resource "aws_subnet" "myvpc_subnet" {
vpc_id = "${aws_vpc.myvpc.id}"
cidr_block = "10.0.1.0/24"
}
# network module | output.tf
output "myvpc_subnet_id" {
description = "Subnet ID"
value = "${aws_subnet.myvpc_subnet.id}"
}