# description: Terraform single OpenStack instance with floating IP

provider "openstack" {
  {% if "cloud" in vars %}
     cloud = "{{ vars['cloud'] }}"
  {% else %}
     auth_url = "{{ vars['auth_url']|env_override('OS_AUTH_URL') }}"
     password = "{{ vars['password']|env_override('OS_PASSWORD') }}"
     user_name = "{{ vars['username']|env_override('OS_USERNAME') }}"
     tenant_name = "{{ vars['tenant_name']|env_override('OS_PROJECT_NAME') }}"
     domain_name = "{{ vars['domain_name']|env_override('OS_USER_DOMAIN_NAME') }}"
  {% endif %}
}

data "openstack_networking_network_v2" "provider-network" {
  name = "{{ vars['provider_network'] }}"
}

resource "openstack_networking_network_v2" "test-network" {
  name = "test-network"
}

resource "openstack_networking_subnet_v2" "test-subnet" {
  network_id = "${openstack_networking_network_v2.test-network.id}"
  cidr       = "10.0.0.0/24"
}

resource "openstack_compute_keypair_v2" "keypair1" {
  name = "keypair2"
  public_key = "${file("~/.ssh/id_rsa.pub")}"
}

resource "openstack_networking_router_v2" "test-router" {
  name                = "test-router"
  admin_state_up      = true
  external_network_id = "${data.openstack_networking_network_v2.provider-network.id}"
}

resource "openstack_networking_router_interface_v2" "test-router-interface" {
  router_id = "${openstack_networking_router_v2.test-router.id}"
  subnet_id = "${openstack_networking_subnet_v2.test-subnet.id}"
}

resource "openstack_compute_secgroup_v2" "test-sg" {
  name        = "test-sg"
  description = "test-sg"

  rule {
    from_port       = -1
    to_port         = -1
    ip_protocol = "icmp"
    cidr        = "0.0.0.0/0"
  }

  rule {
    from_port   = 22
    ip_protocol = "tcp"
    to_port     = 22
    cidr        = "0.0.0.0/0"
  }

  rule {
    from_port   = 80
    ip_protocol = "tcp"
    to_port     = 80
    cidr        = "0.0.0.0/0"
  }
}

resource "openstack_compute_instance_v2" "test-server" {
  name = "{{ vars['instance_name']|default('test-server') }}"
  image_name = "{{ vars['image_name']|default('rhel-7.6-server-x86_64-latest') }}"
  flavor_name = "{{ vars['flavor']|default('m1.large') }}"
  key_pair = "${openstack_compute_keypair_v2.keypair1.name}"
  security_groups = formatlist("%s", openstack_compute_secgroup_v2.test-sg.name)

network {
    name = "test-network"
  }
}

resource "openstack_networking_floatingip_v2" "test-fip" {
  pool = "{{ vars['provider_network'] }}"
}

resource "openstack_compute_floatingip_associate_v2" "fip_assosiate" {
  instance_id = openstack_compute_instance_v2.test-server.id
  floating_ip = "${openstack_networking_floatingip_v2.test-fip.*.address[0]}"
}

output "floating_ip" {
  value = "${openstack_networking_floatingip_v2.test-fip.*.address}"
}
