---

# When the job doesn't exist, we provide an empty XML, and then work
# directly on the jenkins_home/jobs/JOB/config.xml file
- name: Create a empty job
  shell: "echo '<project />' | {{ jenkins_cli_command }} create-job {{ job.key | quote }}"
  when: job.key not in current_jobs_list.stdout_lines

- name: Upload job config template
  template:
    src: "{{ item }}"
    # if job exists, we write directly to jobs/JOBNAME/config.xml, else we write to the tmp file.
    dest: "{{ jenkins_home + '/jobs/' + job.key + '/config.xml' }}"
    mode: 0600
    owner: jenkins
    group: jenkins
    backup: yes
    force: yes
  with_first_found:
    - "jobs/config.xml.{{ ansible_fqdn }}.{{ job.key }}.j2"
    - "jobs/config.xml.{{ job.key }}.j2"
    - "jobs/config.xml.{{ ansible_fqdn }}.j2"
    - "jobs/config.xml.j2"
  register: jobconfig

- name: Reload the job
  shell: "{{ jenkins_cli_command }} reload-job {{ job.key | quote }}"
  when: jobconfig.changed