首页 > 解决方案 > 将公共 IP 输出与服务器名称连接起来

问题描述

我编写了一个 Terraform 脚本来创建一些 Azure 虚拟机。

创建的虚拟机数量基于type我的.tfvars文件中调用的变量:

type = [ "Master-1", "Master-2", "Master-3", "Slave-1", "Slave-2", "Slave-3" ]

我的variables.tf文件包含以下内容local

count_of_types = "${length(var.type)}"

我的resources.tf文件包含根据这些信息实际创建相关数量的虚拟机所需的代码:

resource "azurerm_virtual_machine" "vm" {
  count                 = "${local.count_of_types}"
  name                  = "${replace(local.prefix_specific,"##TYPE##",var.type[count.index])}-VM"
  location              = "${azurerm_resource_group.main.location}"
  resource_group_name   = "${azurerm_resource_group.main.name}"
  network_interface_ids = ["${azurerm_network_interface.main.*.id[count.index]}"]
  vm_size               = "Standard_B2ms"
  tags                  = "${local.tags}"

最后,在我的output.tf文件中,我输出了每台服务器的 IP 地址:

output "public_ip_address" {
  value = ["${azurerm_public_ip.main.*.ip_address}"]
}

我正在创建一个具有 1x Master 和 1x Slave VM 的 Kubernetes 集群。为此,脚本工作正常 - 第一个 IP 输出是主站,第二个 IP 输出是从站。

但是,当我总共迁移到 8 个以上的 VM 时,我想知道哪个 IP 指的是哪个 VM。

有没有办法修改我的输出以包含type本地或仅包含公共 IP旁边的服务器主机名?

例如54.10.31.100 // Master-1

标签: terraform

解决方案


看看 formatlist(它是字符串操作的函数之一),可用于迭代实例属性和列表标签以及其他感兴趣的属性。

output "ip-address-hostname" {
  value = "${
      formatlist(
        "%s:%s",
        azurerm_public_ip.resource_name.*.fqdn,
        azurerm_public_ip.resource_name.*.ip_address
      )
    }"
}

请注意,这只是一个伪代码草案。您可能需要对此进行调整并在 TF 文件中创建额外的数据源以获得有效的枚举

更多阅读可用 - https://www.terraform.io/docs/configuration/functions/formatlist.html


推荐阅读