---

# Parameters:
#   playbook inventory
#     stage := the name of the stage (e.g. dev, int, qa, prod)
#     username := the default username to use for the ssh connection

#############################################################
#   Creating inventory dynamically for given parameters
#############################################################

- hosts: localhost
  connection: local
  gather_facts: false

  pre_tasks:
    - name: "Check if ansible version is at least {{ ansible_minimal_version }}"
      assert:
        that:
          - ansible_version.string is version(ansible_minimal_version, ">=")
        msg: "The ansible version has to be at least {{ ansible_minimal_version }}"

#     add virtual server to load stage specific variables as context
    - name: "Add <{{ stage }}-virtual-host-to-read-groups-vars> to hosts"
      add_host:
        name: "{{ stage }}-virtual-host-to-read-groups-vars"
        groups:
        - "stage_{{ stage }}"
      changed_when: False

#############################################################
#   Updating ssh config for servers with given stage
#############################################################

- hosts: "{{ stage }}-virtual-host-to-read-groups-vars"
  serial: "{{ serial_number | default(1) }}"
  gather_facts: false
  connection: local

  pre_tasks:
    - name: "Reading current server groups from hetzner"
      include_role:
        name: hetzner-ansible-hcloud
        tasks_from: _read_server_infos
      with_items: [
        {
          name: "all",
          label_selector: "stage={{ stage }}",
        }
      ]
      loop_control:
        loop_var: current_server_group

  tasks:
    - name: 'Insert/Update ssh config in ~/.ssh/config'
      blockinfile:
        marker: "# {mark} managed by ansible (hosts config for {{ stage }})"
        path: '~/.ssh/config'
        state: present
        create: yes
        block: |
          {% for host in server_group_infos_all %}
          Host {{ host.name }}
            HostName {{ host.ip }}
            User {{ username }}
          {% endfor %}
