Terraform - 有条件地在循环中创建资源

时间:2018-01-17 12:54:38

标签: azure terraform

是否可以将资源创建与循环(使用计数)相结合,并根据地图的值有条件地跳过某些资源?

我知道我们可以分开做这些事情:

  • 使用count在循环中创建资源。
  • 使用变量/计数变通方法(代替'if'语句)来条件创建资源

为了说明我可以说我有一张地图列表:

variable "resources" {
  type = "list"
  default = [
    {
      name = "kafka"
      createStorage = true
    },
    {
      name = "elastic"
      createStorage = false
    },
    {
      name = "galera"
      createStorage = true
    }
  ]
}

我可以遍历上面的列表并使用资源中的'count'创建三个资源:

resource "azurerm_storage_account" "test" {
    name                     = "test${var.environment}${lookup(var.resources[count.index], "name")}sa"
    location                 = "${var.location}"
    resource_group_name      = "test-${var.environment}-vnet-rg"
    account_tier             = "Standard"
    account_replication_type = "GRS"
    enable_blob_encryption   = true

    count  = "${length(var.resources)}"

}

但是,我还想跳过创建createStorage = false的资源。因此,在上面的示例中,我想创建两个存储帐户,但跳过“弹性”存储帐户。 这可能吗?

1 个答案:

答案 0 :(得分:3)

在terraform 0.12.x中,您可以过滤掉createStorage=true所在的列表,并将其用于计数表达式

variable "resources" {
  type = "list"
  default = [
    {
      name          = "kafka"
      createStorage = true
    },
    {
      name          = "elastic"
      createStorage = false
    },
    {
      name          = "galera"
      createStorage = true
    }
  ]
}

locals {
  resources_to_create = [
    for resource in var.resources :
    resource
    if resource.createStorage == true
  ]
}

resource "azurerm_storage_account" "test" {
  count = length(local.resources_to_create)

  name                     = "test${var.environment}${lookup(local.resources_to_create[count.index], "name")}sa"
  location                 = var.location
  resource_group_name      = "test-${var.environment}-vnet-rg"
  account_tier             = "Standard"
  account_replication_type = "GRS"
  enable_blob_encryption   = true
}