Setanta
Setanta

Reputation: 996

Terraform - conditionally creating a resource within a loop

Is it possible to combine resource creation with a loop (using count) and conditionally skip some resources based on the value of a map?

I know we can do these things separately:

To illustrate lets say I have a list of maps:

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

I can iterate over the over the above list and create three resources using 'count' within the resource:

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)}"

}

However, I want to also skip creation of a resource where createStorage = false. So in the above example I want to create two storage accounts but the 'elastic' storage account is skipped. Is this possible?

Upvotes: 5

Views: 4817

Answers (1)

SomeGuyOnAComputer
SomeGuyOnAComputer

Reputation: 6208

In terraform 0.12.x you can filter out the list where createStorage=true and use that for your count expression

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
  ]
}

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
}

Upvotes: 6

Related Questions