Search code examples
terraformamazon-iamterraform-provider-aws

Data module terraform - How to use conditioanl block


I have a data module where I am creating "aws_iam_policy_document" "trust-policy and would like to add conditions only for certain modules, not all.

For example:

data "aws_iam_policy_document" "trust-policy" {
  statement {
    actions = [var.action]

    principals {
      type        = var.type
      identifiers = concat(var.trusted_arns)
    }
    count        = var.git ? 1 : 0
    condition {
      test     = "StringEquals"
      variable = "abc"
      values   = ["sts.amazonaws.com"]
    }
    condition {
      test     = "StringLike"
      variable = "dcf"
      values   = ["repo:var.org_name/var.repo_name:ref:refs/heads/var.branch_name"]
    }

  }
}

I want to run the condition blocks only if module is git. But with count , it fails with below error:

 An argument named "count" is not expected here.

Solution

  • You can use a dynamic block. For example, declare a new variable trust_policy_conditions like this:

    variable "trust_policy_conditions" {
      description = "A list of trust policy conditions"
      type = list(object({
        test     = string
        variable = string
        values   = list(string)
      }))
      default = []
    }
    

    Then add the dynamic block to the data source:

    data "aws_iam_policy_document" "trust-policy" {
      statement {
        actions = [var.action]
    
        principals {
          type        = var.type
          identifiers = concat(var.trusted_arns)
        }
    
        dynamic "condition" {
          for_each = var.git == true ? { for index, policy in var.trust_policy_conditions : index => policy } : {}
          content {
            test     = condition.value.test
            variable = condition.value.variable
            values   = condition.value.values
          }
        }
      }
    }
    

    Note that the index is the key as there may be a scenario where multiple conditions share the same test or variable attribute.