Conventions, tips, and pitfalls<span id="developing_modules_best_practices"></span>


目录

Topics

As you design and develop modules, follow these basic conventions and tips for clean, usable code:

Scoping your module(s)

Especially if you want to contribute your module(s) to an existing Ansible Collection, make sure each module includes enough logic and functionality, but not too much. If these guidelines seem confusing, consider whether you really need to write a module <module_dev_should_you> at all.

Designing module interfaces

General guidelines & tips

Functions and Methods

Python tips

if __name__ == '__main__':
    main()

Importing and using shared code

import traceback

from ansible.module_utils.basic import missing_required_lib

LIB_IMP_ERR = None
try:
    import foo
    HAS_LIB = True
except:
    HAS_LIB = False
    LIB_IMP_ERR = traceback.format_exc()

Then in main(), just after the argspec, do

if not HAS_LIB:
    module.fail_json(msg=missing_required_lib("foo"),
                     exception=LIB_IMP_ERR)

And document the dependency in the requirements section of your module's documentation_block.

Handling module failures

When your module fails, help users understand what went wrong. If you are using the AnsibleModule common Python code, the failed element will be included for you automatically when you call fail_json. For polite module failure behavior:

Handling exceptions (bugs) gracefully

Creating correct and informative module output

Modules must output valid JSON only. Follow these guidelines for creating correct, useful module output:

If a module returns stderr or otherwise fails to produce valid JSON, the actual output will still be shown in Ansible, but the command will not succeed.

Following Ansible conventions

Ansible conventions offer a predictable user interface across all modules, playbooks, and roles. To follow Ansible conventions in your module development:

Module Security


版本号 #2
由 壳壳虫 创建于 2026-10-31 14:34:21 UTC
由 壳壳虫 更新于 2026-10-31 14:34:22 UTC