Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a list in Terraform from data sources

Tags:

terraform

I have a data management issue that I have been banging my head against. I have some Openstack resources managed outside Terrafrom that I need to find the IP addresses for, then add them to a list that can be handed through Ansible or cloud-init. There are an arbitrary number of these resources, rather than being a fixed list size, or names.

I have the names of the resources, so I am looking them up via for_each:

data "openstack_networking_port_v2" "ports" {
  for_each = toset(var.assigned_ports)
  name = "${each.key}port"
}

which results in a data source for each resource like this:

data.openstack_networking_port_v2.ports["host1port"]
data.openstack_networking_port_v2.ports["host2port"]
data.openstack_networking_port_v2.ports["host3port"]

where the content includes the IP address I'm after via a field (below is truncated for brevity):

data "openstack_networking_port_v2" "ports" {
    admin_state_up         = true
    all_fixed_ips          = [
        "10.1.2.3",
    ]
    all_security_group_ids = [
        "2cccdd5f-dec0-4f2e-80a3-ceefbb3625ff",
    ]
}

I would like to build a local that is a list of these IP addresses that I can use somewhere, but I am struggling to get anywhere, especially as the IP address I am after is element 0 in the list, eg:

data.openstack_networking_port_v2.ports["host3port"].all_fixed_ips[0]

any help would be greatly appreciated.

like image 698
Nafsten Avatar asked Oct 26 '25 14:10

Nafsten


1 Answers

I managed to solve it by creating a local like below:

locals {
  ips = [ for ip in data.openstack_networking_port_v2.ports: ip.all_fixed_ips[0]]
}

I had tried something similar before, but was incorrectly iterating on:

data.openstack_networking_port_v2.ports[*]
like image 108
Nafsten Avatar answered Oct 29 '25 14:10

Nafsten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!