Ansible 检查字典列表中是否存在值
Ansible check if value exists in dictionary list
下面是我的变量列表
hostlist:
- { name: 'host1', ip_addr: '192.168.2.31', hostgrp: 'physical_workstation' }
- { name: 'host2', ip_addr: '192.168.2.32', hostgrp: 'physical_workstation' }
- { name: 'host3', ip_addr: '192.168.2.33', hostgrp: 'virtual_machine' }
我踩在下面
- name: Conditional test
debug:
msg: "hello world"
when: hostlist|selectattr("name", "equalto", "host1")|list|length != 0
这不起作用,如下所示错误
The error was: TemplateRuntimeError: no test named 'equalto'
有升级Jinaj2的解决方案。但是有没有其他方法可以代替使用 selectattr.我不想升级 Jinja2
创建名称列表并测试名称是in列表,例如
- debug:
msg: "hello world"
loop:
- 'host1'
- 'host9'
when: item in _names
vars:
_names: "{{ hostlist|map(attribute='name')|list }}"
给予
ok: [localhost] => (item=host1) =>
msg: hello world
skipping: [localhost] => (item=host9)
只检查host1
- debug:
msg: "hello world"
when: "'host1' in _names"
vars:
_names: "{{ hostlist|map(attribute='name')|list }}"
给予
ok: [localhost] => (item=host1) =>
msg: hello world
下面是我的变量列表
hostlist:
- { name: 'host1', ip_addr: '192.168.2.31', hostgrp: 'physical_workstation' }
- { name: 'host2', ip_addr: '192.168.2.32', hostgrp: 'physical_workstation' }
- { name: 'host3', ip_addr: '192.168.2.33', hostgrp: 'virtual_machine' }
我踩在下面
- name: Conditional test
debug:
msg: "hello world"
when: hostlist|selectattr("name", "equalto", "host1")|list|length != 0
这不起作用,如下所示错误
The error was: TemplateRuntimeError: no test named 'equalto'
有升级Jinaj2的解决方案。但是有没有其他方法可以代替使用 selectattr.我不想升级 Jinja2
创建名称列表并测试名称是in列表,例如
- debug:
msg: "hello world"
loop:
- 'host1'
- 'host9'
when: item in _names
vars:
_names: "{{ hostlist|map(attribute='name')|list }}"
给予
ok: [localhost] => (item=host1) =>
msg: hello world
skipping: [localhost] => (item=host9)
只检查host1
- debug:
msg: "hello world"
when: "'host1' in _names"
vars:
_names: "{{ hostlist|map(attribute='name')|list }}"
给予
ok: [localhost] => (item=host1) =>
msg: hello world