我正在使用映射变量,以便基于较长的变量名创建局部变量,在需要缩写的地方或资源需要在其他地方使用经过清理或缩短的值的地方,都使用了变量。
例如
variable "env-short" {
description = "create a shortened version of the name of use in resource naming"
type = "map"
default = {
"Proof Of Concept" = "poc"
"User Acceptance Testing" = "uat"
"Production" = "prd"
}
}
variable "org-short" {
description = "create a shortened version of the name of use in resource naming"
type = map(string)
default = {
"My Big Company" = "MBC"
"My Little Company" = "MLC"
}
}
variable "loc-short" {
description = "create a shortened version of the name of use in resource naming"
type = map(string)
default = {
"UK South" = "UKS"
"UK West" = "UKW"
"North Europe" = "NEU"
"West Europe" = "WEU"
}
}
并将相应的变量用于其全长映射等价物。
现在我可以像这样在资源块中按原样使用
Name = “${lower(“${var.loc-short[$var.location]}”)-${lower(“${var.org-short[$var.organisation]}”)-${lower(“${var.env-short[$var.environment]}”)-myresource”
但是,像所有优秀的编码人员一样,我喜欢通过声明局部变量以保持整洁和可读性。
locals {
org-short = "${lower("${var.org-short["${var.organisation}"]}")}"
loc-short = "${lower("${var.loc-short["${var.location}"]}")}"
env-short = "${lower("${var.env-short["${var.environment}"]}")}"
# I also create additional for commonly used configurations of them
name-prefix = "${lower("${var.org-short["${var.organisation}"]}")}-${lower("${var.loc-short["${var.location}"]}")}"
name-prefix-storage = "${lower("${var.org-short["${var.organisation}"]}")}${lower("${var.loc-short["${var.location}"]}")}"
}
这真的很好用,并且使内容整洁和可读。
resource "provisioner_example" "test" {
location = var.location
name = “${local.loc-short}-${local.env-short}-my resource”
但是,当我开始使用count功能创建多个资源时,我希望能够使用这种格式。
resource "provisioner_example" "test" {
count = length(var.location)
location = var.location[count.index]
name = “${local.loc-short[count.index]}-${local.env-short}-my resource”
然后,Terraform抱怨该索引在本地查询中无效,而varlocation是具有2个元素的元组,| var.loc-short是具有4个元素的字符串映射。给定的键不能标识此集合值中的元素:必需的字符串。
现在我知道我可以通过摆脱locals变量并直接包括变量计算来解决此问题
name =”${lower("${var.loc-short["${var.locations[count.index]}"]}")}-${local.env-short}-my resource"
但是对我来说,这会使代码显得更凌乱,结构也更少。 关于如何将计数索引值传递给地图查找的任何想法?