3

The Ansible module development documentation states:

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

from ansible.module_utils.basic import *
main()

This contradicts the usual practice of grouping imports at the top of the file. Using import * also prevents lint tools (e.g. flake8) from working effectively, and is generally regarded as bad practice.

Is there any reason to import in this way, or is Ansible just making their own style recommendation here?

augurar
  • 12,081
  • 6
  • 50
  • 65

1 Answers1

2

NOTE: The below answer no longer pertains to Ansible 2.1+. From the comments:

I realize this is an old post but should anyone still be interested, it's worth noting that this is not true anymore since ansible 2.1. Taken from 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

Original Answer

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 is.

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.

slm
  • 15,396
  • 12
  • 109
  • 124
quodlibetor
  • 8,185
  • 4
  • 35
  • 48
  • 1
    @augurar I realize this is an old post but should anyone still be interested, it's worth noting that this is not true anymore since ansible 2.1. Taken from [here](https://docs.ansible.com/ansible/dev_guide/developing_modules.html) : 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 Jan 10 '17 at 19:19