变量.tf
variable "env_name" {
default = "some_client"
}
variable "azure_instance_names" {
default = [
"AD01",
"AD01",
]
}
我',试图为azure_instance_names
变量中指定的尽可能多的实例创建公共IP(在本例中为2),我在命名此资源时遇到问题,我想通过连接env_name
和azure_instance_names
变量来创建名称。它必须是一个单词,由-
分隔,所以名称应该在env_name-azure_instance_names中,例如:
所需输出
name=some_client-AD01
some_client-AD02
实际输出:
name=some_client AD01
some_client AD02
主.tf
resource "azurerm_public_ip" "datasourceip" {
count = "${length(var.azure_instance_names)}"
name = "${join("-", list(format("%s %s", var.env_name, element(var.azure_instance_names, count.index))))}"
location = "${azurerm_resource_group.res_group.location}"
resource_group_name = "${azurerm_resource_group.res_group.name}"
allocation_method = "Static"
}
在地形应用中,我得到了:
+ azurerm_public_ip.datasourceip[1]
id: <computed>
allocation_method: "Static"
fqdn: <computed>
idle_timeout_in_minutes: "4"
ip_address: <computed>
ip_version: "IPv4"
location: "westeurope"
name: "some_client AD01"
resource_group_name: "myrg1"
sku: "Basic"
tags.%: <computed>
由于Azure不接受多个单词i'中的资源名称,因此尝试将"-"联接到var.env_name, var.azure_instance_names
,因此资源名称应为some_client-AD01
虽然我指定了联接函数i',但仍然得到相同的错误:
azurerm_public_ip.datasourceip.1:创建/更新公用ip"some_client AD01"(资源组"myrg1")时出错:网络。PublicIPAddressesClient#CreateOrUpdate:发送请求失败:StatusCode=400--原始错误:Code="InvalidResourceName"Message="资源名称some_client LBA-PEU2B-AD01无效。名称最多可以有80个字符。它必须以单词字符开头,也必须以单词或''结尾。名称可以包含单词字符或'.'、'-'、''。"详细信息=[]
只需始终使用插值:
name = "${var.env_name}-${var.azure_instance_names[count.index]}"
我还发现${var.foo[i]}
比${element(var.foo, i)}
更容易阅读。
愚蠢的我!!,解决方案很简单:
我只需要以这种方式连接var.env_name
和${format("%s",element(var.azure_instance_names, count.index))
,而不是将两个变量都放入联接函数中:
name = "${var.env_name}-${format("%s",element(var.azure_instance_names, count.index))}"
azurerm_public_ip.datasourceip[1]: Creating...
allocation_method: "" => "Static"
fqdn: "" => "<computed>"
idle_timeout_in_minutes: "" => "4"
ip_address: "" => "<computed>"
ip_version: "" => "IPv4"
location: "" => "westeurope"
name: "" => "some_client-AD01"
resource_group_name: "" => "myrg1"
sku: "" => "Basic"
tags.%: "" => "<computed>"
azurerm_public_ip.datasourceip[0]: Creating...
allocation_method: "" => "Static"
fqdn: "" => "<computed>"
idle_timeout_in_minutes: "" => "4"
ip_address: "" => "<computed>"
ip_version: "" => "IPv4"
location: "" => "westeurope"
name: "" => "some_client-AD02"
resource_group_name: "" => "myrg1"
sku: "" => "Basic"
tags.%: "" => "<computed>"
azurerm_public_ip.datasourceip[1]: Creation complete after 5s (ID: /subscriptions/2a325f88-e3dd-48c2-bf85-...PAddresses/some_client-AD01)
azurerm_public_ip.datasourceip[0]: Creation complete after 5s (ID: /subscriptions/2a325f88-e3dd-48c2-bf85-...PAddresses/some_client-AD02)
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.