terraform .12 - add multiple inline policies

Viewed 1103

I am wondering if there is an easy way to add multiple json file policies

mypolicy1.json, mypolicy2.json, mypolicy3.json

as of now this is my code.. works great for one policy

variable "iam_policy_path" {
  default = "./mypolicy.json"  
}

resource "aws_iam_role_policy" "role" {
  name   = var.name
  role   = var.role
  policy = file(var.iam_policy_path)
}

module "aws_iam_role_policy" {
   source = "../modules/mypolicypolicy/"
   name = "mypolicy"
   role = module.myrole.myroleout
   iam_policy_path = "new_policy_path.json"
}
1 Answers

One way would be to use for_each and having your iam_policy_path being a list of paths.

For example:

variable "iam_policy_path" {
  default = ["./mypolicy.json", "./mypolicy2.json"]  
}

resource "aws_iam_role_policy" "role" {
  
  for_each = toset(var.iam_policy_path) # for each requires set. 
 
  name   = var.name
  role   = var.role

  policy = file(each.key)
}

Then when using the module:

module "aws_iam_role_policy" {
   source = "../modules/mypolicypolicy/"
   name = "mypolicy"
   role = module.myrole.myroleout
   iam_policy_path = ["new_policy_path.json", "new_policy_path2.json"]
}

Based on the extra info. The complete solution may require also using aws_iam_role_policy_attachment which attaches a managed policy to a role.

Related