---

# Parameters:
#   playbook inventory
#     stage := the name of the stage (e.g. devnso, qanso, prodnso)
#     tenant := object with tenant related data
#       key := 
#     cluster := object with cluster specific data (optional)
#       key := 
#       size := 
#       service := 
#       features := 
#     data := object with action specific data (optional)
#       ...

#############################################################
#   Creating inventory dynamically for given cluster
#############################################################

- hosts: localhost
  gather_facts: false
  connection: local

  pre_tasks:
    - name: "Import constraints check"
      import_tasks: tasks/constraints_check.yml
      become: false
      tags:
        - always

  tasks:
#   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

    - name: "Add <{{ cluster.stage }}-{{ tenant.key }}-{{ cluster.key }}-01> to hosts"
      add_host:
        name: "{{ cluster.stage }}-{{ tenant.key }}-{{ cluster.key }}-01"
        groups:
        - "stage_{{ stage }}"
      changed_when: False

#############################################################
#   
#############################################################

- hosts: "{{ cluster.stage }}-{{ tenant.key }}-{{ cluster.key }}-01"
  serial: "{{ serial_number | default(1) }}"
  gather_facts: false
  connection: local
  run_once: true

  tasks:
    - name: "Add postgres servers to hosts if necessary"
      add_host:
        name: "{{ shared_service_postgres_primary }}"
        groups:
        - "{{ item }}"
        - "stage_{{ stage }}"
        - "pmci_database_selector"
      changed_when: False
      with_items: "{{ ['hcloud'] + ['stage_' + stage ] + [cluster.service] + (cluster.features | default([])) }}"
      when: item in ['connect', 'management_connect', 'keycloak', 'gitea']

    - name: "Add maria servers to hosts if necessary"
      add_host:
        name: "{{ shared_service_maria_primary }}"
        groups:
        - "{{ item }}"
        - "stage_{{ stage }}"
        - "pmci_database_selector"
      changed_when: False
      with_items: "{{ ['hcloud'] + ['stage_' + stage ] + [cluster.service] + (cluster.features | default([])) }}"
      when: item in ['connect_wordpress']
