---
- name: Create temp directory for kubeconfig
  command: mktemp -d /tmp/openshift-ansible-XXXXXX
  register: mktemp
  changed_when: False

- name: Copy the admin client config(s)
  command: >
    cp {{ openshift_master_config_dir }}/admin.kubeconfig {{ mktemp.stdout }}/admin.kubeconfig
  changed_when: False

- name: Determine if projects exist
  command: >
    {{ openshift.common.client_binary }} --config={{ mktemp.stdout }}/admin.kubeconfig
    get projects {{ item.key }} -o json
  with_dict: "{{ openshift_projects }}"
  failed_when: false
  changed_when: false
  register: project_test

- name: Create projects
  command: >
    {{ openshift.common.client_binary }} adm --config={{ mktemp.stdout }}/admin.kubeconfig
    new-project {{ item.item.key }}
    {% if item.item.value.default_node_selector | default(none) != none %}
    {{ '--node-selector=' ~ item.item.value.default_node_selector }}
    {% endif %}
  when: item.rc == 1
  with_items:
  - "{{ project_test.results }}"

- name: Update project default node selector if necessary
  command: >
    {{ openshift.common.client_binary }}
    --config={{ mktemp.stdout }}/admin.kubeconfig patch namespace {{ item.item.key }}
    -p '{"metadata": {"annotations": {"openshift.io/node-selector": "{{ item.item.value.default_node_selector }}"}}}'
  when:
  - item.rc == 0
  - item.item.value.default_node_selector | default(none) != none
  - item.item.value.default_node_selector | default(none) != (item.stdout | from_json).metadata.annotations['openshift.io/node-selector'] | default(none)
  with_items:
  - "{{ project_test.results }}"
  register: annotate_project

- name: Delete temp directory
  file:
    name: "{{ mktemp.stdout }}"
    state: absent
  changed_when: False
