【问题标题】:Get item value in a loop with failed tasks in Ansible在 Ansible 中使用失败的任务循环获取项目值
【发布时间】:2018-01-16 09:11:59
【问题描述】:

我尝试使用 Ansible 执行一件有趣的事情,但出现了问题。

例子:

  1. 一个文本文件包含一些主机的 IP 地址。
  2. 我需要读取文件中的每一行并检查是否为每个 IP 地址打开了 SSH 端口。
  3. 如果我在检查主机端口时遇到超时,那么我应该知道哪个 IP 地址似乎有问题,并将此项传递给变量以执行额外的检查。

文件内容:

1.1.1.1
1.1.1.2
1.1.1.2

Ansible 剧本:

- hosts: localhost
  connection: local
  gather_facts: no
  tasks:
  - name: Get list of IP adresses
    shell: cat /home/file
    register: ip_addrs
  - name: Check SSH port
    wait_for:
      host: "{{ item }}"
      port: 22
      timeout: 5
    with_items: "{{ ip_addrs.stdout_lines }}"
    ignore_errors: true

我的剧本以结果结束:

ok - 1.1.1.1
ok - 1.1.1.2
timeout - 1.1.1.3

循环的结果包括一个回复中每个任务的结果。 我的问题:如何在导致我的任务失败的循环中提取项目的值?

类似于register: result 用于循环中的任务和用于项目when: result|failed 的一些命令。

【问题讨论】:

    标签: loops ansible


    【解决方案1】:

    注册循环任务的结果并检查每个项目的子结果,如下所示:

      - name: Check SSH port
        wait_for:
          host: "{{ item }}"
          port: 22
          timeout: 5
        with_items: "{{ ip_addrs.stdout_lines }}"
        ignore_errors: true
        register: loop_res
      - debug:
          msg: bad host
        when: item is failed
        with_items: "{{ loop_res.results }}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 2022-01-22
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      相关资源
      最近更新 更多