Developing modules — Ansible Community Documentation (2024)

'; */ // Create a banner if we're not on the official docs site if (location.host == "docs.testing.ansible.com") { document.write('

'); } // Create a banner current_url_path = window.location.pathname; var important = false; var msg = '

'; if (startsWith(current_url_path, "/ansible-core/")) { msg += 'You are reading documentation for Ansible Core, which contains no plugins except for those in ansible.builtin. For documentation of the Ansible package, go to the latest documentation.'; } else if (startsWithOneOf(current_url_path, ["/ansible/latest/", "/ansible/9/"])) { /* temp extra banner to advertise something */ banner += extra_banner; msg += 'This is the latest (stable) Ansible community documentation. For Red Hat Ansible Automation Platform subscriptions, see Life Cycle for version details.'; } else if (startsWith(current_url_path, "/ansible/2.9/")) { msg += 'You are reading the latest Red Hat released version of the Ansible documentation. Community users can use this version, or select latest from the version selector to the left for the most recent community version.'; } else if (startsWith(current_url_path, "/ansible/devel/")) { /* temp extra banner to advertise something */ banner += extra_banner; msg += 'You are reading the devel version of the Ansible documentation - this version is not guaranteed stable. Use the version selection to the left if you want the latest (stable) released version.'; } else { msg += 'You are reading an older version of the Ansible documentation. Use the version selection to the left if you want the latest (stable) released version.'; /* temp extra banner to advertise something - this is for testing*/ banner += extra_banner; } msg += '

'; banner += important ? '
' : ''; banner += msg; banner += important ? '
' : ''; banner += '

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, accepts arguments, and returns information to Ansible by printing a JSON string to stdout before exiting.

If you need functionality that is not available in any of the thousands of Ansible modules found in collections, you can easily write your own custom module. When you write a module for local use, you can choose any programming language and follow your own rules. Use this topic to learn how to create an Ansible module in Python. After you create a module, you must add it locally to the appropriate directory so that Ansible can find and execute it. For details about adding a module locally, see Adding modules and plugins locally.

If you are developing a module in a collection, see those documents instead.

Preparing an environment for developing Ansible modules

You just need ansible-core installed to test the module. Modules can be written in any language,but most of the following guide is assuming you are using Python.Modules for inclusion in Ansible itself must be Python or Powershell.

One advantage of using Python or Powershell for your custom modules is being able to use the module_utils common code that does a lot of theheavy lifting for argument processing, logging and response writing, among other things.

Creating a module

It is highly recommended that you use a venv or virtualenv for Python development.

To create a module:

  1. Create a library directory in your workspace, your test play should live in the same directory.

  2. Create your new module file: $ touch library/my_test.py. Or just open/create it with your editor of choice.

  3. Paste the content below into your new module file. It includes the required Ansible format and documentation, a simple argument spec for declaring the module options, and some example code.

  4. 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 and concise module code.

#!/usr/bin/python# Copyright: (c) 2018, Terry Jones <[emailprotected]># GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)from __future__ import (absolute_import, division, print_function)__metaclass__ = typeDOCUMENTATION = r'''---module: my_testshort_description: This is my test module# If this is part of a collection, you need to use semantic versioning,# i.e. the version is of the form "2.5.0" and not "2.4".version_added: "1.0.0"description: This is my longer description explaining my test module.options: name: description: This is the message to send to the test module. required: true type: str new: description: - Control to demo if the result of this module is changed or not. - Parameter description can be a list as well. required: false type: bool# Specify this value according to your collection# in format of namespace.collection.doc_fragment_name# extends_documentation_fragment:# - my_namespace.my_collection.my_doc_fragment_nameauthor: - Your Name (@yourGitHubHandle)'''EXAMPLES = r'''# Pass in a message- name: Test with a message my_namespace.my_collection.my_test: name: hello world# pass in a message and have changed true- name: Test with a message and changed output my_namespace.my_collection.my_test: name: hello world new: true# fail the module- name: Test failure of the module my_namespace.my_collection.my_test: name: fail me'''RETURN = r'''# These are examples of possible return values, and in general should use other names for return values.original_message: description: The original name param that was passed in. type: str returned: always sample: 'hello world'message: description: The output message that the test module generates. type: str returned: always sample: 'goodbye''''from ansible.module_utils.basic import AnsibleModuledef run_module(): # define available arguments/parameters a user can pass to the module module_args = dict( name=dict(type='str', required=True), new=dict(type='bool', required=False, default=False) ) # seed the result dict in the object # we primarily care about changed and state # changed 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='' ) # 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 ) # 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: module.exit_json(**result) # 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' # 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 # 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) # 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)def main(): run_module()if __name__ == '__main__': main()

Creating an info or a facts module

Ansible gathers information about the target machines using facts modules, and gathers information on other objects or files using info modules.If you find yourself trying to add state: info or state: list to an existing module, that is often a sign that a new dedicated _facts or _info module is needed.

In Ansible 2.8 and onwards, we have two type of information modules, they are *_info and *_facts.

If a module is named <something>_facts, it should be because its main purpose is returning ansible_facts. Do not name modules that do not do this with _facts.Only use ansible_facts for information that is specific to the host machine, for example network interfaces and their configuration, which operating system and which programs are installed.

Modules that query/return general information (and not ansible_facts) should be named _info.General information is non-host specific information, for example information on online/cloud services (you can access different accounts for the same online service from the same host), or information on VMs and containers accessible from the machine, or information on individual files or programs.

Info and facts modules, are just like any other Ansible Module, with a few minor requirements:

  1. They MUST be named <something>_info or <something>_facts, where <something> is singular.

  2. Info *_info modules MUST return in the form of the result dictionary so other modules can access them.

  3. Fact *_facts modules MUST return in the ansible_facts field of the result dictionary so other modules can access them.

  4. They MUST support check_mode.

  5. They MUST NOT make any changes to the system.

  6. They MUST document the return fields and examples.

The rest is just like creating a normal module.

Verifying your module code

After you modify 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 verify your module code.

Verifying your module code locally

The simplest way is to use ansible adhoc command:

ANSIBLE_LIBRARY=./library ansible -m my_test -a 'name=hello new=true' remotehost

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

ANSIBLE_LIBRARY=./library ansible -m my_test -a 'name=hello new=true' localhost
  • If for any reason (pdb, using print(), faster iteration, etc) you want to avoid going through Ansible,another way is to create an arguments file, a basic JSON config file that passes parameters to your module so that you can run it.Name the arguments file /tmp/args.json and add the following content:

{ "ANSIBLE_MODULE_ARGS": { "name": "hello", "new": true }}
  • Then the module can be tested locally and directly. This skips the packing steps and uses module_utils files directly:

``$ python library/my_test.py /tmp/args.json``

It should return output like this:

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

Verifying your module code in a playbook

You can easily run a full test by including it in a playbook, as long as the library directory is in the same directory as the play:

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

  • Add the following to the new playbook file:

- name: test my new module hosts: localhost tasks: - name: run the new module my_test: name: 'hello' new: true register: testout - name: dump test output debug: msg: '{{ testout }}'
  • Run the playbook and analyze the output: $ ansible-playbook ./testmod.yml

Testing your newly-created module

The following 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.

Note

If contributing to Ansible, every new module and plugin should have integration tests, even if the tests cannot be run on Ansible CI infrastructure.In this case, the tests should be marked with the unsupported alias in aliases file.

Performing sanity tests

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

$ ansible-test sanity -v --docker --python 3.10 MODULE_NAME

Note

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 --venv instead of --docker.

Contributing back to Ansible

If you would like to contribute to ansible-core by adding a new feature or fixing a bug, create a fork of the ansible/ansible repository and develop against a new feature branch using the devel branch as a starting point. When you have a good working code change, you can submit a pull request to the Ansible repository by selecting your feature branch as a source and the Ansible devel branch as a target.

If you want to contribute a module to an Ansible collection, review our submission checklist, programming tips, and strategy for maintaining Python 2 and Python 3 compatibility, as well as information 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 #ansible-devel chat channel (using Matrix at ansible.im or using IRC at irc.libera.chat) for discussions surrounding Ansible development.

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

To find other topic-specific chat channels, look at Community Guide, Communicating.

Credit

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

Developing modules — Ansible Community Documentation (2024)

FAQs

Where can you find documentation on Ansible modules? ›

As long as your module file is available locally, you can use ansible-doc -t module my_module_name to view your module documentation at the command line. Any parsing errors will be obvious - you can view details by adding -vvv to the command. You should also test the HTML output of your module documentation.

How to create modules in Ansible? ›

To create a module:
  1. Create a library directory in your workspace, your test play should live in the same directory.
  2. Create your new module file: $ touch library/my_test.py . ...
  3. Paste the content below into your new module file. ...
  4. Modify and extend the code to do what you want your new module to do.

Which file contains Ansible plugin documentation? ›

In ansible-core 2.14 we added support for documenting filter and test plugins. You have two options for providing documentation: Define a Python file that includes inline documentation for each plugin. Define a Python file for multiple plugins and create adjacent documentation files in YAML format.

What is the development process of Ansible? ›

  • Preparing an environment for developing Ansible modules.
  • Creating a module.
  • Creating an info or a facts module.
  • Verifying your module code.
  • Testing your newly-created module.
  • Contributing back to Ansible.
  • Communication and development support.
  • Credit.

Is Ansible still relevant? ›

In terms of popularity for individual configuration management tools, Ansible is now ahead of the pack, with a survey from TechRepublic showing that Ansible had the most widespread usage across survey respondents, at 41%, followed by Chef and Puppet in a tie at 31%, with Terraform at 31%, and Saltstack at 18%.

What language are Ansible modules written in? ›

Ansible is a tool written in Python, and it uses the declarative markup language YAML to describe the desired state of devices and configuration.

What are the most used modules in Ansible? ›

The list
RankModuleUses
1file26,224
2include25,267
3template24,062
4command23,952
96 more rows
Jan 30, 2019

What is the difference between Ansible playbook and module? ›

Modules are typically stored in a playbook's library and run when the playbook executes the associated task, but they may also be included within a role or collection. When an Ansible Role is imported into a playbook, the modules in the role directory execute the task or tasks contained within that role.

What is the difference between module and playbook in Ansible? ›

Ansible modules are standalone scripts that can be used inside an Ansible playbook. A playbook consists of a play, and a play consists of tasks. These concepts may seem confusing if you're new to Ansible, but as you begin writing and working more with playbooks, they will become familiar.

What is the difference between Ansible modules and plugins? ›

Modules interface with Ansible mostly with JSON, accepting arguments and returning information by printing a JSON string to stdout before exiting. Unlike the other plugins (which must be written in Python), modules can be written in any language; although Ansible provides modules in Python and Powershell only.

What is the difference between a plugin and a module in Ansible? ›

Modules execute on the target system (usually that means on a remote system) in separate processes. Plugins augment Ansible's core functionality and execute on the control node within the /usr/bin/ansible process.

Where are Ansible modules installed? ›

Ansible modules

As most Ansible installations use the /etc/ansible directory as the Ansible top-directory (as this is the default in an Ansible installation), this is probably the best installation option.

What will replace Ansible? ›

  • Ansible is a configuration management solution for automating the development life cycle. ...
  • Puppet is another alternative to Ansible. ...
  • Terraform is another Ansible alternative for automating configuration management. ...
  • Chef is an excellent tool for maintaining consistent configurations across multiple servers.
Jan 2, 2024

What is the salary of Ansible developer? ›

Average salary for a Ansible Developer in India is 7.0 Lakhs per year (₹58.3k per month).

Why use Terraform instead of Ansible? ›

Terraform sets up and manages your IT infrastructure, using an infrastructure as code approach. Ansible, on the other hand, focuses on automating IT tasks like provisioning and deployment. In short: Use Terraform for infrastructure setup and Ansible for configuration.

Where can you find a list of all modules in the Ansible online documentation? ›

  1. Module Index. All modules. Cloud modules. Clustering modules. Commands modules. Crypto modules. Database modules. Files modules. Identity modules. Inventory modules. Messaging modules. Monitoring modules. Net Tools modules. Network modules. Notification modules. Packaging modules. Remote Management modules. ...
  2. Return Values.

How can you find information in Ansible? ›

With Ansible you can retrieve or discover certain variables containing information about your remote systems or about Ansible itself. Variables related to remote systems are called facts. With facts, you can use the behavior or state of one system as a configuration on other systems.

How do I get the documentation of a module in Python? ›

The documentation can be presented as pages of text on the console, served to a web browser, or saved to HTML files. For modules, classes, functions and methods, the displayed documentation is derived from the docstring (i.e. the __doc__ attribute) of the object, and recursively of its documentable members.

Top Articles
Latest Posts
Article information

Author: Lakeisha Bayer VM

Last Updated:

Views: 6432

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Lakeisha Bayer VM

Birthday: 1997-10-17

Address: Suite 835 34136 Adrian Mountains, Floydton, UT 81036

Phone: +3571527672278

Job: Manufacturing Agent

Hobby: Skimboarding, Photography, Roller skating, Knife making, Paintball, Embroidery, Gunsmithing

Introduction: My name is Lakeisha Bayer VM, I am a brainy, kind, enchanting, healthy, lovely, clean, witty person who loves writing and wants to share my knowledge and understanding with you.