前几天我发现在循环中使用寄存器变量时,就像这样
- name: Generate pw's for users
command: "/some_path/generate_hashed_pw.sh -u {{ item }}"
register: hashed_pws
with_items:
- joe
- sally
- john
hashed_pws寄存器是一个包含结果[]键的哈希,这是一个哈希数组,如此
{
"hashed_pws" : {
"changed" : true,
"some_other_key" : "some_other_value",
"results" : [
{
"item" : "joe",
"stdout": "joes_hashed_pw",
"some_other_key" : "some_other_value"
},
{
"item" : "sally",
"stdout": "sallys_hashed_pw",
"some_other_key" : "some_other_value"
},
{
"item" : "john",
"stdout": "johns_hashed_pw",
"some_other_key" : "some_other_value"
}
]
}
}
那么直接访问的语法是什么," stdout"数组中每个哈希元素的元素?换句话说,我想:
- debug: msg="Sallys hashed pw is {{ hashed_pws.results[SOME_KEY_TO_DIRECTLY_GET_SALLYS_STDOUT_VALUE] }}"
这可能是一个蟒蛇问题,因为它是一个Ansible问题。
答案 0 :(得分:0)
如果您知道自己想要哪一个,那么获得一个很容易:
print(hashed_pws['results'][1]['stdout'])
但如果你想要所有这些,我就不会很清楚地知道你能做多少循环。你能使用列表推导吗?
print([x['stdout'] for x in hashed_pws['results']])
根据您的答案编辑:
print([x['stdout'] for x in hashed_pws['results'] if x['item'] == "sally"])
答案 1 :(得分:0)
你只需要像这样循环结果:
- debug: msg="{{item.item}}'s hashed pw is {{item.stdout}}"
with_items: "{{hashed_pws.results}}"
输出如下:
TASK [debug]
*******************************************************************
ok: [localhost] => (item={'some_other_key': 'some_other_value', 'stdout': 'joes_hashed_pw', 'item': 'joe'}) => {
"item": {
"item": "joe",
"some_other_key": "some_other_value",
"stdout": "joes_hashed_pw"
},
"msg": "joe's hashed pw is joes_hashed_pw"
}
ok: [localhost] => (item={'some_other_key': 'some_other_value', 'stdout': 'sallys_hashed_pw', 'item': 'sally'}) => {
"item": {
"item": "sally",
"some_other_key": "some_other_value",
"stdout": "sallys_hashed_pw"
},
"msg": "sally's hashed pw is sallys_hashed_pw"
}
ok: [localhost] => (item={'some_other_key': 'some_other_value', 'stdout': 'johns_hashed_pw', 'item': 'john'}) => {
"item": {
"item": "john",
"some_other_key": "some_other_value",
"stdout": "johns_hashed_pw"
},
"msg": "john's hashed pw is johns_hashed_pw"
}