In Ansible, how do I check if a value is in one of

2019-03-06 13:31发布

问题:

I set a register variable that ultimately has this value:

ok: [10.xx.xx.xx] => {
    "yum_sec_upd.stdout_lines": [
        "Loaded plugins: fastestmirror", 
        "Loading mirror speeds from cached hostfile", 
        " * base: mirrors.usinternet.com", 
        " * epel: mirror.steadfast.net", 
        " * extras: mirror.lax.hugeserver.com", 
        " * updates: centos.mirrors.tds.net", 
        "CESA_2017__0086 Important/Sec. kernel-3.10.0-514.6.1.el7.x86_64", 
        "CESA_2017__0086 Important/Sec. kernel-tools-3.10.0-514.6.1.el7.x86_64", 
        "CESA_2017__0086 Important/Sec. kernel-tools-libs-3.10.0-514.6.1.el7.x86_64", 
        "CESA_2017__0086 Important/Sec. python-perf-3.10.0-514.6.1.el7.x86_64", 
        "updateinfo list done"
    ]
}

How do I check if the string "Sec." is present in the yum_sec_upd.stdout_lines array of strings? I want to do this

- name: Send mail for security updates
  mail: # mail parms here
  when: "'Sec.' in yum_sec_upd.stdout_lines[]"

回答1:

If you are registering the output of a command, just use stdout instead of stdout_lines:

- name: Send mail for security updates
  mail: # mail parms here
  when: 'Sec.' in yum_sec_upd.stdout

To check if a list contains a substring, you could use for example:

when: yum_sec_upd.stdout_lines | select('search', 'Sec.') | list | length > 0


标签: ansible