# Nested loop (using github provider)

**URL:** <https://discuss.hashicorp.com/t/nested-loop-using-github-provider/2837>\
**Category:** Terraform\
**Created:** [September 17, 2019, 6:08am UTC](https://discuss.hashicorp.com/t/nested-loop-using-github-provider/2837 "2019-09-17T06:08:42Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![apparentlymart](https://sea2.discourse-cdn.com/hashicorp/user_avatar/discuss.hashicorp.com/apparentlymart/32/702_2.png) [@apparentlymart](https://discuss.hashicorp.com/u/apparentlymart)\
**Post date:** [September 18, 2019, 12:02am UTC](https://discuss.hashicorp.com/t/nested-loop-using-github-provider/2837/2 "2019-09-18T00:02:31Z")

</div>

Hi @HormyAJP,

The main tools for dealing with this sort of situation are [`for` expressions](https://www.terraform.io/docs/configuration/expressions.html#for-expressions) and [the `flatten` function](https://www.terraform.io/docs/configuration/functions/flatten.html). With these two features, we can transform collections and flatten out nested collections for use with the repetition constructs like resource `for_each`.

You didn’t show how you want the collaborators to be represented in your configuration structure but I’m going to assume a variable defined like this for the sake of example:

```auto
variable "repositories" {
  type = map(object({
    allow_merge_commit = bool
    allow_squash_merge = bool
    allow_rebase_merge = bool
    branch_protection = object({
      required_approving_review_count = number
    })

    # Map from username to permission level,
    # like {"bobsmith" = "pull"}.
    collaborator_permissions = map(string)
  }))
}

```

To transform this into a flat set of (repository, username, permission) structures we’ll use `flatten` with some `for` expressions:

```auto
locals {
  repo_collaborators = flatten([
    for rn, r in var.repositories : [
      for un, pn in r.collaborator_permissions : {
        repo = rn
        username = u
        permission = pn
      }
    ]
  ])
}

resource "github_repository_collaborator" "example" {
  # Each instance must have a unique key, so we'll
  # construct them by concatenating the repository
  # name and the username.
  for_each = {
    for rc in local.repo_collaborators :
    "${rc.repo}:${rc.username}" => rc
  }

  repository = each.value.repo
  username = each.value.username
  permission = each.value.permission
}

```

This will produce resource instances with addresses like `github_repository_collaborator.example["repository_1:bobsmith"]`, allowing Terraform to correlate any changes to the collaborator permissions maps with the appropriate resource instances for ongoing updates.

---

_[View the full topic](https://discuss.hashicorp.com/t/nested-loop-using-github-provider/2837)._
