2017-01-27 22:03:26 +00:00
.. _module_dev_tutorial_sample:
2017-07-14 02:06:01 +00:00
Ansible Module Development Walkthrough
======================================
2017-01-27 22:03:26 +00:00
2017-08-17 00:56:53 +00:00
In this section, we will walk through developing, testing, and debugging an Ansible module.
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
What's covered in this section:
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
- `Environment setup <#environment-setup> `__
- `New module development <#new-module-development> `__
- `Local/direct module testing <#localdirect-module-testing> `__
- `Playbook module testing <#playbook-module-testing> `__
- `Debugging (local) <#debugging-local> `__
- `Debugging (remote) <#debugging-remote> `__
- `Unit testing <#unit-testing> `__
- Integration testing (coming soon)
- `Communication and development
support <#communication-and-development-support>`__
- `Credit <#credit> `__
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
Environment setup
=================
2017-11-27 19:58:13 +00:00
Prerequisites Via Apt (Ubuntu)
`` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ``
Due to dependencies (for example ansible -> paramiko -> pynacl -> libffi):
2017-01-27 22:03:26 +00:00
2017-11-27 19:58:13 +00:00
.. code :: bash
sudo apt update
sudo apt install build-essential libssl-dev libffi-dev python-dev
Common Environment setup
`` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ``
2017-07-14 02:06:01 +00:00
1. Clone the Ansible repository:
`` $ git clone https://github.com/ansible/ansible.git ``
2. Change directory into the repository root dir: `` $ cd ansible ``
3. Create a virtual environment: `` $ python3 -m venv venv `` (or for
Python 2 `` $ virtualenv venv `` . Note, this requires you to install
the virtualenv package: `` $ pip install virtualenv `` )
4. Activate the virtual environment: `` $ . venv/bin/activate ``
5. Install development requirements:
`` $ pip install -r requirements.txt ``
6. Run the environment setup script for each new dev shell process:
`` $ . hacking/env-setup ``
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
.. note :: After the initial setup above, every time you are ready to start
developing Ansible you should be able to just run the following from the
root of the Ansible repo:
`` $ . venv/bin/activate && . hacking/env-setup ``
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
New module development
======================
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
If you are creating a new module that doesn't exist, you would start
working on a whole new file. Here is an example:
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
- Navigate to the directory that you want to develop your new module
in. E.g. `` $ cd lib/ansible/modules/cloud/azure/ ``
- Create your new module file: `` $ touch my_new_test_module.py ``
2017-08-17 00:56:53 +00:00
- Paste this example code into the new module file: (explanation in comments)
.. code :: python
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
#!/usr/bin/python
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
ANSIBLE_METADATA = {
2017-08-05 18:28:21 +00:00
'metadata_version': '1.1',
2017-07-14 02:06:01 +00:00
'status': ['preview'],
2017-08-05 18:28:21 +00:00
'supported_by': 'community'
2017-07-14 02:06:01 +00:00
}
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
DOCUMENTATION = '''
---
module: my_sample_module
short_description: This is my sample module
version_added: "2.4"
description:
- "This is my longer description explaining my sample module"
options:
name:
description:
- This is the message to send to the sample module
required: true
new:
description:
- Control to demo if the result of this module is changed or not
required: false
2017-08-11 21:35:14 +00:00
extends_documentation_fragment:
2017-07-14 02:06:01 +00:00
- azure
author:
- Your Name (@yourhandle)
'''
EXAMPLES = '''
# Pass in a message
- name: Test with a message
my_new_test_module:
name: hello world
# pass in a message and have changed true
- name: Test with a message and changed output
my_new_test_module:
name: hello world
new: true
# fail the module
- name: Test failure of the module
my_new_test_module:
name: fail me
'''
RETURN = '''
original_message:
description: The original name param that was passed in
type: str
message:
description: The output message that the sample module generates
'''
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
from ansible.module_utils.basic import AnsibleModule
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
def run_module():
# define the available arguments/parameters that a user can pass to
# the module
module_args = dict(
name=dict(type='str', required=True),
new=dict(type='bool', required=False, default=False)
)
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
# seed the result dict in the object
# we primarily care about changed and state
# change is if this module effectively modified the target
# state will include any data that you want your module to pass back
# for consumption, for example, in a subsequent task
result = dict(
changed=False,
original_message='',
message=''
)
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
# the AnsibleModule object will be our abstraction working with Ansible
# this includes instantiation, a couple of common attr would be the
# args/params passed to the execution, as well as if the module
# supports check mode
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True
)
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
# if the user is working with this module in only check mode we do not
# want to make any changes to the environment, just return the current
# state with no modifications
if module.check_mode:
return result
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
# manipulate or modify the state as needed (this is going to be the
# part where your module will do what it needs to do)
result['original_message'] = module.params['name']
result['message'] = 'goodbye'
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
# use whatever logic you need to determine whether or not this module
# made any modifications to your target
if module.params['new']:
result['changed'] = True
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
# during the execution of the module, if there is an exception or a
# conditional state that effectively causes a failure, run
# AnsibleModule.fail_json() to pass in the message and the result
if module.params['name'] == 'fail me':
module.fail_json(msg='You requested this to fail', **result)
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
# in the event of a successful module execution, you will want to
# simple AnsibleModule.exit_json(), passing the key/value results
module.exit_json(**result)
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
def main():
run_module()
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
if __name__ == '__main__':
main()
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
Local/direct module testing
===========================
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
You may want to test the module on the local machine without targeting a
remote host. This is a great way to quickly and easily debug a module
that can run locally.
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
- Create an arguments file in `` /tmp/args.json `` with the following
content: (explanation below)
2017-01-27 22:03:26 +00:00
2017-08-17 00:56:53 +00:00
.. code :: json
2017-01-27 22:03:26 +00:00
2017-08-17 00:56:53 +00:00
{
"ANSIBLE_MODULE_ARGS": {
"name": "hello",
"new": true
}
}
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
- If you are using a virtual environment (highly recommended for
development) 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 ``
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
This should be working output that resembles something like the
following:
2017-01-27 22:03:26 +00:00
2017-08-17 00:56:53 +00:00
.. code :: json
2017-05-08 16:08:55 +00:00
2017-07-14 02:06:01 +00:00
{"changed": true, "state": {"original_message": "hello", "new_message": "goodbye"}, "invocation": {"module_args": {"name": "hello", "new": true}}}
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
The arguments file is just a basic json config file that you can
use to pass the module your parameters to run the module it
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
Playbook module testing
=======================
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
If you want to test your new module, you can now consume it with an
Ansible playbook.
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
- Create a playbook in any directory: `` $ touch testmod.yml ``
2017-08-14 00:09:19 +00:00
- Add the following to the new playbook file::
2017-01-27 22:03:26 +00:00
2017-08-14 00:09:19 +00:00
- name: test my new module
connection: local
hosts: localhost
tasks:
- name: run the new module
my_new_test_module:
name: 'hello'
new: true
register: testout
- name: dump test output
debug:
msg: '{{ testout }}'
- Run the playbook and analyze the output: `` $ ansible-playbook ./testmod.yml ``
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
Debugging (local)
2017-08-17 00:56:53 +00:00
=================
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
If you want to break into a module and step through with the debugger, locally running the module you can do:
2017-01-27 22:03:26 +00:00
2017-08-17 00:56:53 +00:00
- Set a breakpoint in the module: `` import pdb; pdb.set_trace() ``
2017-08-14 00:09:19 +00:00
- Run the module on the local machine: `` $ python -m pdb ./my_new_test_module.py ./args.json ``
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
Debugging (remote)
==================
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
In the event you want to debug a module that is running on a remote target (i.e. not localhost), one way to do this is the following:
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
- On your controller machine (running Ansible) set `ANSIBLE_KEEP_REMOTE_FILES=1` (this tells Ansible to retain the modules it sends to the remote machine instead of removing them)
- Run your playbook targetting the remote machine and specify `` -vvvv `` (the verbose output will show you many things, including the remote location that Ansible uses for the modules)
- Take note of the remote path Ansible used on the remote host
- SSH into the remote target after the completion of the playbook
- Navigate to the directory (most likely it is going to be your ansible remote user defined or implied from the playbook: `` ~/.ansible/tmp/ansible-tmp-... `` )
- Here you should see the module that you executed from your Ansible controller, but this is the zipped file that Ansible sent to the remote host. You can run this by specifying `` python my_test_module.py `` (not necessary)
2017-08-14 00:09:19 +00:00
- To debug, though, we will want to extract this zip out to the original module format: `` python my_test_module.py explode `` (Ansible will expand the module into `` ./debug-dir `` )
2017-07-14 02:06:01 +00:00
- Navigate to `` ./debug-dir `` (notice that unzipping has caused the generation of `` ansible_module_my_test_module.py `` )
- Modify or set a breakpoint in the unzipped module
- Ensure that the unzipped module is executable: `` $ chmod 755 ansible_module_my_test_module.py ``
- Run the unzipped module directly passing the args file: `` $ ./ansible_module_my_test_module.py args `` (args is the file that contains the params that were originally passed. Good for repro and debugging)
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
Unit testing
============
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
Unit tests for modules will be appropriately located in `` ./test/units/modules `` . You must first setup your testing environment. In this example, we're using Python 3.5.
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
- 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)
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
.. note :: Ansible uses pytest for unit testing.
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
To run pytest against a single test module, you can do the following (provide the path to the test module appropriately):
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
`` $ pytest -r a --cov=. --cov-report=html --fulltrace --color yes
test/units/modules/.../test/my_new_test_module.py``
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
Going Further
=============
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
If you are starting new development or fixing a bug, create a new branch:
2017-01-27 22:03:26 +00:00
2017-08-17 00:56:53 +00:00
`` $ git checkout -b my-new-branch `` .
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
If you are planning on contributing
back to the main Ansible repository, fork the Ansible repository into
2017-08-14 00:09:19 +00:00
your own GitHub account and develop against the new non-devel branch
2017-07-14 02:06:01 +00:00
in your fork. When you believe you have a good working code change,
submit a pull request to the Ansible repository.
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
If you want to submit a new module to the upstream Ansible repo, be sure
to run through sanity checks first. For example:
2017-01-27 22:03:26 +00:00
2017-08-17 00:56:53 +00:00
`` $ ansible-test sanity -v --docker --python 2.7 MODULE_NAME ``
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
Note that this example requires docker to be installed and running. If you'd rather not use a
container for this, you can choose to use `` --tox `` instead of `` --docker `` .
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
Communication and development support
=====================================
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
Join the IRC channel `` #ansible-devel `` on freenode for discussions
surrounding Ansible development.
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
For questions and discussions pertaining to using the Ansible product,
use the `` #ansible `` channel.
2017-01-27 22:03:26 +00:00
2017-07-14 02:06:01 +00:00
Credit
======
2017-01-27 22:03:26 +00:00
2017-10-01 08:39:02 +00:00
Thank you to Thomas Stringer (`@tstringer <https://github.com/tstringer> `_ ) for contributing source
2017-07-14 02:06:01 +00:00
material for this topic.