Search code examples
terraformterraform0.12+

Dynamic block of lifecycle_rule not working in terraform 1.0.6


The following block within a google_cloud_storage resource

  dynamic "lifecycle_rule" {
    for_each = var.bucket_lifecycle_rule
    content {
      condition {
        age        = lifecycle_rule.age
        with_state = lifecycle_rule.with_state
      }
      action {
        type          = lifecycle_rule.type
        storage_class = lifecycle_rule.storage_class
      }
    }
  }

with the following variable declaration


variable "bucket_lifecycle_rule" {
  description = "Lifecycle rules"
  type = list(object({
    age           = string
    with_state    = string
    type          = string
    storage_class = string
  }))
  default = [
    {
      age           = 30
      with_state    = "ANY"
      type          = "SetStorageClass"
      storage_class = "COLDLINE"
    },
    {
      age           = 120
      with_state    = "ANY"
      type          = "Delete"
      storage_class = ""
    },
  ]
}

errors out as follows:

│ Error: Unsupported attribute
│
│   on main.tf line 18, in resource "google_storage_bucket" "my_bucket":
│   18:         age        = lifecycle_rule.age
│
│ This object does not have an attribute named "age".
╵
╷
│ Error: Unsupported attribute
│
│   on main.tf line 19, in resource "google_storage_bucket" "my_bucket":
│   19:         with_state = lifecycle_rule.with_state
│
│ This object does not have an attribute named "with_state".
╵
╷
│ Error: Unsupported attribute
│
│   on main.tf line 22, in resource "google_storage_bucket" "my_bucket":
│   22:         type          = lifecycle_rule.type
│
│ This object does not have an attribute named "type".
╵
╷
│ Error: Unsupported attribute
│
│   on main.tf line 23, in resource "google_storage_bucket" "my_bucket":
│   23:         storage_class = lifecycle_rule.storage_class
│
│ This object does not have an attribute named "storage_class".

why is that?


Solution

  • You have to reference the properties from your objects with value:

      dynamic "lifecycle_rule" {
        for_each = var.bucket_lifecycle_rule
        content {
          condition {
            age        = lifecycle_rule.value.age
            with_state = lifecycle_rule.value.with_state
          }
          action {
            type          = lifecycle_rule.value.type
            storage_class = lifecycle_rule.value.storage_class
          }
        }
      }
    

    In the Terraform docs there is a note about this:

    The iterator object has two attributes:

    • key is the map key or list element index for the current element. If the for_each expression produces a set value then key is identical to value and should not be used.
    • value is the value of the current element.