问题描述
我想在具有大量端口组的环境中自动部署 Vmware 虚拟机.为了能够选择正确的端口组,最好输入 2 个变量租户和环境.这 2 个变量用于 CMDB 注册和部署目的.
I want to automate deployments of Vmware VM's in an landscape with lots of portgroups. To be able to select the correct portgroup it would be best to enter 2 variables tenant and environment. These 2 variables are used for CMDB registration and deployment purposes.
对于部署,需要将变量合并为 1 个新变量以选择正确的端口组.由于插值语法,似乎不可能在查找中使用 2 个组合变量.
For the deployment the variables need to be combined in to 1 new variable to pick the correct portgroup. Due to interpolation syntax it seems to be impossible to use 2 combined variables in the lookup.
如何在 Terraform 中将 2 个变量合并为 1?
How can I combine 2 variables to 1 in Terraform?
我也尝试使用正确的字符串制作本地文件,但该文件需要在脚本启动之前存在,terraform plan 给出了该文件不存在的错误消息.
I also tried to make a local file with the correct string, but that file needs to exist before the script starts, terraform plan gives a error message that the file doesn't exist.
variable "tenant" {
description = "tenant: T1 or T2"
}
variable "environment" {
description = "environment: PROD or TEST"
}
variable "vm_network" {
description = "network the VM will be provisioned with"
type = "map"
default = {
T1_PROD = "T1-PROD-network"
T2_PROD = "T2-PROD-network"
T1_TEST = "T1-TEST-network"
T2_TEST = "T2-TEST-network"
}
}
data "vsphere_network" "network" {
name = "${lookup(var.vm_network, tenant_environment)}"
datacenter_id = "${data.vsphere_datacenter.dc.id}"
}
推荐答案
在我的脑海里,我可以想到三种不同的方法来合并变量以用作查找键:
Off the top of my head I can think of three different ways to merge the variables to use as a lookup key:
variable "tenant" {}
variable "environment" {}
variable "vm_network" {
default = {
T1_PROD = "T1-PROD-network"
T2_PROD = "T2-PROD-network"
T1_TEST = "T1-TEST-network"
T2_TEST = "T2-TEST-network"
}
}
locals {
tenant_environment = "${var.tenant}_${var.environment}"
}
output "local_network" {
value = "${lookup(var.vm_network, local.tenant_environment)}"
}
output "format_network" {
value = "${lookup(var.vm_network, format("%s_%s", var.tenant, var.environment))}"
}
output "lookup_network" {
value = "${lookup(var.vm_network, "${var.tenant}_${var.environment}")}"
}
第一个选项使用 locals 创建一个已经插入的变量,并且可以很容易地在多个地方重用,而这些地方不能直接用 Terraform/HCL 中的变量来完成.这通常是在更高版本的 Terraform 中进行变量组合/插值的最佳方式(它们是在 Terraform 0.10.3 中引入的).
The first option uses locals to create a variable that is interpolated already and can be easily reused in multiple places which can't be done directly with variables in Terraform/HCL. This is generally the best way to do variable combination/interpolation in later versions of Terraform (they were introduced in Terraform 0.10.3).
第二个选项使用格式
函数 创建一个包含租户和环境变量的字符串.
The second option uses the format
function to create a string containing the tenant and environment variables.
最后一个看起来有点滑稽,但它是有效的 HCL.如果可能,我可能会回避使用该语法.
The last one is a little funny looking but is valid HCL. I'd probably shy away from using that syntax if possible.
这篇关于Terraform 将 2 个变量组合成一个新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!