【问题标题】:How can I check an URL with uri module and loop?如何使用 uri 模块和循环检查 URL?
【发布时间】:2022-12-20 04:52:29
【问题描述】:

我正在尝试使用 uri 模块检查 URL,当然还有一个循环,因为我有多个 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 }}"

【问题讨论】:

  • 由于这似乎只是对您正在尝试做的事情的描述,您能否更详细地描述问题是什么,或者您正在观察哪些问题或错误?

标签: loops ansible uri


【解决方案1】:

您可以查看以下最小示例。

---
- 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 }}"

导致输出

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>
    ...

如您所见,debug 任务结果集的数据结构与former given example 相比发生了变化。因此,建议通过使用其他任务来熟悉它,例如

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

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

进一步的文件

【讨论】:

    猜你喜欢
    • 2022-12-01
    • 1970-01-01
    • 2019-10-21
    • 2022-11-18
    • 2023-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    相关资源
    最近更新 更多