Adithya Rathakrishnan
Adithya Rathakrishnan

Reputation: 11

how to enable dynamic block conditionally for creating GCS buckets

Im trying to add retention policy but I want to enable it conditionally, as you can see from the code

buckets.tf

locals {
  team_buckets = {
    arc   = { app_id = "20390", num_buckets = 2,  retention_period = null }
    ana = { app_id = "25402", num_buckets = 2, retention_period = 631139040 }
    cha    = { app_id = "20391", num_buckets = 2,  retention_period = 631139040 } #20 year
  }
}


module "team_bucket" {
  source = "../../../../modules/gcs_bucket"

  for_each = {
    for bucket in flatten([
      for product_name, bucket_info in local.team_buckets : [
        for i in range(bucket_info.num_buckets) : {
          name             = format("%s-%02d", product_name, i + 1)
          team             = "ei_${product_name}"
          app_id           = bucket_info.app_id
          retention_period = bucket_info.retention_period
        }
      ]
    ]) : bucket.name => bucket
  }

  project_id       = var.project
  name             = "teambucket-${each.value.name}"
  app_id           = each.value.app_id
  team             = each.value.team
  retention_period = each.value.retention_period

}

root module is defined as follows main.tf

resource "google_storage_bucket" "bucket" {
  project  = var.project_id
  name     = "${var.project_id}-${var.name}"
  location = var.location

  labels = {
    app_id      = var.app_id
    ei_team     = var.team
    cost_center = var.cost_center
  }

  uniform_bucket_level_access = var.uniform_bucket_level_access

  dynamic "retention_policy" {
    for_each = var.retention_policy == null ? [] : [var.retention_period]
    content {
      retention_period = var.retention_period
    }
  }
}

but I can't seem to make the code pick up the value,

for example as you see below the value doesn't get implemented

  ~ resource "google_storage_bucket" "bucket" {
        id                          = "teambucket-cha-02"
        name                        = "teambucket-cha-02"
        # (11 unchanged attributes hidden)

      - retention_policy {
          - is_locked        = false -> null
          - retention_period = 3155760000 -> null
        }
    }

variables.tf for retention policy is as follows

variable "retention_policy" {
  description = "Configuation of the bucket's data retention policy for how long objects in the bucket should be retained"
  type = any
  default = null
}

variable "retention_period" {
  default = null
}

Upvotes: 0

Views: 149

Answers (1)

Marcin
Marcin

Reputation: 238269

Your var.retention_policy is always null, as its default value. You are not changing the default value at all. Probably you wanted the following:

 for_each = var.retention_period == null ? [] : [var.retention_period]

instead of

for_each = var.retention_policy == null ? [] : [var.retention_period]

Upvotes: 1

Related Questions