'Dynamically create a list of objects to be used inside a module in Terraform

I am trying to dynamically create a list of objects within a Terraform module so I dont need to hard code unnecessary repeated values. I found a module on the Terraform Registry that is the basis of what I am doing. The module is located at https://github.com/cloudposse/terraform-aws-sso. In the examples/complete/main.tf in module "sso_account_assignments", they duplicate the AdministratorAccess permission set for different AWS accounts. My problem is I have nearly 30 accounts where I want to assign the same permission set but I dont want to duplicate entries in the code with just the account number being different. I am experienced with Python and the way I would write it with Python would be something like the following:

If I Were to Write It In Python

account_list = ['11111111111', '22222222222', '33333333333']
account_assignments = []
for acct in account_list:
    obj = {
        "account": acct,
        "permission_set_arn": "Some value......",
        "permission_set_name": "AdministratorAccess",
        "principal_type": "GROUP",
        "principal_name": "Administrators"
    }
    account_assignments.append(obj)

print(account_assignments)

Output

[
   {
      "account":"11111111111",
      "permission_set_arn":"Some value......",
      "permission_set_name":"AdministratorAccess",
      "principal_type":"GROUP",
      "principal_name":"Administrators"
   },
   {
      "account":"22222222222",
      "permission_set_arn":"Some value......",
      "permission_set_name":"AdministratorAccess",
      "principal_type":"GROUP",
      "principal_name":"Administrators"
   },
   {
      "account":"33333333333",
      "permission_set_arn":"Some value......",
      "permission_set_name":"AdministratorAccess",
      "principal_type":"GROUP",
      "principal_name":"Administrators"
   }
]

Basically I am having trouble figuring out how to dynamically build the list of objects in Terraform. I am sure it can be solved with a for_each or for loop but not figuring it out. Hopefully this makes sense.

Tried writing the code but it is not working and is erroring. I looked at HashiCorp's documentation but no luck.



Solution 1:[1]

You can accomplish this with a simple for loop:

variable "account_list" {
  default = ["11111111111", "22222222222", "33333333333"]
}

locals {
  account_assignments = [for account_id in var.account_list : {
    "account" : account_id,
    "permission_set_arn" : "Some value......",
    "permission_set_name" : "AdministratorAccess",
    "principal_type" : "GROUP",
    "principal_name" : "Administrators"
  }]
}

output "account_assignments" {
  value = local.account_assignments
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ervin Szilagyi