1 year ago

#344312

test-img

Sarmad

Terraform - Reference a for_each resource from another for_each resource

I have a terraform file with the following contents:

resource "aws_iam_group" "developers" {
  name     = each.value
  for_each = toset(var.groups)
}

resource "aws_iam_group_membership" "developers_team" {
  name = "Developers Team"

  users    = [each.value]
  for_each = toset(var.group_users)

  group = aws_iam_group.developers.name
}

I would like to reference aws_iam_group from aws_iam_group_membership. How would I do that? The current terraform file is not working.

I tried this:

group = aws_iam_group.developers[each.value] //This will not work since it uses the for_each of 
its own code block

The variable file is as below:

variable "groups" {
  type = list(string)
  default = [
    "terraform_group1",
    "terraform_group2",
    "terraform_group3",
  ]
}

variable "group_users" {
  type = list(string)
  default = [
    "terraform_test_user1",
    "terraform_test_user2"
  ]
}

Edit: I tried the below, but it is not working

resource "aws_iam_group_membership" "developers_team" {
  name = "Developers Team"

  users    = [for group_user in var.group_users : group_user]
  for_each = toset(var.groups)

  group = aws_iam_group.developers[each.key]
}

Apparently, this is working:

resource "aws_iam_group" "developer" {
  name     = "truedeveloper"
}

resource "aws_iam_group_membership" "developers_team" {
  name = "Developers_Team"

  users    = [for group_user in var.group_users : group_user]
  for_each = toset(var.groups)

  group = aws_iam_group.developer.name
}

terraform

terraform-provider-aws

terraform-template-file

0 Answers

Your Answer

Accepted video resources