【发布时间】:2021-03-19 03:08:13
【问题描述】:
我很难理解 Terraform (v0.12.12) 中数据传入和传出模块的方式。我有一个我认为非常简单的例子,但无法理解数据应该如何在模块之间传递。我能找到的大多数例子要么不完整,要么已经过时。
我创建了一个包含两个模块的简单示例。一个创建 vpc 和子网的网络模块,以及一个创建 EC2 实例的计算模块。我只是想为计算模块提供 EC2 实例应该去的子网的 ID。但我不明白:
- 如何从创建的网络模块中获取子网 ID 子网给其他模块能用吗?
- 如何让计算模块使用子网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?
}
【问题讨论】:
-
您的
./modules/compute模块中有variable "subnet_id"块吗? (有关此类块内容的更多详细信息,请参阅Declaring an Input Variable。)