Search code examples
terraformterraform-provider-awsterraform0.12+terraform-template-fileterraform-modules

Terraform best practise for near identical iam_policy_document's for each environment to avoid duplication


What’s the best practise for handling policy documents that are entirely the same for each environment apart from an ID within them?

  • Initially, the codebase I was using simply duplicated these policies in the iam.tf file with the ID changed in each environments resource definition. It’s a single workspace monolithic repo that I can’t change.
  • I then refactored it to be a module which creates the policy with the ID as a variable.
  • I then found out about templatefiles in terraform so I refactored it to instead be a policy .tftpl file in a subdirectory and then I call templatefile() with the different variable for each environment.

I’m aware that the recommended convention for policy documents is to implement them as a data object, but my understanding is I can’t then parameterise it to prevent entire policy documents being repeated save for a single variable (unless I modularise it like I did initially).

Does anyone have any advice on the best practise for this scenario?


Solution

  • You can definitely parameterize the aws_iam_policy_document data source.

    data "aws_iam_policy_document" "this" {
      for_each = toset(["bucket-a", "bucket-b"])
    
      statement {
        actions   = ["s3:*"]
        resources = ["arn:aws:s3:::${each.key}"]
      }
    }
    

    You can follow this pattern for attachment too:

    resource "aws_iam_policy" "this" {
      for_each = toset(["bucket-a", "bucket-b"])
    
      name_prefix = each.key
      policy      = data.aws_iam_policy_document.this[each.key].json
    }
    
    resource "aws_iam_policy_attachment" "this" {
      for_each = toset(["bucket-a", "bucket-b"])
    
      name       = "${each.key}-attachment"
      policy_arn = aws_iam_policy.this[each.key].arn
      # things to attach to
    }