构建自定义模块 Ansible

Building custom module Ansible

我正在尝试为我们的私有云基础架构构建自定义模块。

我关注了这个文档http://docs.ansible.com/ansible/latest/dev_guide/developing_modules_general.html

我创建了一个 my_module.py 模块文件。

当我打ansible-playbook playbook/my_module.yml

响应:

PLAY [Create, Update, Delete VM] *********************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************************
ok: [localhost]

TASK [VM create] *************************************************************************************************************************
changed: [localhost]

TASK [dump test output] ***********************************************************************************************************************
ok: [localhost] => {
    "msg": {
        "changed": true,
        "failed": false,
        "message": "goodbye",
        "original_message": "pcp_vm_ansible"
    }
}

PLAY RECAP ************************************************************************************************************************************
localhost                  : ok=3    changed=1    unreachable=0    failed=0  

这意味着它按预期正常工作

Module.py

from ansible.module_utils.basic import AnsibleModule

def run_module():

    module_args = dict(
        name=dict(type='str', required=True),
        new=dict(type='bool', required=False, default=False)
    )


    result = dict(
        changed=False,
        original_message='',
        message=''
    )

    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=True
    )
    if module.check_mode:
        return result
    result['original_message'] = module.params['name']
    result['message'] = 'goodbye'
    if module.params['new']:
        result['changed'] = True
    if module.params['name'] == 'fail me':
        module.fail_json(msg='You requested this to fail', **result)


    module.exit_json(**result)

def main():
    print("================== Main Called =======================") 
    run_module()

if __name__ == '__main__':
    main()

我正在尝试使用 print() 甚至 logging 来打印日志以可视化我的输入数据。

print("================== Main Called =======================")

但是没有任何内容被打印到控制台

根据Conventions, Best Practices, and Pitfalls、"Modules must output valid JSON only. The top level return type must be a hash (dictionary) although they can be nested. Lists or simple scalar values are not supported, though they can be trivially contained inside a dictionary."

实际上,核心运行时仅通过 JSON 与模块通信,并且核心运行时控制标准输出,因此来自模块的标准打印语句被抑制。如果您想要或需要有关执行运行时的更多信息,那么我建议使用 Callback Plugin.