Ansible module development: getting started

A module is a reusable, standalone script that Ansible runs on your behalf, either locally or remotely. Modules interact with your local machine, an API, or a remote system to perform specific tasks like changing a database password or spinning up a cloud instance. Each module can be used by the Ansible API, or by the ansible or ansible-playbook programs. A module provides a defined interface, accepting arguments and returning information to Ansible by printing a JSON string to stdout before exiting. Ansible ships with thousands of modules, and you can easily write your own. If you’re writing a module for local use, you can choose any programming language and follow your own rules. This tutorial illustrates how to get started developing an Ansible module in Python.

Environment setup

Prerequisites via apt (Ubuntu)

Due to dependencies (for example ansible -> paramiko -> pynacl -> libffi):

  1. sudo apt update
  2. sudo apt install build-essential libssl-dev libffi-dev python-dev

Common environment setup

  • Clone the Ansible repository:$ git clone https://github.com/ansible/ansible.git
  • Change directory into the repository root dir: $ cd ansible
  • Create a virtual environment: $ python3 -m venv venv (or forPython 2 $ virtualenv venv. Note, this requires you to installthe virtualenv package: $ pip install virtualenv)
  • Activate the virtual environment: $ . venv/bin/activate
  • Install development requirements:$ pip install -r requirements.txt
  • Run the environment setup script for each new dev shell process:$ . hacking/env-setup

Note

After the initial setup above, every time you are ready to startdeveloping Ansible you should be able to just run the following from theroot of the Ansible repo:$ . venv/bin/activate && . hacking/env-setup

Starting a new module

To create a new module:

  • Navigate to the correct directory for your new module: $ cd lib/ansible/modules/cloud/azure/
  • Create your new module file: $ touch my_new_test_module.py
  • Paste the content below into your new module file. It includes the required Ansible format and documentation and some example code.
  • Modify and extend the code to do what you want your new module to do. See the programming tips and Python 3 compatibility pages for pointers on writing clean, concise module code.
  1. #!/usr/bin/python
  2.  
  3. # Copyright: (c) 2018, Terry Jones <[email protected]>
  4. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
  5.  
  6. ANSIBLE_METADATA = {
  7. 'metadata_version': '1.1',
  8. 'status': ['preview'],
  9. 'supported_by': 'community'
  10. }
  11.  
  12. DOCUMENTATION = '''
  13. ---
  14. module: my_sample_module
  15.  
  16. short_description: This is my sample module
  17.  
  18. version_added: "2.4"
  19.  
  20. description:
  21. - "This is my longer description explaining my sample module"
  22.  
  23. options:
  24. name:
  25. description:
  26. - This is the message to send to the sample module
  27. required: true
  28. new:
  29. description:
  30. - Control to demo if the result of this module is changed or not
  31. required: false
  32.  
  33. extends_documentation_fragment:
  34. - azure
  35.  
  36. author:
  37. - Your Name (@yourhandle)
  38. '''
  39.  
  40. EXAMPLES = '''
  41. # Pass in a message
  42. - name: Test with a message
  43. my_new_test_module:
  44. name: hello world
  45.  
  46. # pass in a message and have changed true
  47. - name: Test with a message and changed output
  48. my_new_test_module:
  49. name: hello world
  50. new: true
  51.  
  52. # fail the module
  53. - name: Test failure of the module
  54. my_new_test_module:
  55. name: fail me
  56. '''
  57.  
  58. RETURN = '''
  59. original_message:
  60. description: The original name param that was passed in
  61. type: str
  62. message:
  63. description: The output message that the sample module generates
  64. '''
  65.  
  66. from ansible.module_utils.basic import AnsibleModule
  67.  
  68. def run_module():
  69. # define available arguments/parameters a user can pass to the module
  70. module_args = dict(
  71. name=dict(type='str', required=True),
  72. new=dict(type='bool', required=False, default=False)
  73. )
  74.  
  75. # seed the result dict in the object
  76. # we primarily care about changed and state
  77. # change is if this module effectively modified the target
  78. # state will include any data that you want your module to pass back
  79. # for consumption, for example, in a subsequent task
  80. result = dict(
  81. changed=False,
  82. original_message='',
  83. message=''
  84. )
  85.  
  86. # the AnsibleModule object will be our abstraction working with Ansible
  87. # this includes instantiation, a couple of common attr would be the
  88. # args/params passed to the execution, as well as if the module
  89. # supports check mode
  90. module = AnsibleModule(
  91. argument_spec=module_args,
  92. supports_check_mode=True
  93. )
  94.  
  95. # if the user is working with this module in only check mode we do not
  96. # want to make any changes to the environment, just return the current
  97. # state with no modifications
  98. if module.check_mode:
  99. return result
  100.  
  101. # manipulate or modify the state as needed (this is going to be the
  102. # part where your module will do what it needs to do)
  103. result['original_message'] = module.params['name']
  104. result['message'] = 'goodbye'
  105.  
  106. # use whatever logic you need to determine whether or not this module
  107. # made any modifications to your target
  108. if module.params['new']:
  109. result['changed'] = True
  110.  
  111. # during the execution of the module, if there is an exception or a
  112. # conditional state that effectively causes a failure, run
  113. # AnsibleModule.fail_json() to pass in the message and the result
  114. if module.params['name'] == 'fail me':
  115. module.fail_json(msg='You requested this to fail', **result)
  116.  
  117. # in the event of a successful module execution, you will want to
  118. # simple AnsibleModule.exit_json(), passing the key/value results
  119. module.exit_json(**result)
  120.  
  121. def main():
  122. run_module()
  123.  
  124. if __name__ == '__main__':
  125. main()

Exercising your module code

Once you’ve modified the sample code above to do what you want, you can try out your module.Our debugging tips will help if you run into bugs as you exercise your module code.

Exercising module code locally

If you module does not need to target a remote host, you can quickly and easily exercise you code locally like this:

  • Create an arguments file, a basic JSON config file that passes parameters to your module so you can run it. Name the arguments file /tmp/args.json and add the following content:
  1. {
  2. "ANSIBLE_MODULE_ARGS": {
  3. "name": "hello",
  4. "new": true
  5. }
  6. }
  • If you are using a virtual environment (highly recommended fordevelopment) activate it: $ . venv/bin/activate
  • Setup the environment for development: $ . hacking/env-setup
  • Run your test module locally and directly:$ python ./my_new_test_module.py /tmp/args.json

This should return output something like this:

  1. {"changed": true, "state": {"original_message": "hello", "new_message": "goodbye"}, "invocation": {"module_args": {"name": "hello", "new": true}}}

Exercising module code in a playbook

The next step in testing your new module is to consume it with an Ansible playbook.

  • Create a playbook in any directory: $ touch testmod.yml

  • Add the following to the new playbook file:

  1. - name: test my new module
  2. hosts: localhost
  3. tasks:
  4. - name: run the new module
  5. my_new_test_module:
  6. name: 'hello'
  7. new: true
  8. register: testout
  9. - name: dump test output
  10. debug:
  11. msg: '{{ testout }}'
  • Run the playbook and analyze the output: $ ansible-playbook ./testmod.yml

Testing basics

These two examples will get you started with testing your module code. Please review our testing section for more detailedinformation, including instructions for testing module documentation, adding integration tests, and more.

Sanity tests

You can run through Ansible’s sanity checks in a container:

$ ansible-test sanity -v —docker —python 2.7 MODULE_NAME

Note that this example requires Docker to be installed and running. If you’d rather not use acontainer for this, you can choose to use —tox instead of —docker.

Unit tests

You can add unit tests for your module in ./test/units/modules. You must first setup your testing environment. In this example, we’re using Python 3.5.

  • Install the requirements (outside of your virtual environment): $ pip3 install -r ./test/runner/requirements/units.txt
  • To run all tests do the following: $ ansible-test units —python 3.5 (you must run . hacking/env-setup prior to this)

Note

Ansible uses pytest for unit testing.

To run pytest against a single test module, you can do the following (provide the path to the test module appropriately):

$ pytest -r a —cov=. —cov-report=html —fulltrace —color yestest/units/modules/…/test/my_new_test_module.py

Contributing back to Ansible

If you would like to contribute to the main Ansible repositoryby adding a new feature or fixing a bug, create a forkof the Ansible repository and develop against a new featurebranch using the devel branch as a starting point.When you you have a good working code change, you cansubmit a pull request to the Ansible repository by selectingyour feature branch as a source and the Ansible devel branch asa target.

If you want to contribute your module back to the upstream Ansible repo,review our submission checklist, programming tips,and strategy for maintaining Python 2 and Python 3 compatibility, as well asinformation about testing before you open a pull request.The Community Guide covers how to open a pull request and what happens next.

Communication and development support

Join the IRC channel #ansible-devel on freenode for discussionssurrounding Ansible development.

For questions and discussions pertaining to using the Ansible product,use the #ansible channel.

Credit

Thank you to Thomas Stringer (@tstringer) for contributing sourcematerial for this topic.