---

- name: "Initialize VARs"
  set_fact:
    awx_job_template_id: "None"
    job:
      name: "{{ item | regex_replace('^(.*)/pmci-(.*).yml$', 'pmci-\\2') }}"
      description: "{{ item | regex_replace('^(.*)/pmci-(.*).yml$', 'pmci-\\2') }}"
  changed_when: False

- name: "Search job template {{ job.name }}"
  include_tasks: awx-config-get-typ-id.yml
  vars:
    awx_rest_api_type: job_templates
    awx_search_key: name
    awx_search_name: "{{ job.name }}"

- name: "Update awx_job_template_id"
  set_fact:
    awx_job_template_id: "{{ awx_type_id }}"
  when:
    - (awx_type_id | default(None)) != "None"

- name: "Add job template {{ job.name }}"
  delegate_to: localhost
  vars:
    name: "{{ job.name }}"
    description: "{{ job.description | default(job.name) }}"
    inventory_id: "{{ awx_localhost_inventory_id }}"
    project_id: "{{ awx_hetzner_ansible_project_id }}"
    execution_environment_id: "{{ awx_ee_hetzner_ansible_id }}"
    playbook: "{{ job.playbook_file | default(job.name + '.yml') }}"
    ask_variables_on_launch: true
  uri:
    url: "{{ shared_service_kube_url_awx }}/api/v2/job_templates/"
    method: POST
    user: "{{ awx_rest_api_access_user }}"
    password: "{{ awx_rest_api_access_pw }}"
    headers:
      Content-Type: "application/json"
      Accept: "application/json"
    body_format: "json"
    body: "{{ lookup('template','awx-create-job-template.json.j2') }}"
    force_basic_auth: true
    validate_certs: false
    status_code: 201
  register: response
  changed_when: response.status == 201
  when: awx_job_template_id == "None"

- name: "Search job template {{ job.name }}"
  include_tasks: awx-config-get-typ-id.yml
  vars:
    awx_rest_api_type: job_templates
    awx_search_key: name
    awx_search_name: "{{ job.name }}"
  when: awx_job_template_id == "None"

- name: "Update awx_job_template_id"
  set_fact:
    awx_job_template_id: "{{ awx_type_id }}"
  when: awx_job_template_id == "None"

- include_tasks: awx-config-job-template-credential.yml
  loop: "{{ job_templates_credentials }}"
  loop_control:
    loop_var: awx_credential_id
  when: awx_job_template_id is defined
