---
- name: Include prompts
  import_tasks: prompts.yml

- name: Upload the SSH key
  digital_ocean_sshkey:
    oauth_token: "{{ algo_do_token }}"
    name: "{{ SSH_keys.comment }}"
    ssh_pub_key: "{{ lookup('file', SSH_keys.public) }}"
  register: do_ssh_key

- name: Creating a droplet...
  digital_ocean_droplet:
    state: present
    name: "{{ algo_server_name }}"
    oauth_token: "{{ algo_do_token }}"
    size: "{{ cloud_providers.digitalocean.size }}"
    region: "{{ algo_do_region }}"
    image: "{{ cloud_providers.digitalocean.image }}"
    wait_timeout: 300
    unique_name: true
    ipv6: true
    ssh_keys: "{{ do_ssh_key.data.ssh_key.id }}"
    user_data: "{{ lookup('template', 'files/cloud-init/base.yml') | string }}"
    tags:
      - Environment:Algo
  register: digital_ocean_droplet

# Return data is not idempotent
- set_fact:
    droplet: "{{ digital_ocean_droplet.data.droplet | default(digital_ocean_droplet.data) }}"

- when: alternative_ingress_ip | bool
  block:
    - name: Create a Floating IP
      community.digitalocean.digital_ocean_floating_ip:
        state: present
        oauth_token: "{{ algo_do_token }}"
        droplet_id: "{{ droplet.id }}"
      register: digital_ocean_floating_ip

    - name: Set the static ip as a fact
      set_fact:
        cloud_alternative_ingress_ip: "{{ digital_ocean_floating_ip.data.floating_ip.ip }}"

- set_fact:
    cloud_instance_ip: "{{ (droplet.networks.v4 | selectattr('type', '==', 'public')).0.ip_address }}"
    ansible_ssh_user: algo
    ansible_ssh_port: "{{ ssh_port }}"
    cloudinit: true
