I would like to assign members to Azure Active Directory groups after creating them using Terraform and the resources "azuread_group_member", "azuread_group" and "azuread_user".
First of all, I have a CSV file that has a relationship between users and departments:
first_name,last_name,department
UserName1,LastName1,Department1
UserName2,LastName2,Department2
And other CSV file containing the groups:
department_name
Department1
Department2
Then, I have a local variable that is reading these CSV files:
locals {
users = csvdecode(file("${path.module}/users.csv"))
groups = csvdecode(file("${path.module}/aad_groups.csv"))
}
Next, I create the users:
# Create users
resource "azuread_user" "users" {
for_each = { for user in local.users : user.first_name =\> user }
user_principal_name = format(
"%s@%s",
each.value.employee_id,
"mydomain.com"
)
}
Following, I create the groups iterating the groups.csv
# Create groups resource
"azuread_group" "groups" {
for_each = { for group in local.groups : group.deparment_name => group }
display_name = each.value.deparment_name
security_enabled = true }
But now, I would like assign members, with "azuread_group_member" to the groups using the relationship that I have in users.csv, in the column "department"
How can I do that?
I have created users and groups as below.
locals {
users = {
"[email protected]" = { first_name = "John", last_name = "Doe" , password = "xxx@123",department = "Marketing Department" },
"[email protected]" = { first_name = "Jane", last_name = "Doe" , password = "xxx@123",department = "IT Department"}
}
}
locals {
groups = {
"Marketing Department" = { display_name = "Marketing Department" },
"Sales Department" = { display_name = "Sales Department" },
"IT Department" = { display_name = "IT Department" }
}
}
resource "azuread_user" "users" {
for_each = local.users
display_name = "${each.value.first_name} ${each.value.last_name}"
mail_nickname = each.value.first_name
user_principal_name = each.key
password = each.value.password
department = each.value.department
}
resource "azuread_group" "departments" {
for_each = local.groups
display_name = each.value.display_name
security_enabled = true
mail_enabled =false
}
Here note that group key value must match the user department value.
example : Marketing Department , which equals user department of John Doe
resource "azuread_group_member" "group_members" {
for_each = local.users
group_object_id = azuread_group.departments[each.value.department].object_id
member_object_id = azuread_user.users[each.key].object_id
}
With the above mapping i could add the users based on their department to groups .