导入 Ansible 模块实用程序

Importing Ansible module utils

Ansible module development documentation 声明:

Key parts [of writing an Ansible module] include always ending the module file with:

from ansible.module_utils.basic import *
main()

这与在文件顶部对导入进行分组的通常做法相矛盾。使用 import * 还会阻止 lint 工具(例如 flake8)有效工作,并且 generally regarded as bad practice.

是否有任何理由以这种方式导入,或者 Ansible 只是在这里提出自己的风格推荐?

注意:以下答案不再适用于 Ansible 2.1+。来自评论:

我知道这是一个旧的 post 但如果有人仍然感兴趣,值得注意的是,自从 ansible 2.1 以来,这不再是真的了。摘自 here: Prior to Ansible-2.1.0, importing only what you used from ansible.module_utils.basic did not work. You needed to use a wildcard import - bouletta

原答案

Ansible(prior to version 2.1) will refuse to run if you don't do the import * business. I'm not 100% certain what magic is being done, but I know some 是。

The Replacer is used to insert chunks of code into modules before transfer. Rather than doing classical python imports, this allows for more efficient transfer in a no-bootstrapping scenario by not moving extra files over the wire, and also takes care of embedding arguments in the transferred modules.

This version is done in such a way that local imports can still be used in the module code, so IDEs don't have to be aware of what is going on.

Example:

from ansible.module_utils.basic import * 

... will result in the insertion basic.py into the module from the module_utils/ directory in the source tree.

All modules are required to import at least basic, though there will also be other snippets.