---
- name: "Initilize VARs"
  set_fact:
    found_credential_id: ""

- name: "Get {{ job.name }} job_template credential id's from awx server"
  delegate_to: localhost
  uri:
    url: "{{ awx_base_url }}/api/v2/job_templates/{{ awx_job_template_id }}/credentials"
    method: GET
    user: "{{ awx_rest_api_access_user }}"
    password: "{{ awx_rest_api_access_pw }}"
    return_content: true
    validate_certs: false
    force_basic_auth: yes
    status_code: 200
  register: awx_job_template_info
  when: (awx_job_template_id | default("") | length > 0)

- name: Save result as variable (fact)
  set_fact: 
    awx_job_template_info_json: "{{ awx_job_template_info.json }}"

- name: "Printing..."
  debug:
    msg: "{{ awx_job_template_info_json }}"
  delegate_to: 127.0.0.1
  become: false
  when:
   - debug

- name: "Search <{{ awx_credential_id }}> in <{{ job.name }}> job_template"
  vars:
    query: '[? id==`{{ awx_credential_id }}`].id'
  set_fact:
    found_credential_id: "{{ awx_job_template_info_json.results | json_query(query) | first | default(None) }}"
  when: (awx_job_template_info_json.results is defined) and (awx_job_template_info_json.results | length > 0)

- name: "Printing..."
  debug:
    msg: "{{ awx_type_id }}"
  delegate_to: 127.0.0.1
  become: false
  when:
   - debug
   - awx_type_id is defined

- name: "Add credential id {{ awx_credential_id }} to {{ job.name }} job_template"
  delegate_to: localhost
  uri:
    url: "{{ awx_base_url }}/api/v2/job_templates/{{ awx_job_template_id }}/credentials/"
    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: >
      {
        'associate': true,
        'id': {{ awx_credential_id | int }}
      }
    force_basic_auth: true
    validate_certs: false
    status_code: 204
  when: >
    (found_credential_id | default("") | length == 0) and
    (awx_credential_id is defined) and
    (awx_job_template_id | default("") | length > 0)
