UserP
UserP

Reputation: 314

How to create multiple azure ad users using terraform?

I am trying to create multiple users using terraform. For now I am declaring them as locals but later on i will be using json file to create multiple users in my azuread environment.

Here is how i declare the locals:

locals {
  users = [
    [
      "user1", 
      "Example User1",
      "Password@1234#"
    ],
    [
      "user2", 
      "Example User2",
      "Password@09876#" 
    ]
  ]
}

But when I use the below code I am getting an error:

resource "azuread_user" "test" {
  for_each = local.users

  user_principal_name = "${each.value[0]}@tenantname.OnMicrosoft.com"
  display_name        = each.value[1]
  mail_nickname       = each.value[0]
  password            = each.value[2]
}

Error:

╷
│ Error: Invalid for_each argument
│
│   on main.tf line 18, in resource "azuread_user" "test":
│   18:   for_each = local.users
│     ├────────────────
│     │ local.users is tuple with 2 elements
│
│ The given "for_each" argument value is unsuitable: the "for_each" argument must be a map, or set of strings, and you have provided a value of type tuple.
╵

Will really appreciate any help on how to resolve this?

Upvotes: 2

Views: 1569

Answers (2)

SergiCarbajosa
SergiCarbajosa

Reputation: 11

As you have been told in the other answer, you need it to be a map, but before doing a for as in the other answer, it would use terraform's own tomap () function.

resource "azuread_user" "test" {

  for_each = tomap({users=local.users})

  user_principal_name = "${each.value[0]}@M365B109047.OnMicrosoft.com"
  display_name        = each.value[1]
  mail_nickname       = each.value[0]
  password            = each.value[2]

Upvotes: 0

Marcin
Marcin

Reputation: 238051

You have to covert it to a map:

resource "azuread_user" "test" {

  for_each = {for idx, user in local.users: idx => user}

  user_principal_name = "${each.value[0]}@M365B109047.OnMicrosoft.com"
  display_name        = each.value[1]
  mail_nickname       = each.value[0]
  password            = each.value[2]
}

Upvotes: 1

Related Questions