I have the following csv
file :
first_name,last_name,department,job_title
Michael,Scott,TF_TEST1,Manager
Jim,Halpert,TF_TEST1,Engineer
Pam,Beesly,TF_TEST2,Engineer
I want to create all those users and set them member of the group corresponding to their departement, like :
User | Group |
---|---|
Michael Scott | TF_TEST1 |
Jim Halpert | TF_TEST1 |
Pam Beesly | TF_TEST2 |
Here is what I have so far :
# Configure the Azure Active Directory Provider
provider "azuread" {}
# Retrieve domain information
data "azuread_domains" "default" {
only_initial = true
}
locals {
domain_name = data.azuread_domains.default.domains.0.domain_name
users = csvdecode(file("${path.module}/users.csv"))
groups = toset(local.users[*].department)
}
resource "azuread_user" "users" {
for_each = { for user in local.users : user.first_name => user }
user_principal_name = format(
"%s.%s@%s",
lower(each.value.first_name),
lower(each.value.last_name),
local.domain_name
)
password = format(
"%s%s%s!",
lower(each.value.last_name),
substr(lower(each.value.first_name), 0, 1),
length(each.value.first_name)
)
force_password_change = true
display_name = "${each.value.first_name} ${each.value.last_name}"
department = each.value.department
job_title = each.value.job_title
}
resource "azuread_group" "groups" {
for_each = local.groups
display_name = each.key
security_enabled = true
assignable_to_role = true
}
Users and groups get created just fine. However I can't figure a way of adding those users inside their corresponding groups.
I feel like I should itarate through my azuread_user.users
and azuread_group.groups
to make the binding using a group_member resources but no chance.
Or maybe that would be easier using the members = []
property from group resource ?
Any help will be appreciated :)
CodePudding user response:
As per our discussion from the comments, you can achieve what you want by using a combination of values
built-in function [1] and if
instead of the ternary operator:
resource "azuread_group" "groups" {
for_each = local.groups
display_name = each.key
security_enabled = true
assignable_to_role = true
members = [ for u in values(azuread_user.users) : u.id if u.department == each.key ]
}