Terraform结合了查找和splat语法

时间:2018-04-23 18:21:37

标签: terraform

我正在尝试使用Terraform配置多个Azure虚拟机,然后获取授权的MSI身份ID。我开始使用这个适用于我的MSI示例(https://www.terraform.io/docs/providers/azurerm/authenticating_via_msi.html),并尝试添加计数,即。

resource "azurerm_virtual_machine" "virtual_machine" {
  count = "5"
  name                  = "test"
  ....

  identity = {
    type = "SystemAssigned"
  }

  .....
}

resource "azurerm_virtual_machine_extension" "virtual_machine_extension" {
  count = "5"
  name                 = "test"
  location             = "${var.location}"
  resource_group_name  = "test"
  virtual_machine_name = "${element(azurerm_virtual_machine.virtual_machine.*.name, count.index)}"
  publisher            = "Microsoft.ManagedIdentity"
  type                 = "ManagedIdentityExtensionForWindows"
  type_handler_version = "1.0"

  settings = <<SETTINGS
    {
        "port": 50342
    }
SETTINGS
}


output "vm_principals" {
  # original had --- "${lookup(azurerm_virtual_machine.virtual_machine.identity[0], "principal_id"}"
  value = ["${azurerm_virtual_machine.virtual_machine.*.identity[0]}"]
}

问题是我得到一个输出数组如下:

vm_principals = [
  { 
     principal_id = xxxxxxxxxxxxx, 
     type = SystemAssigned
  }, 
  { 
     principal_id = yyyyyyyyyyyyy,
     type = SystemAssigned
  }
]

我想要的是

vm_principals = [
  xxxxxxxxxxxxxxxxx,
  yyyyyyyyyyyyyyyyy
]

我尝试了明显的变化,但我怀疑这是一个Terraform限制。

  value = ["${lookup(azurerm_virtual_machine.virtual_machine.*.identity[0], "principal_id)}"]

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

不幸的是,你是对的。我相信您在打this issue。但是,这可能会在Terraform v0.12中解决,因为它将引入一种经过改进的语言(HCL)。有关更多详细信息,请参见此Hashicorp blog article

答案 1 :(得分:0)

这是我处理此问题的方式

resource "azurerm_virtual_machine" "kubenode" {
  count = "3"
  ...
}

对于名为kubenode的azurerm_virtual_machine资源,您可以执行以下操作:

${azurerm_virtual_machine.kubenode.*.identity.0.principal_id}

这将返回主体ID的列表。然后,您可以这样做:

${azurerm_virtual_machine.kubenode.*.identity.0.principal_id[count.index]}

例如在角色分配方案中:

resource "azurerm_role_assignment" "kubenode-subscription-reader-role" {
  count                = "${azurerm_virtual_machine.kubenode.count}"
  scope                = "${data.azurerm_subscription.primary.id}"
  role_definition_name = "Reader"
  principal_id         = "${azurerm_virtual_machine.kubenode.*.identity.0.principal_id[count.index]}"
}