Terraform-从值列表创建对象列表

时间:2019-11-04 18:14:18

标签: azure terraform terraform-provider-azure

我在Terraform v 0.11.8上遇到了一个奇怪的问题。我们正在尝试关闭ACR的端口,使其仅在网络中可用,并且还允许应用程序服务访问它。

terraform IP_restriction规则文档显示了类似的内容。

network_rule_set {
    default_action = "Deny"
    **ip_rule = [{
      action = "Allow"
      ip_range = "x.x.x.x"
    },
    {
      action = "Allow"
      ip_range = "y.y.y.y"
    }...]**
  }

我在变量/本地中有IP列表

variable "myIps" {
   type="list"
   default="[x.x.x.x, y.y.y.y, z.z.z.z, ....]"
}

如何将元素[x.x.x.x]的列表转换为具有以下内容的对象列表 [{action =“ Allow” ip_range =“ x.x.x.x”}]。第一个属性action =“ Allow”始终是静态的。我必须将IP从变量传递到object属性。

我尝试使用正则表达式模式

variable "test2" {
  type="string"
  default = "{action=\"Allow\", ip_range=\"%s\"}"
}

但这将返回字符串,而不是对象列表。

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用for循环来迭代ip_rule条目。

这是Terraform v0.12.9在我这边的一个有效示例 + provider.azurerm v1.36.1

resource "azurerm_resource_group" "test" {
  name     = "example-test"
  location = "East US"
}


variable "ips" {
   type= "list"
   default= ["8.8.8.8", "1.1.1.1","2.2.2.2"]

}

resource "azurerm_container_registry" "acr" {
    name                =   "mytestacr123"
    resource_group_name =   "${azurerm_resource_group.test.name}"
    location            =   "${azurerm_resource_group.test.location}"
    admin_enabled       =   false
    sku                 =   "Premium"


   # georeplication_locations    =   ["East US"]

    network_rule_set        {
        default_action  =   "Deny"
        # ip_rule block
          ip_rule =  [
              for ip in var.ips: {
              action  = "Allow"
              ip_range = ip
                     }
              ] 
          }
}

结果:

enter image description here