Use a list inside a loop

Hi there,

I have a variable as below, setting a list with security groups from a remote_state:

variable "instances" {
    description = "instances to be deployed"
    type        = map(object({
        ufqdn     = string
...
        secgroups  = list(string)
        }))
    default = {
        "instance-1" = {
            ufqdn     = "instance-1.domain.com"
...
            secgroups  = [ "data.terraform_remote_state.network.outputs.secgroup1", 
                          "data.terraform_remote_state.network.outputs.secgroup2", **
                         "data.terraform_remote_state.network.outputs.secgroup3"**
                        ]
    },
        "instance-2" = {
            ufqdn     = "instance-2.domain.com"
...
            secgroups  = [ "data.terraform_remote_state.network.outputs.secgroup4", 
                          "data.terraform_remote_state.network.outputs.secgroup5", 
                          "data.terraform_remote_state.network.outputs.secgroup6"
                        ]
    }
}

And the .tf consuming the variable is below:

resource "openstack_networking_port_v2" "port_instance" {
  for_each           = var.instances
  name               = "port-${each.value.ufqdn}"
  network_id         = data.terraform_remote_state.network.outputs.network_id
  security_group_ids = each.value.secgroups

Whenever I try to apply this definition, I got an error saying that the IDs weren’t found.

The problem seems that I cannot use variables as inputs.

Any clue on how to use variables as inputs for other variables?

Thanks in advance,

Hi @hutger,

The default value for an input variable is always a constant value, so it can’t refer to any other objects in the module.

I think you’re seeing the error you’re seeing here because "data.terraform_remote_state.network.outputs.secgroup1" is a string containing literally those characters, not actually a reference to data.terraform_remote_state.network. Terraform is therefore sending those strings to the OpenStack provider as security_group_ids, which fails because you presumably don’t have a security group object in your remote system whose id is data.terraform_remote_state.network.outputs.secgroup1.

It’s difficult to suggest a different approach here because I can’t really see what your underlying goal is, but I’d say it’s quite unusual for a complex variable like this to have a default value. Do you have some callers of this module that override instances while others just take the default? Could you refactor this so that instances is a required variable and the calling module itself can be the one to load the data from the remote state if needed?