自定义Ansible模块中exit_json()函数消息未显示问题排查
自定义Ansible模块exit_json返回结果不显示问题排查
开发自定义Ansible模块时,发现模块中exit_json()函数返回的自定义结果未在默认执行输出中显示。以下是相关代码、Playbook、执行结果及版本信息,以及对应的排查和解决方法:
模块代码(library/test_out_module.py)
from ansible.module_utils.basic import AnsibleModule def main(): module = AnsibleModule( argument_spec=dict( some_var=dict(required=True, type='raw'), ) ) some_var = module.params['some_var'] result = {} result['result_data'] = some_var result['result'] = 'goodbye' result['changed'] = True module.exit_json(**result) if __name__ == '__main__': main()
Playbook代码
--- - hosts: localhost gather_facts: no tasks: - name: test out module test_out_module: some_var: asdad
执行结果
constantine@MacBook-Pro-Constantine ~/work/tapentertainment/ansible $ ./ansible-playbook playbooks/dev-devel.yml PLAY [localhost] ********************************************************************************************************************************************************************************************************************************************************************* TASK [test out module] *************************************************************************************************************************************************************************************************************************************************************** changed: [localhost] PLAY RECAP *************************************************************************************************************************************************************************************************************************************************************************** localhost : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
版本信息
ansible [core 2.16.3] python version = 3.12.1 (main, Dec 7 2023, 20:45:44) [Clang 15.0.0 (clang-1500.0.40.1)] jinja version = 3.1.3 libyaml = True
问题原因
Ansible默认输出级别仅展示任务的执行状态(如changed/ok/failed等),不会显示模块通过exit_json()返回的自定义结果数据。
解决办法
1. 提升输出详细级别
执行Playbook时添加-v(详细)、-vv(更详细)或-vvv(调试级)参数,即可查看模块返回的完整结果:
./ansible-playbook playbooks/dev-devel.yml -v
执行后会在任务输出中显示result_data、result等自定义字段内容。
2. 注册结果并通过debug模块打印
修改Playbook,将模块执行结果注册到变量,再用debug模块输出:
--- - hosts: localhost gather_facts: no tasks: - name: test out module test_out_module: some_var: asdad register: module_result - name: 打印模块返回结果 debug: var: module_result
执行后,debug任务会完整输出模块返回的所有数据。
3. 添加msg字段(可选)
如果希望自定义消息在默认输出中直接显示,可以在返回结果里加入msg字段,Ansible会自动在任务行展示该内容:
# 模块中修改result部分 result = {} result['result_data'] = some_var result['result'] = 'goodbye' result['changed'] = True result['msg'] = '模块执行完成,返回结果:goodbye' # 新增msg字段 module.exit_json(**result)
修改后,无需添加详细参数,执行时任务输出会显示类似:changed: [localhost] => {"msg": "模块执行完成,返回结果:goodbye"}的内容。
内容的提问来源于stack exchange,提问作者Constantine Volodin
相关产品推荐
相关产品推荐

