terraform - 引用 Terraform 中的其他模块资源
问题描述
我的 Terraform Cloud git 项目中有这样的层次结构:
├── aws
│ ├── flavors
│ │ └── main.tf
│ ├── main.tf
│ ├── security-rules
│ │ └── sec-rule1
│ │ └── main.tf
│ └── vms
│ │ └── vm1
│ │ └── main.tf
└── main.tf
所有主main.tf
文件都包含带有子文件夹的模块定义:
/main.tf
:
terraform {
required_version = "~> 0.12.0"
backend "remote" {
hostname = "app.terraform.io"
organization = "foo"
workspaces {
name = "bar"
}
}
required_providers {
openstack = "~> 1.24.0"
}
}
module "aws" {
source = "./aws"
}
/aws/main.tf
:
module "security-rules" {
source = "./security-rules"
}
module "flavors" {
source = "./flavors"
}
module "vms" {
source = "./vms"
}
/aws/security-rules/main-tf
:
module "sec-rule1" {
source = "./sec-rule1"
}
/aws/vms/main-tf
:
module "vm1" {
source = "./vm1"
}
然后我定义了这个安全规则。
/aws/security-rules/sec-rule1/main-tf
:
resource "openstack_compute_secgroup_v2" "sec-rule1" {
name = "sec-rule1"
description = "Allow web port"
rule {
from_port = 80
to_port = 80
ip_protocol = "tcp"
cidr = "0.0.0.0/0"
}
lifecycle {
prevent_destroy = false
}
}
而且我想从一个或多个 VM 中引用它,但我不知道如何通过资源 ID(或名称)进行引用。我使用简单的名称而不是参考。
/aws/vms/vm1/main-tf
:
resource "openstack_blockstorage_volume_v3" "vm1_volume" {
name = "vm1_volume"
size = 30
image_id = "foo-bar"
}
resource "openstack_compute_instance_v2" "vm1_instance" {
name = "vm1_instance"
flavor_name = "foo-bar"
key_pair = "foo-bar keypair"
image_name = "Ubuntu Server 18.04 LTS Bionic"
block_device {
uuid = "${openstack_blockstorage_volume_v3.vm1_volume.id}"
source_type = "volume"
destination_type = "volume"
boot_index = 0
delete_on_termination = false
}
network {
name = "SEG-tenant-net"
}
security_groups = ["default", "sec-rule1"]
config_drive = true
}
resource "openstack_networking_floatingip_v2" "vm1_fip" {
pool = "foo-bar"
}
resource "openstack_compute_floatingip_associate_v2" "vm1_fip" {
floating_ip = "${openstack_networking_floatingip_v2.vm1_fip.address}"
instance_id = "${openstack_compute_instance_v2.vm1_instance.id}"
}
我想使用通过 name 或 ID 引用的安全规则(和更多东西),因为它会更加一致。此外,当我创建一个新的安全规则并同时创建一个 VM 时,Terraform OpenStack 提供者计划它没有错误,但是在应用它时,会产生错误,因为 VM 是先创建的,它没有发现尚未创建新的安全规则。
我怎样才能做到这一点?
解决方案
您应该输出sec_rule_allow_web_name
forsec-rule1
和security-rules
模块,然后将模块的输出设置为和模块security-rules
的输入。这样,您可以保持模块的依赖关系,其输出称为Dependency Inversion。vm1
vms
vm1
security-rules
如果在正确的模块中定义了输出和输入,aws/main.tf
则变为
module "security-rules" {
source = "./security-rules"
}
module "flavors" {
source = "./flavors"
}
module "vms" {
source = "./vms"
security_rule_name = module.security-rules.sec_rule_allow_web_name
}
推荐阅读
- nuxt.js - 内容 API:如何呈现入口超链接
- javascript - 如何使用appium将照片等文件上传到ios应用程序
- php - 如何在Where子句php mysql查询中使用字符串变量
- flutter - 如何在 Flutter 中遍历 Map 并更新现有模型中的属性
- oracle - DELETE ANY TABLE TO TEST_USER_ROLE(除了一张表?)
- php - 谷歌分析通过获取参数获取一个 URL 加上相同 URL 的总浏览量
- ios - 如何在 swiftUI 中构建这样的网格列表?
- javascript - 侧边栏仅在屏幕尺寸 > 992 像素及以上时修复,但仍无法正常工作
- c# - 带有默认值的较短参数列表
- html - 如何将 appsettings.json 文件中的值用作 AMP html 中的 href 变量?