Search code examples
ansibleansible-tower

Iterating through Ansible Tower APIs with multiple pages


I need to take all related jobs for a job template. API can only return up to 200 results per page.
Has anyone handled API pagination with the URI module?
How can I simply iterate over the number of pages with a variable named page_number?

below my code:

- name: List related jobs for job template
  uri:
    url: http://localhost{{ api_for_job_template.json.related.jobs }}?page_size=200&page={{ page_number }}
    force_basic_auth: yes
    user: "{{ user }}"
    password: "{{ password }}"
    body_format: json
  register: jobs_info

Solution

  • Ok, I found a way how to get all pages. In one task I'm taking count of jobs from API and dividing it by number of records returned per page. Next in uri iterate page by page with "with_sequence". Just needed to round up it and convert to int.

    - name: List related jobs for job template
      uri:
        url: http://localhost{{ api_for_job_template.json.related.jobs }}?page_size={{ page_size }}&page={{ item }}
        force_basic_auth: yes
        user: "{{ user }}"
        password: "{{ password }}"
        body_format: json
      register: jobs_info
      with_sequence: start=1 end="{{ end_at }}"
      vars:
        - end_at: "{{ ((jobs_count.json.count / 20) | round(0,'ceil')) | int }}"