opensource engineer
opensource engineer

Reputation: 59

how to associate floating ip address to a instance in openstack using terraform

I am using terraform to create couple of instances in openstack and I would like to automatically assign floatings ip address to them without any manual intervention.

My .tf file is as below:

resource "openstack_networking_floatingip_v2" "floating-ip" {
 count  = 4
 pool = "floating-ip-pool" 
}

resource "openstack_compute_floatingip_associate_v2" "fip-associate" {
floating_ip = openstack_networking_floatingip_v2.floating-ip.address[count.0]
instance_id = openstack_compute_instance_v2.terraform-vm.id[count.0]
}`

I am getting an error

"Error: Missing resource instance key

on image-provisioning.tf line 33, in resource "openstack_compute_floatingip_associate_v2" "fip-associate": 33: instance_id = openstack_compute_instance_v2.terraform-vm.id[count.0]"

My terraform version is : Terraform v0.12.24 + provider.openstack 1.26.0

Upvotes: 1

Views: 3589

Answers (2)

opensource engineer
opensource engineer

Reputation: 59

able to resolve using for_each option in terraform :

resource "openstack_compute_instance_v2" "terraform_vm" {
     image_id        = "f8b9189d-2518-4a32-b1ba-2046ea8d47fd"
     for_each        =  var.instance_name
     name            =  each.key
     flavor_id       = "3"
     key_pair        = "openstack vm key"
     security_groups = ["default"]

    network {
     name = "webapps-network"
    }
}

resource "openstack_networking_floatingip_v2" "floating_ip" {
    pool     = "floating-ip-pool"
    for_each =  var.instance_name
}

resource "openstack_compute_floatingip_associate_v2" "fip_associate" {
    for_each    =  var.instance_name
    floating_ip = openstack_networking_floatingip_v2.floating_ip[each.key].address
    instance_id = openstack_compute_instance_v2.terraform_vm[each.key].id
}

Upvotes: 0

maikel
maikel

Reputation: 1165

You need to use the port_id in the associate. That can be looked up using the compute instance IPv4 address:

resource "openstack_networking_floatingip_v2" "floating-ip" {
  # count = 4
  pool  = "floating-ip-pool" 
}

data "openstack_networking_port_v2" "terraform-vm" {
  fixed_ip = openstack_compute_instance_v2.terraform-vm.access_ip_v4
}

resource "openstack_compute_floatingip_associate_v2" "fip-associate" {
  floating_ip = openstack_networking_floatingip_v2.floating-ip.address
  port_id     = data.openstack_networking_port_v2.terraform-vm.id
}

Upvotes: 0

Related Questions