* updated docs
- for devs:
- added inventory/vars section
- made some updates to general section and other plugin types
- for users:
- added 'user' plugin section to start describing the plugins
- docs on types, what they are and how to use
- removed ref to deleted AUTHORS file
- corrected several typos/headers
- added descriptions to config.rst template
- ignore generated files for cli/plugins and config
- remove new generated files on `make clean`
- moved details from devguid and intro doc to plugin specific pages
- pretied up lookup notes
- changed precedence ref to not conflict config
- removed duplicate config data, as config is autogenerated and up to date
- put new plugins under playbooks
- added `pass` cause rst/python dislikes fractions
- removed dupe in .gitignore, alpha sorted to avoid moar dupes
- added try cause rst/python freaks out
* generate plugins into their own dir
only do plugins that support docs
use toctree from main plugins page
Plugins are pieces of code that augment Ansible's core functionality. Ansible ships with a number of handy plugins, and you can easily write your own.
Plugins are pieces of code that augment Ansible's core functionality. Ansible ships with a number of handy plugins, and you can easily write your own.
The following types of plugins are available:
- *Action* plugins are front ends to modules and can execute actions on the controller before calling the modules themselves.
- *Cache* plugins are used to keep a cache of 'facts' to avoid costly fact-gathering operations.
- *Callback* plugins enable you to hook into Ansible events for display or logging purposes.
- *Connection* plugins define how to communicate with inventory hosts.
- *Filters* plugins allow you to manipulate data inside Ansible plays and/or templates. This is a Jinja2 feature; Ansible ships extra filter plugins.
- *Lookup* plugins are used to pull data from an external source. These are implemented using a custom Jinja2 function.
- *Strategy* plugins control the flow of a play and execution logic.
- *Shell* plugins deal with low-level commands and formatting for the different shells Ansible can encounter on remote hosts.
- *Test* plugins allow you to validate data inside Ansible plays and/or templates. This is a Jinja2 feature; Ansible ships extra test plugins.
- *Vars* plugins inject additional variable data into Ansible runs that did not come from an inventory, playbook, or the command line.
This section describes the various types of plugins and how to implement them.
This section describes the various types of plugins and how to implement them.
.._plugin_guidelines:
.._developing_callbacks:
General Guidelines
------------------
Callback Plugins
----------------
Callback plugins enable adding new behaviors to Ansible when responding to events. By default, callback plugins control most of the output you see when running the command line programs.
.._callback_examples:
Example Callback Plugins
Some things that should apply to any type of plugin you develop.
++++++++++++++++++++++++
Ansible comes with a number of callback plugins that you can look at for examples. These can be found in `lib/ansible/plugins/callback <https://github.com/ansible/ansible/tree/devel/lib/ansible/plugins/callback>`_.
Raising Errors
``````````````
The `log_plays
In general, errors encountered during execution should be returned by raising AnsibleError() or similar class with a message describing the error.
callback provided is particularly entertaining -- it will respond with
computer synthesized speech on OS X in relation to playbook events,
and is guaranteed to entertain and/or annoy coworkers.
.._configuring_callbacks:
from ansible.module_utils._text import to_native
Configuring Callback Plugins
try:
++++++++++++++++++++++++++++
cause_an_exeption()
except Exception as e:
AnsibleError('Something happend, this was original exception: %s' % to_native(e))
You can activate a custom callback by either dropping it into a callback_plugins directory adjacent to your play or inside a role or by putting it in one of the callback directory sources configured in `ansible.cfg`.
Check the different AnsibleError objects and see which one applies the best to your situation.
Plugins are loaded in alphanumeric order; for example, a plugin implemented in a file named `1_first.py` would run before a plugin file named `2_second.py`.
String encoding
```````````````
Any strings returned by your plugin that could ever contain non-ASCII characters must be converted into Python's unicode type
because the strings will be run through jinja2. To do this, you can use:
Most callbacks shipped with Ansible are disabled by default and need to be whitelisted in your `ansible.cfg` file in order to function. For example::
Starting in 2.4 and going forward, we are unifying how each plugin type is configured and how they get those settings, plugins will be able to 'declare'
```````````````
their needs and have Ansible provide them with the 'resolved' configuration. As of 2.4 both Callback and Connection type plugins can use this system,
most plugins will be able to use `self._options[<optionname>]` to access the settings, except callbacks that due to prexisting collsion
use `self._plugin_optoins[<optionname>]`.
You can only have one plugin be the main manager of your console output. If you want to replace the default, you should define CALLBACK_TYPE = stdout in the subclass and then configure the stdout plugin in `ansible.cfg`. For example::
Plugins that supprot docs (see `ansible-doc` for the list) are now required to provide documentation to be considered for merge into the Ansible repo.
#stdout_callback = mycallbackplugin
Also be aware that if you inherit from a plugin you must ALSO document the optoins it takes, either via a documentation fragment or as a copy.
.._developing_callbacks:
Callback Plugins
----------------
.._callback_development:
See :doc: plugins/callback as to what they are and how to use them. This section explains how to use them.
Developing Callback Plugins
+++++++++++++++++++++++++++
Callback plugins are created by creating a new class with the Base(Callbacks) class as the parent:
Callback plugins are created by creating a new class with the Base(Callbacks) class as the parent:
..code-block:: python
..code-block:: python
from ansible.plugins.callback import CallbackBase
from ansible.plugins.callback import CallbackBase
from ansible import constants as C
class CallbackModule(CallbackBase):
class CallbackModule(CallbackBase):
pass
pass
From there, override the specific methods from the CallbackBase that you want to provide a callback for. For plugins intended for use with Ansible version 2.0 and later, you should only override methods that start with `v2`. For a complete list of methods that you can override, please see ``__init__.py`` in the `lib/ansible/plugins/callback <https://github.com/ansible/ansible/tree/devel/lib/ansible/plugins/callback>`_ directory.
From there, override the specific methods from the CallbackBase that you want to provide a callback for.
For plugins intended for use with Ansible version 2.0 and later, you should only override methods that start with `v2`.
For a complete list of methods that you can override, please see ``__init__.py`` in the
Note that the CALLBACK_VERSION and CALLBACK_NAME definitions are required for properly functioning plugins for Ansible >=2.0.
Note that the CALLBACK_VERSION and CALLBACK_NAME definitions are required for properly functioning plugins for Ansible >=2.0.
CALLBACK_TYPE is mostly needed to distinguish 'stout' plugins from the rest, as you can only load one of that type.
.._developing_connection_plugins:
.._developing_connection_plugins:
@ -142,7 +157,45 @@ are covered in the :doc:`../intro_getting_started` section. Should you want to
directory. The value of 'smart' for a connection allows selection of paramiko or openssh based on system capabilities, and chooses
directory. The value of 'smart' for a connection allows selection of paramiko or openssh based on system capabilities, and chooses
'ssh' if OpenSSH supports ControlPersist, in Ansible 1.2.1 and later. Previous versions did not support 'smart'.
'ssh' if OpenSSH supports ControlPersist, in Ansible 1.2.1 and later. Previous versions did not support 'smart'.
More documentation on writing connection plugins is pending, though you can jump into `lib/ansible/plugins/connection <https://github.com/ansible/ansible/tree/devel/lib/ansible/plugins/connection>`_ and figure things out pretty easily.
More documentation on writing connection plugins is pending, though you can jump into
`lib/ansible/plugins/connection <https://github.com/ansible/ansible/tree/devel/lib/ansible/plugins/connection>`_ and figure things out pretty easily.
.._developing_inventory_plugins:
Inventory Plugins
-----------------
Added in Ansible 2.4 they are in charge of parsing inventory sources and forming the 'in memory' representation of the Inventory.
They are invoked via the InventoryManager and are given access to any existing inventory data added previouslly,
they are given an 'inventory source' as supplied to Ansible (via config/optoins/defaults/etc), which they can ignore
(return false from the `verify_file` method), or attempt to parse (via `parse` method) and return an `AnsibleParserError` on failure.
* inventory: inventory object with existing data and the methods to add hosts/groups/variables to inventory
* loader: Ansible's DataLoader, it can read files, auto load JSON/YAML and decrypt vaulted data, it also caches read filesh.
* path: string with inventory source (normally a path, but not required)
* cache: hint to the plugin if it should use or avoid caches (Cache plugin and/or loader)
Inventory sources are strings, most of the time they correspond to a file path, but can also be a comma separated list,
a uri or anything your plugin can use as input.
The 'inventory source' provided can be either a string (`host_list` plugin), a data file (like consumed by the `yaml` and `ini` plugins),
a configuration file (see `virtualbox` and `constructed`) or even a script or executable (the `script` uses those) which is how 'inventory scripts' work.
Inventory plugins can also use the configured Cache plugin to store and retrieve data to avoid costly external calls,
of course this only works if using a 'persistent' cache (i.e not the memory one).
Be aware that inventory plugins normally only execute at the start of the run, before playbooks/plays and roles are found,
but they can be 're-executed' via the `meta: refresh_inventory` task, which will clear out the existing inventory and rebuild it.
More documentation on writing inventory plugins is pending, though you can jump into
`lib/ansible/plugins/inventory <https://github.com/ansible/ansible/tree/devel/lib/ansible/plugins/inventory>`_ and figure things out pretty easily.
.._developing_lookup_plugins:
.._developing_lookup_plugins:
@ -155,6 +208,25 @@ Here's a simple lookup plugin implementation - this lookup returns the contents
..code-block:: python
..code-block:: python
# python 3ish headers, required if submitting to Ansible
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
lookup: file
author: Daniel Hokka Zakrisson <daniel@hozac.com>
version_added: "0.9"
short_description: read file contents
description:
- This lookup returns the contents from a file on the Ansible controller's file system.
options:
_terms:
description: path(s) of files to read
required: True
notes:
- if read in variable context, the file can be interpreted as YAML if the content is valid to the parser.
- this lookup does not understand 'globing', use the fileglob lookup instead.
"""
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.plugins.lookup import LookupBase
from ansible.plugins.lookup import LookupBase
@ -169,19 +241,28 @@ Here's a simple lookup plugin implementation - this lookup returns the contents
def run(self, terms, variables=None, **kwargs):
def run(self, terms, variables=None, **kwargs):
ret = []
# lookups in general are expected to both take a list as input and output a list
# this is done so they work with the looping construct `with_`.
ret = []
for term in terms:
for term in terms:
display.debug("File lookup term: %s" % term)
display.debug("File lookup term: %s" % term)
# Find the file in the expected search path
# Find the file in the expected search path, using a class method
# that implements the 'expected' search path for Ansible plugins.
# Always use ansible error classes to throw 'final' exceptions,
# so the Ansible engine will know how to deal with them.
# The Parser error indicates invalid options passed
raise AnsibleParserError()
raise AnsibleParserError()
except AnsibleParserError:
except AnsibleParserError:
raise AnsibleError("could not locate file in lookup: %s" % term)
raise AnsibleError("could not locate file in lookup: %s" % term)
@ -199,13 +280,6 @@ An example of how this lookup is called::
- debug: msg="the value of foo.txt is {{ contents }} as seen today {{ lookup('pipe', 'date +"%Y-%m-%d"') }}"
- debug: msg="the value of foo.txt is {{ contents }} as seen today {{ lookup('pipe', 'date +"%Y-%m-%d"') }}"
Errors encountered during execution should be returned by raising AnsibleError() with a message describing the error. Any strings returned by your lookup plugin implementation that could ever contain non-ASCII characters must be converted into Python's unicode type because the strings will be run through jinja2. To do this, you can use:
..code-block:: python
from ansible.module_utils._text import to_text
result_string = to_text(result_string)
For more example lookup plugins, check out the source code for the lookup plugins that are included with Ansible here: `lib/ansible/plugins/lookup <https://github.com/ansible/ansible/tree/devel/lib/ansible/plugins/lookup>`_.
For more example lookup plugins, check out the source code for the lookup plugins that are included with Ansible here: `lib/ansible/plugins/lookup <https://github.com/ansible/ansible/tree/devel/lib/ansible/plugins/lookup>`_.
For usage examples of lookup plugins, see `Using Lookups <http://docs.ansible.com/ansible/playbooks_lookups.html>`_.
For usage examples of lookup plugins, see `Using Lookups <http://docs.ansible.com/ansible/playbooks_lookups.html>`_.
@ -215,14 +289,42 @@ For usage examples of lookup plugins, see `Using Lookups <http://docs.ansible.co
Vars Plugins
Vars Plugins
------------
------------
Playbook constructs like 'host_vars' and 'group_vars' work via 'vars' plugins. They inject additional variable
Playbook constructs like 'host_vars' and 'group_vars' work via 'vars' plugins.
data into ansible runs that did not come from an inventory, playbook, or command line. Note that variables
They inject additional variable data into ansible runs that did not come from an inventory source, playbook, or command line.
can also be returned from inventory, so in most cases, you won't need to write or understand vars_plugins.
Vars plugins got rewritten in 2.4 and had been semi-functional since 2.0.
Older pugins used a `run` method as their main body/work:
..code-block:: python
def run(self, name, vault_password=None):
pass # your code goes here
But Ansible 2.0 did not pass passwords to them so vaults were unavilable.
Most of the work now happens in the `get_vars` method which is called from the VariableManager when needed.
More documentation on writing vars plugins is pending, though you can jump into `lib/ansible/plugins <https://github.com/ansible/ansible/tree/devel/lib/ansible/plugins/>`_ and figure
..code-block:: python
things out pretty easily.
def get_vars(self, loader, path, entities):
pass # your code goes here
The parameters are:
* loader: Ansible's DataLoader, it can read files, auto load JSON/YAML and decrypt vaulted data, it also caches read filesh.
* path: this is 'directory data' for every inventory source and the current play's playbook directory, so they can search for data
in reference to them, `get_vars` will be called at least once per available path.
* entities: these are host or group names that are pertinent to the variables needed, the plugin will get called once for hosts and again for groups.
This method just needs to return a dictionary structure with the pertinent variables.
Since Ansible 2.4, vars plugins execute as needed when preparing to execute a task, this avoids the costly 'always execute' that used
to happend during inventory construction.
More documentation on writing vars plugins is pending, though you can jump into
`lib/ansible/plugins/vars <https://github.com/ansible/ansible/tree/devel/lib/ansible/plugins/vars>`_ and figure things out pretty easily.
If you find yourself wanting to write a vars_plugin, it's more likely you should write an inventory script instead.
.._developing_filter_plugins:
.._developing_filter_plugins:
@ -255,11 +357,14 @@ Plugins are automatically loaded when you have one of the following subfolders a
* lookup_plugins
* lookup_plugins
* callback_plugins
* callback_plugins
* connection_plugins
* connection_plugins
* inventory_plugins
* filter_plugins
* filter_plugins
* strategy_plugins
* strategy_plugins
* cache_plugins
* cache_plugins
* test_plugins
* test_plugins
* shell_plugins
* shell_plugins
* vars_plugins
When shipped as part of a role, the plugin will be available as soon as the role is called in the play.
When shipped as part of a role, the plugin will be available as soon as the role is called in the play.
Lookup plugins allow access of data in Ansible from outside sources. Like all templating, these plugins are evaluated on the Ansible control
Lookup plugins allow access of data in Ansible from outside sources. Like all templating, these plugins are evaluated on the Ansible control
machine, and can include reading the filesystem but also contacting external datastores and services.
machine, and can include reading the filesystem but also contacting external datastores and services.
These values are then made available using the standard templating system in Ansible, and are typically used to load variables or templates with information from those systems.
..note:: This is considered an advanced feature, and many users will probably not rely on these features.
These values are then made available using the standard templating system in Ansible,
and are typically used to load variables or templates with information from those systems.
..note:: Lookups occur on the local computer, not on the remote computer.
..note::
- Lookups occur on the local computer, not on the remote computer.
..note:: Lookups are executed with a cwd relative to the role or play, as opposed to local tasks which are executed with the cwd of the executed script.
- They are executed with a cwd relative to the role or play, as opposed to local tasks which are executed with the cwd of the executed script.
- Since 1.9 you can pass wantlist=True to lookups to use in jinja2 template "for" loops.
..note:: Since 1.9 you can pass wantlist=True to lookups to use in jinja2 template "for" loops.
- This is considered an advanced feature, you should try to feel comfortable with Ansible plays before incorporating them.
..warning:: Some lookups pass arguments to a shell. When using variables from a remote/untrusted source, use the `|quote` filter to ensure safe usage.
..warning:: Some lookups pass arguments to a shell. When using variables from a remote/untrusted source, use the `|quote` filter to ensure safe usage.
@ -69,7 +69,7 @@ Variables can also be passed to include files using an alternative syntax, which
- "{{ lookup('file', 'keys/one.pub') }}"
- "{{ lookup('file', 'keys/one.pub') }}"
- "{{ lookup('file', 'keys/two.pub') }}"
- "{{ lookup('file', 'keys/two.pub') }}"
Using either syntax, variables passed in can then be used in the included files. These variables will only be available to tasks within the included file. See :ref:`variable_precedence` for more details on variable inheritance and precedence.
Using either syntax, variables passed in can then be used in the included files. These variables will only be available to tasks within the included file. See :ref:`ansible_variable_precedence` for more details on variable inheritance and precedence.
Task include statements can be used at arbitrary depth.
Task include statements can be used at arbitrary depth.
Callback plugins enable adding new behaviors to Ansible when responding to events.
By default, callback plugins control most of the output you see when running the command line programs,
but can also be used to add additional output, integrate with other tools and marshall the events to a storage backend.
.._callback_examples:
Example Callback Plugins
++++++++++++++++++++++++
The :doc:`log_plays <callback/log_plays>` callback is an example of how to record playbook events to a log file,
and the :doc:`mail callback/mail` callback sends email on playbook failures.
The :doc:`osx_say <callback/oxs_say>` callback provided is particularly entertaining --
it will respond with computer synthesized speech on OS X in relation to playbook events,
and is guaranteed to entertain and/or annoy coworkers.
.._enabling_callbacks:
Enabling Callback Plugins
++++++++++++++++++++++++++
You can activate a custom callback by either dropping it into a ``callback_plugins`` directory adjacent to your play or inside a role
or by putting it in one of the callback directory sources configured in :doc:`ansible.cfg <../config>`.
Plugins are loaded in alphanumeric order; for example, a plugin implemented in a file named `1_first.py` would run before a plugin file named `2_second.py`.
Most callbacks shipped with Ansible are disabled by default and need to be whitelisted in your :doc:`ansible.cfg <../config>` file in order to function.
For example:
..code-block:: ini
#callback_whitelist = timer, mail, profile_roles
Managing stdout
```````````````
You can only have one plugin be the main manager of your console output. If you want to replace the default, you should define CALLBACK_TYPE = stdout in the subclass and then configure the stdout plugin in :doc:`ansible.cfg <../config>`. For example:
..code-block:: ini
stdout_callback = dense
or for my custom callback:
..code-block:: ini
stdout_callback = mycallback
This only affects :doc:`../ansible-playbook` by default.
Managing AdHoc
``````````````
The :doc:`ansible <../ansible>` AdHoc command speifically uses a different callback plugin for stdout,
so there is an extra setting you need to enable it to use the stdout callback defined above, in :doc:`ansible.cfg <../config>`:
..code-block:: ini
[defaults]
bin_ansible_callbacks=True
or as an environment variable:
..code-block:: shell
export ANSIBLE_LOAD_CALLBACK_PLUGINS=1
Plugin List
+++++++++++
You can use ``ansible-doc -t callback -l`` to see the list of available plugins,
use ``ansible-doc -t callback <plugin name>`` to see specific documents and examples.
..toctree:: :maxdepth: 1
:glob:
callback/*
..seealso::
:doc:`../playbooks`
An introduction to playbooks
:doc:`inventory`
Ansible inventory plugins
:doc:`../playbooks_filters`
Jinja2 filter plugins
:doc:`../playbooks_tests`
Jinja2 test plugins
:doc:`../playbooks_lookups`
Jinja2 lookup plugins
:doc:`vars`
Ansible vars plugins
`User Mailing List <http://groups.google.com/group/ansible-devel>`_
These plugins are in charge of enabling Ansible to connect to the target hosts so it can execute tasks on them.
Ansible ships we many connection plugins but only one can be used per host at a time.
By default, the configuration uses a 'smart' value, which means Ansible will decide to use the 'ssh' or 'paramiko' (python version of ssh client)
depending on what it detects on your system capabilities, it normally chooses 'ssh' if OpenSSH supports ControlPersist.
The basics of these connection types are covered in the :doc:`../intro_getting_started` section.
..contents:: Topics
.._ssh_plugins:
The ssh Plugins
++++++++++++++++
Since ssh is the default protocol used in system administration it is also the most used and prevalent in Ansible,
so much so that ssh options are included in the command line tools unlike other plugins, see :doc:`../ansible-playbook` for more details.
.._using_connection_plugins:
Using Connection Plugins
++++++++++++++++++++++++
The transport can be changed via :doc:`configuration <../config>`, in the command line (``-c``, ``--connection``), as a keyword (:ref:`connection`)
in your play or by setting the a connection variable (:ref:`ansible_connection`), most often, in your inventory.
For example, for windows machines you might want o use the :doc:`winrm <connection/winrm>` plugin instead.
Most connection plugins can operate with a minimum configuration, by defaul they use the :ref:`inventory_hostname` and defaults to find the target host.
Each plugin documents it's configuration options and how to set, the following are 'connection variables' common to most:
:ref:ansible_host
The name of the host to connect to, if different from the :ref:`inventory_hostname`.
:ref:ansible_port
The ssh port number, for :doc:`ssh <connection/ssh>` and :doc:`paramiko <connection/paramiko>` it defaults to 22.
:ref:ansible_user
The default user name to log in as, most plugins defaul to the 'current user running Ansible'
Each plugin might also have a specific version that overrides the general one. i.e :ref:`ansible_ssh_host` for the :doc:`ssh <connection/ssh>` plugin.
Enabling Connection Plugins
+++++++++++++++++++++++++++
Should you want to extend Ansible to support other transports (SNMP, Message bus, etc) it's as simple as dropping a custom plugin
into the ``connection_plugins`` directory.
Plugin List
+++++++++++
You can use ``ansible-doc -t connection -l`` to see the list of available plugins,
use ``ansible-doc -t connection <plugin name>`` to examine detailed documentation and examples.
..toctree:: :maxdepth: 1
:glob:
connection/*
..seealso::
:doc:`../playbooks`
An introduction to playbooks
:doc:`callback`
Ansible callback plugins
:doc:`../playbooks_filters`
Jinja2 filter plugins
:doc:`../playbooks_tests`
Jinja2 test plugins
:doc:`../playbooks_lookups`
Jinja2 lookup plugins
:doc:`vars`
Ansible vars plugins
`User Mailing List <http://groups.google.com/group/ansible-devel>`_
Ansible supports a few ways of providing configuration variables, mainly through environment variables, command line switches and an ini file `ansible.cfg`.
Starting at Ansible 2.4 the `ansible-config` utility allows users to see all the configuration settings available, their defaults, how to set them and
where their current value comes from. See :doc:ansible-config for more information.
The configuration file
======================
Changes can be made and used in a configuration file which will be searched for in the following order::
* ANSIBLE_CONFIG (environment variable if set)
* ansible.cfg (in the current directory)
* ~/.ansible.cfg (in the home directory)
* /etc/ansible/ansible.cfg
Ansible will process the above list and use the first file found, all others are ignored.
.. note:: Comments
The configuration file is one variant of an INI format.
Both the hash sign ("#") and semicolon (";") are allowed as
comment markers when the comment starts the line.
However, if the comment is inline with regular values,
only the semicolon is allowed to introduce the comment.
For instance::
# some basic default values...
inventory = /etc/ansible/hosts ; This points to the file that lists your hosts
Common Options
Common Options
==============
==============
This is a copy of the options available from our release, your local install might have extra options due to additional plugins,
you can use the command line utility mentioned above (`ansible-config`) to browse through those.