amazon-web-servicesterraformamazon-iamaws-lake-formation

Looping through iam user arn's to pass to aws_lakeformation_permissions


I am defining lake formation permissions and I wanted to loop through all user's that are part of the admin and security IAM Group and pass them in the principal section as follows :

resource "aws_lakeformation_permissions" "example" {
  for_each = data.aws_iam_users.users
  principal   = "A LIST OF IAM USER ARNS FROM ADMIN IAM GROUP"
  permissions = ["CREATE_TABLE", "ALTER", "DROP"]

  database {
    name       = aws_glue_catalog_database.example.name
    catalog_id = "110376042874"
  }
}

I have looked at the following documentation on terraform to make use of the data source but am not sure how to reference a specific IAM Group within this :

data "aws_iam_users" "users" {}

I understand I need to make use of for_each but not entirely sure of how to obtain the list of IAM User arns that are part of the IAM Group admin and security. Is it not possible to do this via the data source

data "aws_iam_users" "users" {}

I have tried to make use of this data source : https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_users


Solution

  • Here you go:

    data "aws_iam_group" "admin" {
      group_name = "admin"
    }
    
    data "aws_iam_group" "security" {
      group_name = "security"
    }
    
    resource "aws_lakeformation_permissions" "example" {
      for_each = { for usr in concat(data.aws_iam_group.admin.users, data.aws_iam_group.security.users): usr.user_name => usr.arn }
      principal   = each.value
      permissions = ["CREATE_TABLE", "ALTER", "DROP"]
    
      database {
        name       = aws_glue_catalog_database.example.name
        catalog_id = "110376042874"
      }
    }
    
    1. Use aws_iam_group instead of aws_iam_users because the latter cannot give you a list of users by group.
    2. for_each can loop over a set of strings or a map. You have to use { for ... } loop to transform data.aws_iam_group.admin.users list of objects into a map. More about it here - https://developer.hashicorp.com/terraform/language/expressions/for#result-types.