简体   繁体   中英

terraform for_each using terneray operation fails

I'm trying to create multiple secrets in AWS secrets manager using for_each just in prod environment:

resource "aws_kms_key" "secret_cmk" {
  deletion_window_in_days = 7
  is_enabled              = true
  enable_key_rotation     = true
  policy                  = data.aws_iam_policy_document.cmk_policy.json
}

module "airflow_conn_secret" {
  source        = "./modules/..."
  for_each      = var.env == "prd" ? local.secrets : {}
  name          = each.value.secret_id
  kms_key_id    = aws_kms_key.secret_cmk.key_id
  secret_string = jsonencode(each.value)
}

locals {
   secrets = {
     secret1 = {
        "secret_id"   = ""
        "secret_type" = ""
        "host"      = var.host
        "login"     = var.user
        "password"  = var.pwd
        "info" = {
          ...
        }
    }
    ...more secrets
   }
 }
}

But I get The true and false result expressions must have consistent types. The given expressions are object and object, respectively. The true and false result expressions must have consistent types. The given expressions are object and object, respectively. How can I fix this issue?

It seems like your goal is to declare zero instances of module.airflow_conn_secret if var.env does not equal "prd" .

A different way to achieve that result which doesn't require both conditional "arms" to have the same type is to instead construct a new mapping that has all of the elements filtered out in that case:

  for_each = {
    for k, v in local.secrets : k => v
    if var.env == "prd"
  }

Because the if clause doesn't refer to either k or v , this particular filter will either keep all or discard all of the elements of local.secrets , getting the effect you wanted.

If you had another situation where you only wanted to keep a subset of the elements then you could write an if clause that uses either k or v to make a decision based on each specific element, but that isn't needed for your use-case here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM