我有一个资源用于创建 ec2 实例,另一个资源用于创建 ebs(内部有附加)。
在 ebs 中,我需要为其提供在 ec2 资源中创建的 instance_id = aws_instance.ec2.id 。如何将 var 值从一种资源传递到另一种资源?
我正在使用带有 tfvars 文件的模块来消耗大约资源来使用外部磁盘创建 ec2 实例。
ec2主文件:
# NIC
resource "aws_network_interface" "nic" {
subnet_id = "${var.subnet_id}"
private_ips = "${var.ip_address}"
tags = { Name = var.tags }
}
# EC2 Instance
resource "aws_instance" "ec2" {
ami = "${var.ami}"
instance_type = "${var.instance_type}"
iam_instance_profile = "${var.iam_instance_profile}"
tags = { Name = var.tags }
key_name = "${var.key_name}"
network_interface {
network_interface_id = "${aws_network_interface.nic.id}"
device_index = 0
}
}
外盘主文件:
resource "aws_ebs_volume" "external_disk" {
availability_zone = "${var.availability_zone}"
size = "${var.disk_size}"
type = "${var.disk_type}"
tags = { Name = var.tags }
}
resource "aws_volume_attachment" "disk_attach" {
device_name = "${var.device_name}"
volume_id = aws_ebs_volume.external_disk.id
instance_id = aws_instance.ec2.id
}
主要环境模块:
module "external_disk_red" {
source = "../source-modules/external-disk"
availability_zone = "${var.availability_zone}"
size = "${var.disk_size_red}"
type = "${var.disk_type_red}"
}
module "red" {
source = "../source-modules/ec2"
region = "${var.region}"
access_key = "${var.access_key}"
secret_key = "${var.secret_key}"
ami = "${var.ami}"
instance_type = "${var.instance_type}"
iam_instance_profile = "${var.iam_instance_profile}"
tags = "${var.tags_red}"
key_name = "${var.key_name}"
ip_address = "${var.ip_address_red}"
subnet_id = "${var.subnet_id}"
device_name = "${var.volume_path_red}"
}
在这种情况下,您需要做的是将输出添加到您的 ec2 模块,并将其用作外部磁盘模块中的输入(变量)。
另外,我不知道您使用的是哪个版本的 Terraform,但是使用双引号来引用变量被认为是遗留的(除非您想进行插值)。
所以...
源模块/ec2/output.tf
output "instance_id" {
value = aws_instance.ec2.id
description = "ID of the EC2 instance"
}
源模块/外部磁盘/变量.tf
variable "instance_id" {
type = string
description = "ID of the EC2 instance"
}
源模块/外部磁盘/main.tf
resource "aws_ebs_volume" "external_disk" {
availability_zone = var.availability_zone
size = var.disk_size
type = var.disk_type
tags = { Name = var.tags }
}
resource "aws_volume_attachment" "disk_attach" {
device_name = var.device_name
volume_id = aws_ebs_volume.external_disk.id
instance_id = var.instance_id
}
主环境模块
module "external_disk_red" {
source = "../source-modules/external-disk"
availability_zone = var.availability_zone
size = var.disk_size_red
type = var.disk_type_red
instance_id = module.red.instance_id
}
module "red" {
source = "../source-modules/ec2"
region = var.region
access_key = var.access_key
secret_key = var.secret_key
ami = var.ami
instance_type = var.instance_type
iam_instance_profile = var.iam_instance_profile
tags = var.tags_red
key_name = var.key_name
ip_address = var.ip_address_red
subnet_id = var.subnet_id
device_name = var.volume_path_red
}