如何在 var 匹配中测试 ansible 中的子字符串列表?

How do I test in a var matches against a list of substrings in ansible?

我是 ansible 的新手,我正在尝试确定如何测试传递给我的剧本的变量是否与子字符串列表相匹配。

我试过类似下面的方法。遍历我的 badcmds 列表,然后测试它是否在传递的变量中。

vars:
    badcmds:
     - clear
     - no

  tasks:


  - name: validate input
    debug:
       msg: " {{ item }}"
    when: item in my_command
    with_items: "{{ badcmds }}"

我收到以下错误:

  "msg": "The conditional check 'item in my_command' failed. 
  The error was: Unexpected templating type error occurred on
 ({% if item in my_command %} True {% else %} False {% endif %}):  
 coercing to Unicode: need string or buffer, bool found

非常感谢。

您的剧本的一个问题是 - no 会自动转换为布尔值 false。您应该使用 "no" 让 Ansible 将变量视为字符串。没有引号:

---
- hosts: localhost
  connection: local
  gather_facts: false
  vars:
    badcmds:
     - clear
     - no
    my_command: clear

  tasks:
  - name: print variable
    debug:
      msg: "{{ item }}"
    with_items: 
      - "{{ badcmds }}"

输出:

TASK [print variable] ***********************************************************************************************************************************************************************************************
ok: [localhost] => (item=None) => {
    "msg": "clear"
}
ok: [localhost] => (item=None) => {
    "msg": false
}

我猜你应该用引号将 no 引起来,因为这种行为不是你的本意。

要进行循环并检查变量是否与 badcmds 列表中的任何项目匹配,您可以使用:

---
- hosts: localhost
  connection: local
  gather_facts: false
  vars:
    badcmds:
     - "clear"
     - "no"

  tasks:
  - name: validate input
    debug:
      msg: "{{ item }}"
    when: item == my_command
    with_items: 
      - "{{ badcmds }}"

希望对您有所帮助