Ansible 如何访问结果字典

Ansible how to acces results dictionary

我正在打开一个 playbook 来更新 centos 中的补丁,但首先我需要验证是否有更新的包,以防任务没有停止。

我正在使用 yum 插件来验证是否有更新,但是当尝试通过调试使任务失败以防没有更新时,它不允许我验证并且总是提供 skyp。

剧本。

---
- hosts: "{{ hosts}}"
  become: true
  tasks:
  - name: check updates
    yum:
      list: updates
      update_cache: true
    register: salida

  - name: show yum
    debug:
      msg: "{{ salida }}"
    when: '"yumstate" in salida.results'
...


Output

TASK [Gathering Facts] *********************************************************************************************************************
ok: []

TASK [check updates] **********************************************************************************************************************
ok: []

TASK [show yum] ************************************************************************************************************
skipping: []

输出变量

"msg": [
    {
        "arch": "x86_64",
        "envra": "0:",
        "epoch": "0",
        "name": "",
        "release": "3770.el7",
        "repo": "",
        "version": "20.0.0",
        "yumstate": "available"
    },
    {
        "arch": "x86_64",
        "envra": "0:",
        "epoch": "0",
        "name": "syslog-ng-premium-edition-compact",
        "release": "1.rhel7",
        "repo": "",
        "version": "7.0.29",
        "yumstate": "available"
    }
]

}

比如统计可用包的个数,有则执行任务

    - debug:
        msg: "There are {{ pkg_available }} packages available."
      vars:
        pkg_available: "{{ salida.results|
                           selectattr('yumstate', 'eq', 'available')|
                           length }}"
      when: pkg_available|int > 0

这在 --check 模式下也能正常工作。