您的with_items 缺少扩展:
- name: iterate items
debug:
msg: "{{ item.name }}"
with_items: DEVICE_RESULT.msg_output
应该是:
- name: iterate items
debug:
msg: "{{ item.name }}"
with_items: "{{ DEVICE_RESULT.msg_output }}"
以下是使用 Python 3.6.4 和 Ansible 2.6.0 的工作示例:
play.yml
---
- hosts: localhost
tasks:
- name: build dictionary of system ips
custommod:
register: DEVICE_RESULT
- debug:
var: DEVICE_RESULT
- name: iterate items
debug:
msg: "{{ item.name }}" # You need double quotes here
with_items: "{{ DEVICE_RESULT.msg }}" # And double quotes here
库/custommod.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
from ansible.module_utils.basic import *
def main():
module = AnsibleModule({})
l = [
{ 'name': 'TEST1_HOST', 'ip_addr': '1.1.1.1' },
{ 'name': 'TEST2_HOST', 'ip_addr': '1.1.1.2' },
]
module.exit_json(changed=True, msg=l)
if __name__ == '__main__':
main()
输出
ansible-playbook play.yml
[WARNING]: Unable to parse /etc/ansible/hosts as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
PLAY [localhost] *******************************************************************************************************************************************************************
TASK [Gathering Facts] *************************************************************************************************************************************************************
ok: [localhost]
TASK [build ditionary of system ip's] **********************************************************************************************************************************************
changed: [localhost]
TASK [debug] ***********************************************************************************************************************************************************************
ok: [localhost] => {
"DEVICE_RESULT": {
"changed": true,
"failed": false,
"msg": [
{
"ip_addr": "1.1.1.1",
"name": "TEST1_HOST"
},
{
"ip_addr": "1.1.1.2",
"name": "TEST2_HOST"
}
]
}
}
TASK [iterate items] ***************************************************************************************************************************************************************
ok: [localhost] => (item={'name': 'TEST1_HOST', 'ip_addr': '1.1.1.1'}) => {
"msg": "TEST1_HOST"
}
ok: [localhost] => (item={'name': 'TEST2_HOST', 'ip_addr': '1.1.1.2'}) => {
"msg": "TEST2_HOST"
}
PLAY RECAP *************************************************************************************************************************************************************************
localhost : ok=4 changed=1 unreachable=0 failed=0