---
- name: Create
  hosts: localhost
  connection: local
  gather_facts: false
  no_log: "{{ not (lookup('env', 'MOLECULE_DEBUG') | bool or molecule_yml.provisioner.log|default(false) | bool) }}"

  vars:
    ssh_user: root
    ssh_port: 22
    ssh_identity_file: /tmp/molecule_ssh_key

  tasks:
    - name: create ssh key
      command: ssh-keygen -f {{ ssh_identity_file }}
      args:
        creates: "{{ ssh_identity_file }}"

    - name: save ssh key into a variable
      command: cat {{ ssh_identity_file }}.pub
      register: molecule_ssh_key
      changed_when: no

    - name: upload digitalocean ssh key
      digital_ocean_sshkey:
        name: "{{ ssh_identity_file }}"
        state: present
        ssh_pub_key: "{{ molecule_ssh_key.stdout }}"
      register: digital_ocean_ssh_key

    - name: start digitalocean droplet
      digital_ocean:
        name: "{{ item.name }}"
        state: present
        size_id: "{{ item.size_id | default('2gb') }}"
        region_id: "{{ item.region_id | default('ams3') }}"
        image_id: "{{ item.image_id | default('centos-7-x64') }}"
        unique_name: yes
        ssh_key_ids:
          - "{{ digital_ocean_ssh_key.data.ssh_key.id }}"
      register: server
      with_items:
        - "{{ molecule_yml.platforms }}"

    - name: render sshd_config for instances
      template:
        src: sshd_config.j2
        dest: "{{ molecule_ephemeral_directory }}/sshd_config"
      when: server.changed | bool

    - name: wait for ssh_port to be available
      wait_for:
        port: "{{ ssh_port }}"
        host: "{{ item.droplet.ip_address }}"
        search_regex: SSH
        delay: 10
        timeout: 320
      with_items:
        - "{{ server.results }}"

    # Mandatory configuration for Molecule to function.

    - name: Populate instance config dict
      set_fact:
        instance_conf_dict: {
          'instance': "{{ item.droplet.id }}",
          'address': "{{ item.droplet.ip_address}}",
          'user': "{{ ssh_user }}",
          'port': "{{ ssh_port }}",
          'identity_file': "{{ ssh_identity_file }}", }
      with_items: "{{ server.results }}"
      register: instance_config_dict
      when: server.changed | bool

    - name: Convert instance config dict to a list
      set_fact:
        instance_conf: "{{ instance_config_dict.results | map(attribute='ansible_facts.instance_conf_dict') | list }}"
      when: server.changed | bool

    - name: Dump instance config
      copy:
        content: "{{ instance_conf | to_json | from_json | molecule_to_yaml | molecule_header }}"
        dest: "{{ molecule_instance_config }}"
      when: server.changed | bool
