Loop through all github ip ranges

I’m trying to make an azure container registry that has an IP whitelist for every single IP range in github, provided by github provider function github_ip_ranges. This requires a loop.

I’m having a really hard time figuring out how to do this and all the stuff I find on google are all these very long winded explanations of how loops work as a concept in terraform which I don’t have time to read.

This is my code:

data "github_ip_ranges" "latest" {}

resource "azurerm_container_registry" "acr" {
  name                          = "var.acrname"
  resource_group_name           = var.resource_group_name
  location                      = var.location
  sku                           = "Premium"
  admin_enabled                 = true
  }
  network_rule_set {
    default_action = "Deny"
    ip_rule {
      for_each = data.github_ip_ranges.latest.actions_ipv4
      ip_range = each.value
      action   = "Allow"
    }
  }
}

It fails with:

│ Error: each.value cannot be used in this context

│ on main.tf line 49, in resource “azurerm_container_registry” “acr”:
│ 49: ip_range = each.value

│ A reference to “each.value” has been used in a context in which it unavailable, such as when the configuration no longer contains the value in its “for_each” expression.
│ Remove this reference to each.value in your configuration to work around this error.

If I change the value from each.value to each.key the error becoems:


│ Error: Reference to “each” in context without for_each

│ on main.tf line 49, in resource “azurerm_container_registry” “acr”:
│ 49: ip_range = each.key

│ The “each” object can be used only in “module” or “resource” blocks, and only when the “for_each” argument is set.

Solved it! Used a “locals” bloc to create the values instead. Here it is, for anyone else stuck on this in the future:

data "github_ip_ranges" "latest" {}

locals {
  allowed_ip_ranges  = [for github_cidr in data.github_ip_ranges.latest.actions_ipv4: github_cidr]
  allowed_ip_rules   = [for cidr in local.allowed_ip_ranges : {
    action   = "Allow",
    ip_range = cidr
  }]
}

resource "azurerm_container_registry" "acr" {
  name                          = "var.acrname"
  resource_group_name           = var.resource_group_name
  location                      = var.location
  sku                           = "Premium"
  admin_enabled                 = true
  network_rule_set {
    default_action = "Deny"
    ip_rule = local.allowed_ip_rules
  }
}
1 Like