How to populate a list in resource

Specifically for the rancher2_registry Resource, it has a registries argument that says it is a list but I can’t figure out how to populate it.
https://registry.terraform.io/providers/rancher/rancher2/latest/docs/resources/registry
Here’s what the rancher2_registry looks like

# Create a new rancher2 Namespaced Registry
resource "rancher2_registry" "foo" {
  name = "foo"
  description = "Terraform registry foo"
  project_id = "<project_id>"
  namespace_id = "<namespace_id>"
  registries {
    address = "test.io"
    username = "user2"
    password = "pass"
  }
}

My variable looks like this

variable "containerRepositories" {
  type = list(object({
    url = string
    username = string
    password = string
  }))
  default = []
  description = "A list of Docker container repositories"
}

Here’s how I’m trying to do it, which is not correct.

# Add the customers Artifactory Docker registries as Rancher registries in case they want to load custom build images from one of them.
resource "rancher2_registry" "registry" {
  count = length(var.containerRepositories) > 0 ? 1 : 0
  name = "registry"
  description = "Registry entry to talk to customers Artifactory Docker registries"
  project_id = var.rancherProject
  namespace_id = rancher2_namespace.jenkins-namespace.id
  registries {
    for auth in var.containerRepositories : auth => {
      address = auth.url
      username = auth.username
      password = auth.password
    }
  }
}

Does anyone know how to accomplish this?

I haven’t used this provider, but I believe the Terraform language feature you’re looking for here is dynamic blocks. Try this:

resource "rancher2_registry" "registry" {
  count = length(var.containerRepositories) > 0 ? 1 : 0
  name = "registry"
  description = "Registry entry to talk to customers Artifactory Docker registries"
  project_id = var.rancherProject
  namespace_id = rancher2_namespace.jenkins-namespace.id

  dynamic "registries" {
    for_each = var.containerRepositories
    content {
      address = registries.url
      username = registries.username
      password = registries.password
    }
  }
}

@alisdair, Thank you! That was it (mostly). I didn’t know that even existed. Always so much more to learn with Terraform.
For future reference I had to make one minor change, which I learned from link @alisdair gave above.

Here’s the working code for my example above.

resource "rancher2_registry" "registry" {
  count = length(var.containerRepositories) > 0 ? 1 : 0
  name = "registry"
  description = "Registry entry to talk to customers Artifactory Docker registries"
  project_id = var.rancherProject
  namespace_id = rancher2_namespace.jenkins-namespace.id
  dynamic "registries" {
    for_each = var.containerRepositories
    content {
      address = registries.value["url"]
      username = registries.value["username"]
      password = registries.value["password"]
    }
  }
}
1 Like