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

如何根据ansible中的子字符串列表在var匹配中进行测试?,ansible,jinja2,ansible-2.x,Ansible,Jinja2,Ansible 2.x,我是ansible的新手,我正在尝试确定如何根据子字符串列表测试传递给playbook比赛的变量 我试过下面的方法。循环遍历我的BADCMD列表,然后测试它是否在传递的变量中 vars: badcmds: - clear - no tasks: - name: validate input debug: msg: " {{ item }}" when: item in my_command with_items: "

我是ansible的新手,我正在尝试确定如何根据子字符串列表测试传递给playbook比赛的变量

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

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
会自动转换为boolean
false
。你应该使用“否”来让ANTIVE把变量看作字符串。不加引号:

---
- 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 }}"

希望对您有所帮助

您的剧本中的一个问题是,
-no
会自动转换为boolean
false
。你应该使用“否”来让ANTIVE把变量看作字符串。不加引号:

---
- 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 }}"
希望能有帮助