Search code examples
terraformterraform-provider-aws

Terraform Nested Loop


As an absolute beginner in Terraform, I'm looking to assign AWS permissions to IAM users. I have a set of usernames and managed policies that I'd like to use for this task. Here are my variables:

variable "username" {
        type = list(string)
    default = ["name1" ,"name2" , "name3"]
  
}

variable "managedpolicy" {
    type = list(string)
    default = [
        "arn:aws:iam::aws:policy/AmazonEC2FullAccess",
        "arn:aws:iam::aws:policy/AmazonS3FullAccess",
        "arn:aws:iam::aws:policy/AWSLambda_FullAccess"
    ]
}

All users will have these 3 permissions. How to achieve this task. Do I need to use nested loop.

For now I can do for one user as below file.

provider "aws" {
         region = "ap-southeast-1"
}

resource "aws_iam_user_policy_attachment" "attach" {
  user       = var.user
  policy_arn = each.value
  for_each   = toset(var.managedpolicy)
}

Solution

  • First, you create a local variable, which contains all combinations of username and managedpolicy using the setproduct function. Then you can use this local variable in the for each statement when attaching the policies.

    locals {
    combinations = {for val in setproduct(var.username, var.managedpolicy):
                    "${val[0]}-${val[1]}" => val}  
    }
    
    resource "aws_iam_user_policy_attachment" "attach" {
      for_each   = local.combinations
      user       = each.value[0]
      policy_arn = each.value[1]
    }