Search code examples
terraformgoogle-cloud-rungoogle-secret-manager

Creating a dynamic secret variable block within Terraform for Cloud Run


I'm trying to create the following block dynamically based on a list of strings

        env {
          name = "SECRET_ENV_VAR"
      value_from {
            secret_key_ref {
              name = google_secret_manager_secret.secret.secret_id
              key = "1"
            }
          }
        }

Based off documentation: https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/cloud_run_service#example-usage---cloud-run-service-secret-environment-variables

I would like to dynamically add Secrets, and have defined the following dynamic block:

        dynamic "env" {
          for_each = toset(var.secrets)
          content {
            name = each.value
            value_from {
              secret_key_ref {
                name = each.value
                key  = "1"
              }
            }
          }
        }

Where secrets is a variable of type list(string)

However, this throws an error: Blocks of type "value_from" are not expected here.

I'm not sure what I'm missing, or where I have incorrectly specified the value_from block.

Could someone point me in the right direction for fixing this up?

UPDATE; I have also tried to implement this variable as a map, as per the suggestion in the comments on this post. (https://www.terraform.io/docs/language/expressions/dynamic-blocks.html#multi-level-nested-block-structures)

        dynamic "env" {
          for_each = var.secrets
          content {
            name = each.key
            dynamic "value_from" {
              for_each = env.value.name
              secret_key_ref {
                name = value_from.value.name
                key  = value_from.value.version
              }
            }
          }
        }

However, this also gives the same error. Blocks of type "value_from" are not expected here.

In this example, the secrets variable is defined as a list(any) with this value:

secrets = [
    {
      name    = "SECRET"
      version = "1"
    }
  ]

Solution

  • In the end, I solved this by changing the variable type to a map(any):

    secrets = {
        "SECRET" = "1"
    }
    

    This allowed me to create the "dynamic" env block, without needing to implement the nested dynamic block.