sebastian
sebastian

Reputation: 2368

Conditional dynamic block if map key is empty string

I have a dynamic statement in which i want to optionally create an iam policy statement.

dynamic "statement" {
    for_each = var.deploy == "true" && contains(keys(var.env_vars), "enable") ? [var.env_vars.enable] : []
    content {
      actions = [
      "lambda:InvokeFunction",
      "lambda:InvokeAsync"
      ]
  
      resources = ["arn:aws:lambda:${var.region}:${data.aws_caller_identity.current.account_id}:function:${statement.value}"]
      
      effect = "Allow"
    }
  }

however if someone sets the "enable" to "" string the iam policy statement is created. which is not what i want.

My immediate thought is to add a condition that ensures the env var "enable" is not an empty string.

  dynamic "statement" {
    for_each = (var.deploy == "true" && 
      contains(keys(var.env_vars), "enable") &&
      var.env_vars.enable != "" ? <<--HERE
      [var.env_vars.enable] : 
      [])
    content {
      actions = [
        "lambda:InvokeFunction",
        "lambda:InvokeAsync"
      ]
  
      resources = ["arn:aws:lambda:${var.region}:${data.aws_caller_identity.current.account_id}:function:${statement.value}"]
      
      effect = "Allow"
    }
  }

however terraform apply returns an error, because other invocations of this module does not have "var.env_vars.enable" variable.


Error: Missing map element

  on ../modules/apollo-beanstalk/main.tf line 222, in data "aws_iam_policy_document" "web":
 222:       var.env_vars.enable != "" ?
    |----------------
    | var.env_vars is map of string with 14 elements

This map does not have an element with the key
"enable".

How can I remove any items from the var.env_vars map that have "" as their value?

Upvotes: 2

Views: 4247

Answers (2)

Marcin
Marcin

Reputation: 239000

Here is an answer addressing the issue with var.env_vars.enable != "", if you still are interested in it.

Basically instead of

var.env_vars.enable != ""

you can do the following with lookup:

lookup(var.env_vars, "enable", "") != ""

Upvotes: 1

sebastian
sebastian

Reputation: 2368

Okay I got it. This removed any items from env_vars that have "" string as their value. Fixing my problem.

locals {
  env_vars = { for k, v in var.env_vars : k => v if v != ""}
}

Upvotes: 0

Related Questions