首页 > 解决方案 > Ansible:regex_search 过滤器比较以及如何调试 when 子句

问题描述

我今天花了一些时间尝试编写一些 Ansible 脚本,以便仅在相关命令输出中不存在相应行时才运行命令。经过一番反复试验,我得到了一些对我有用的东西,但我不清楚为什么我与空字符串的初始比较不起作用。

这是一个展示我的问题的剧本:

- name: test
  hosts: localhost
  tasks:
  - shell: "cat /tmp/cmdoutput"
    register: cmdoutput

  - debug: var=filtered_output
    vars:
      filtered_output: "{{ cmdoutput.stdout | regex_search(item) }}"
    with_items:
      - "aa .* xx"
      - "bb .* yy"

  - debug: msg="do action that inserts {{ item }}"
    with_items:
      - "aa .* xx"
      - "bb .* yy"
    when: cmdoutput.stdout | regex_search(item) == ""

  - debug: msg="do action that inserts {{ item }}"
    with_items:
      - "aa .* xx"
      - "bb .* yy"
    when: not cmdoutput.stdout | regex_search(item)
cat /tmp/cmdoutput
aa b c d xx
aa f g h yy
bb i j k xx

这将产生以下输出:

$ ansible-playbook test.yml 
 [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'


PLAY [test] **********************************************************************************************************************

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

TASK [shell] *********************************************************************************************************************
changed: [localhost]

TASK [debug] *********************************************************************************************************************
ok: [localhost] => (item=None) => {
    "filtered_output": "aa b c d xx"
}
ok: [localhost] => (item=None) => {
    "filtered_output": ""
}

TASK [debug] *********************************************************************************************************************
skipping: [localhost] => (item=None) 
skipping: [localhost] => (item=None) 

TASK [debug] *********************************************************************************************************************
skipping: [localhost] => (item=None) 
ok: [localhost] => (item=None) => {
    "msg": "do action that inserts bb .* yy"
}

PLAY RECAP ***********************************************************************************************************************
localhost                  : ok=4    changed=1    unreachable=0    failed=0   

"filtered_output": "",但以下比较不匹配时。

所以我的问题是:

我的 Ansible 版本:2.5.1

谢谢

标签: ansible

解决方案


回答你的问题

为什么条件匹配“”时第二次调试不?

当没有“ NoneType ”类型的正则表达式匹配对象时返回。这种类型没有长度。而不是测试空字符串(题外话见E602

when: cmdoutput.stdout|regex_search(item) == ""

使用(你的例子中已经有了它)。

when: not cmdoutput.stdout|regex_search(item)

推荐阅读