---
- name: SET VARIABLES WHEN PROVISIONING
  hosts: localhost
  tags: always
  gather_facts: no
  run_once: true
  tasks:
    - name: not provisioning
      set_fact:
        provisioning: false
      delegate_facts: yes
    - name: enable provisioning
      set_fact:
        provisioning: true
      delegate_facts: yes
      when: ('force-delete' not in ansible_run_tags)

- name: OVH CLOUD PROVISIONING
  hosts: localhost
  connection: local
  tags: always
  vars:
    ovh_prefix: cloud
  tasks:
    - name: list all server in cloud project
      os_server_info:
        availability_zone: nova
        server: "{{ ovh_prefix }}-*"
        filters:
          vm_state: active
      register: result_json

    - name: register variable for futures uses
      set_fact:
        current_servers: "{{ result_json.openstack_servers }}"

    - name: add existent hosts to inventory
      add_host:
        name: "{{ item.metadata.hostname }}"
        ansible_host: "{{ item.accessIPv4 }}"
        ansible_user: debian
        ansible_become: yes
      loop: "{{ current_servers }}"

    - name: launch a compute instance for non existant hosts
      os_server:
        state: present
        name: "{{ ovh_prefix }}-{{ item }}"
        availability_zone: nova
        image: "{{ hostvars[item].image | default('a75cc6c8-f697-48a6-a820-37e68621b07a') }}"
        flavor: "{{ hostvars[item].flavor | default('b2-7-flex') }}"
        security_groups: default
        key_name: gitlab
        meta:
          hostname: "{{ item }}"
        nics:
          - net-name: Ext-Net
          - net-name: backend
      when:
        - hostvars[item].ansible_host is defined
        - hostvars[item].ansible_host == "ovhcloud"
        - hostvars.localhost.provisioning == true
        - item not in current_servers
      register: openstack_servers
      loop: "{{ query('inventory_hostnames', 'all:!localhost') }}"

    - name: add created hosts to inventory
      add_host:
        name: "{{ item.metadata.hostname }}"
        ansible_host: "{{ item.accessIPv4 }}"
        ansible_user: debian
        ansible_become: yes
      loop: "{{ openstack_servers | json_query('results[*].openstack') }}"

...
