Search code examples
terraformvault

Only create policy document rule on condition true - Terraform Vault


I have a Vault instance and I manage policies and secrets in it with Terraform. There are a couple of repeated steps when creating approle authentication, policy and policy documents for newly onboarded teams, because each team has several applications they work on. I'd like to modularize the repeated parts ( policy document, policy creation and approle for the team-app), though each application has a slightly different rule set. Is there a way to create policy documents in a way that some rules are only included if a bool is set to true?

for example: I have a module that creates policies and policy documents as below: I would pass a bool variable named enable_metadata_rule and based on it's value I would create the 2nd rule or not:

resource "vault_policy" "example_policy" {
  for_each = var.environments
  provider = vault
  name     = "${var.team}-${var.application}-${each.key}"
  policy   = data.vault_policy_document.policy_document["${each.key}"].hcl
}

data "vault_policy_document" "policy_document" {
  for_each = var.environments
  rule {
    path         = "engines/${var.team}-kv/data/${each.key}/services/${var.application}/*"
    capabilities = ["read", "list"]
    description  = "Read secrets for ${var.application}"
  }
  rule {
    # IF  enable_metadata_rule == true
    path         = "engines/${var.team}-kv/metadata/*"
    capabilities = ["list"]
    description  = "List metadata for kv store"
  }
}

If there isn't such thing, is there an option for merging separately created policy documents?


Solution

  • You should be able to do it using dynamic blocks:

    data "vault_policy_document" "policy_document" {
      for_each = var.environments
      rule {
        path         = "engines/${var.team}-kv/data/${each.key}/services/${var.application}/*"
        capabilities = ["read", "list"]
        description  = "Read secrets for ${var.application}"
      }  
      
      dynamic "rule" {
      
        for_each = var.enable_metadata_rule == true ? [1]: []
        
        content {
            path         = "engines/${var.team}-kv/metadata/*"
            capabilities = ["list"]
            description  = "List metadata for kv store"
        }
      }
    }