這個ansible劇本有效
---
- hosts: localhost
gather_facts: False
vars:
jq: "[?contains(name, 'Pizza')]"
json: |
[{
"name": "Ted's Sub Shop - 720895714701",
"templateid": "24632"
},
{
"name": "Ted's Pizza - 720895714702",
"templateid": "24663"
}]
tasks:
- name: DEBUG
debug:
msg: "{{ json | from_json | json_query(jq) }}"
它回傳以下內容
ok: [localhost] => {
"msg": [
{
"name": "Ted's Pizza - 720895714702",
"templateid": "24663"
}
]
}
我需要更進一步,當namecontains的值時,Pizza我需要它只回傳最后的 12 位數字。所以回傳輸出看起來像這樣
ok: [localhost] => {
"msg": "720895714702"
}
想法?
uj5u.com熱心網友回復:
你可以試試
- name: testplaybook jinja2
hosts: localhost
gather_facts: no
vars:
json: |
[{
"name": "Ted's Sub Shop - 720895714701",
"templateid": "24632"
},
{
"name": "Ted's Pizza - 720895714702",
"templateid": "24663"
}]
tasks:
- name: DEBUG
debug:
msg: "{{ json | from_json | selectattr('name', 'contains' , 'Pizza')
| map(attribute='name')
| map('regex_replace', '^.*?(\\d*)$', '\\1')}}"
結果:
ok: [localhost] => {
"msg": [
"720895714702"
]
}
uj5u.com熱心網友回復:
添加屬性可能更有效。例如下面的宣告
json_id: "{{ json|zip(id_hash)|map('combine')|list }}"
id_hash: "{{ id_list|
map('community.general.dict_kv', 'id')|list }}"
id_list: "{{ json|
map(attribute='name')|
map('split', '-')|
map('last')|
map('int')|list }}"
擴展到
json_id:
- id: 720895714701
name: Ted's Sub Shop - 720895714701
templateid: '24632'
- id: 720895714702
name: Ted's Pizza - 720895714702
templateid: '24663'
然后,使用是微不足道的。例如
- debug:
msg: "{{ json_id|
selectattr('name', 'contains' , 'Pizza')|
map(attribute='id')|list }}"
給
msg:
- 720895714702
同樣的結果也給出了下面的json_query
- debug:
msg: "{{ json_id|
json_query('[?contains(name, `Pizza`)].id') }}"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/467322.html
