Home > Enterprise >  How can I check an URL with uri module and loop?
How can I check an URL with uri module and loop?

Time:12-02

I'm trying to check URL's with the uri module and a loop of course because I have more than one URL.

---
- name: check URLs with a loop
  hosts: localhost
  connection: local
  gather_facts: no
  vars:
    url:
      - https://www.google.com
      - https://example.com
      - https://www.wikipedia.org

 tasks:
   - name: test url
     uri:
       url: "{{ item }}"
     loop:
      - "{{ url }}"

CodePudding user response:

You may have a look into the following minimal example.

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Check that a page returns a status 200
    uri:
      url: "{{ item }}"
      return_content: yes
    register: this
    loop:
      - http://www.example.com
      - http://www.example.org

  - name: Show content with loop
    debug:
      msg: "{{ item.content }}"
    loop_control:
      label: "{{ item.url }}"
    loop: "{{ this.results }}"

resulting into an output of

TASK [Check that a page returns a status 200] *****
ok: [localhost] => (item=http://www.example.com)
ok: [localhost] => (item=http://www.example.org)

TASK [Show content with loop] *********************
ok: [localhost] => (item=http://www.example.com) =>
  msg: |-
    <!doctype html>
    ...
ok: [localhost] => (item=http://www.example.org) =>
  msg: |-
    <!doctype html>
    ...

As you see can from the debug task the data structure of the result set changed in compare to the former given example. Therefore it is recommend to get familiar with it by using additional tasks like

- name: Show var
    debug:
      var: this.results

  - name: Show content with filter
    debug:
      msg: "{{ this.results | map(attribute='content') }}"

Further Documentation

  • Related