我有以下复杂的字典(这只是一个例子)。我试图抓取一个属于服务器1的所有ID的列表。我尝试了jinja2的过滤器,如match, search, equalto,但都没有返回预期的结果。我也试过JSON查询,但还是不知道如何将小写或大写的比较工作。
---
- name: TEST
hosts: localhost
gather_facts: no
vars:
datacenters: {
cabinets: {
servers: [
{
name: Server1,
id: 1
},
{
name: SERVER1,
id: 2
},
{
name: Server2,
id: 3
},
{
name: server1,
id: 4
},
]
}
}
tasks:
- name: get ids for Server 1
set_fact:
ids: "{{ datacenters.cabinets.servers
| selectattr('name','match','Server1')
| map(attribute='id')
| list }}"
- debug:
var: ids
- debug: msg="{{ datacenters | json_query(\"cabinets.servers[?name == 'Server1'].id\") }}"
这可以用when和 lower
过滤器的ansible。下面的玩法对我来说是可行的。
剧本。
- name: Demo of restore plan
hosts: localhost
gather_facts: False
vars:
datacenters: {
cabinets: {
servers: [
{
name: Server1,
id: 1
},
{
name: SERVER1,
id: 2
},
{
name: Server2,
id: 3
},
{
name: server1,
id: 4
},
]
}
}
tasks:
- debug:
msg: "{{ item.name }}"
with_items:
- "{{ datacenters.cabinets.servers }}"
when: item.name|lower == "server1"
输出:
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
PLAY [Demo of restore plan] ************************************************************************************************************************************************
TASK [debug] ***************************************************************************************************************************************************************
ok: [localhost] => (item={'name': 'Server1', 'id': 1}) => {
"msg": "Server1"
}
ok: [localhost] => (item={'name': 'SERVER1', 'id': 2}) => {
"msg": "SERVER1"
}
skipping: [localhost] => (item={'name': 'Server2', 'id': 3})
ok: [localhost] => (item={'name': 'server1', 'id': 4}) => {
"msg": "server1"
}
PLAY RECAP *****************************************************************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Ansible只列出server1行,忽略server2行。
希望能帮到你