Ansible 1.2 DocumentationRelease 0.01
Ansible, Inc
May 16, 2017
Contents
1 About Ansible 1
i
ii
CHAPTER 1
About Ansible
Welcome to the Ansible documentation!
Ansible is an IT automation tool. It can configure systems, deploy software, and orchestrate more advanced IT taskssuch as continuous deployments or zero downtime rolling updates.
Ansible’s main goals are simplicity and ease-of-use. It also has a strong focus on security and reliability, featuringa minimum of moving parts, usage of OpenSSH for transport (with an accelerated socket mode and pull modes asalternatives), and a language that is designed around auditability by humans–even those not familiar with the program.
We believe simplicity is relevant to all sizes of environments, so we design for busy users of all types: developers,sysadmins, release engineers, IT managers, and everyone in between. Ansible is appropriate for managing all envi-ronments, from small setups with a handful of instances to enterprise environments with many thousands of instances.
Ansible manages machines in an agent-less manner. There is never a question of how to upgrade remote daemons orthe problem of not being able to manage systems because daemons are uninstalled. Because OpenSSH is one of themost peer-reviewed open source components, security exposure is greatly reduced. Ansible is decentralized–it relieson your existing OS credentials to control access to remote machines. If needed, Ansible can easily connect withKerberos, LDAP, and other centralized authentication management systems.
This documentation covers the current released version of Ansible (1.9.1) and also some development version features(2.0). For recent features, we note in each section the version of Ansible where the feature was added.
Ansible, Inc. releases a new major release of Ansible approximately every two months. The core application evolvessomewhat conservatively, valuing simplicity in language design and setup. However, the community around newmodules and plugins being developed and contributed moves very quickly, typically adding 20 or so new modules ineach release.
Introduction
Before we dive into the really fun parts – playbooks, configuration management, deployment, and orchestration, we’lllearn how to get Ansible installed and cover some basic concepts. We’ll also go over how to execute ad-hoc commandsin parallel across your nodes using /usr/bin/ansible. Additionally, we’ll see what sort of modules are available inAnsible’s core (though you can also write your own, which is also covered later).
1
Ansible 1.2 Documentation, Release 0.01
Installation
Topics
• Installation
– Getting Ansible
– Basics / What Will Be Installed
– What Version To Pick?
– Control Machine Requirements
– Managed Node Requirements
– Installing the Control Machine
* Running From Source
* Latest Release Via Yum
* Latest Releases Via Apt (Ubuntu)
* Latest Releases Via Portage (Gentoo)
* Latest Releases Via pkg (FreeBSD)
* Latest Releases on Mac OSX
* Latest Releases Via OpenCSW (Solaris)
* Latest Releases Via Pacman (Arch Linux)
* Latest Releases Via Pip
* Tarballs of Tagged Releases
Getting Ansible
You may also wish to follow the GitHub project if you have a GitHub account. This is also where we keep the issuetracker for sharing bugs and feature ideas.
Basics / What Will Be Installed
Ansible by default manages machines over the SSH protocol.
Once Ansible is installed, it will not add a database, and there will be no daemons to start or keep running. You onlyneed to install it on one machine (which could easily be a laptop) and it can manage an entire fleet of remote machinesfrom that central point. When Ansible manages remote machines, it does not leave software installed or running onthem, so there’s no real question about how to upgrade Ansible when moving to a new version.
What Version To Pick?
Because it runs so easily from source and does not require any installation of software on remote machines, manyusers will actually track the development version.
2 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Ansible’s release cycles are usually about four months long. Due to this short release cycle, minor bugs will generallybe fixed in the next release versus maintaining backports on the stable branch. Major bugs will still have maintenancereleases when needed, though these are infrequent.
If you are wishing to run the latest released version of Ansible and you are running Red Hat Enterprise Linux (TM),CentOS, Fedora, Debian, or Ubuntu, we recommend using the OS package manager.
For other installation options, we recommend installing via “pip”, which is the Python package manager, though otheroptions are also available.
If you wish to track the development release to use and test the latest features, we will share information about runningfrom source. It’s not necessary to install the program to run from source.
Control Machine Requirements
Currently Ansible can be run from any machine with Python 2.6 or 2.7 installed (Windows isn’t supported for thecontrol machine).
This includes Red Hat, Debian, CentOS, OS X, any of the BSDs, and so on.
Note: As of 2.0 ansible uses a few more file handles to manage its forks, OS X has a very low setting so if you want touse 15 or more forks you’ll need to raise the ulimit, like so sudo launchctl limit maxfiles 1024 2048.Or just any time you see a “Too many open files” error.
Managed Node Requirements
On the managed nodes, you need a way to communicate, normally ssh. By default this uses sftp, if not available youcan switch to scp in ansible.cfg. Also you need Python 2.4 or later, but if you are running less than Python 2.5 on theremotes, you will also need:
• python-simplejson
Note: Ansible’s “raw” module (for executing commands in a quick and dirty way) and the script module don’t evenneed that. So technically, you can use Ansible to install python-simplejson using the raw module, which then allowsyou to use everything else. (That’s jumping ahead though.)
Note: If you have SELinux enabled on remote nodes, you will also want to install libselinux-python on them beforeusing any copy/file/template related functions in Ansible. You can of course still use the yum module in Ansible toinstall this package on remote systems that do not have it.
Note: Python 3 is a slightly different language than Python 2 and most Python programs (including Ansible) are notswitching over yet. However, some Linux distributions (Gentoo, Arch) may not have a Python 2.X interpreter installedby default. On those systems, you should install one, and set the ‘ansible_python_interpreter’ variable in inventory(see Inventory) to point at your 2.X Python. Distributions like Red Hat Enterprise Linux, CentOS, Fedora, and Ubuntuall have a 2.X interpreter installed by default and this does not apply to those distributions. This is also true of nearlyall Unix systems.
If you need to bootstrap these remote systems by installing Python 2.X, using the ‘raw’ module will be ableto do it remotely. For example, ansible myhost --sudo -m raw -a "yum install -y python2python-simplejson"would install Python 2.X and the simplejson module needed to run ansible and its modules.
1.1. Introduction 3
Ansible 1.2 Documentation, Release 0.01
Installing the Control Machine
Running From Source
Ansible is trivially easy to run from a checkout, root permissions are not required to use it and there is no softwareto actually install for Ansible itself. No daemons or database setup are required. Because of this, many users in ourcommunity use the development version of Ansible all of the time, so they can take advantage of new features whenthey are implemented, and also easily contribute to the project. Because there is nothing to install, following thedevelopment version is significantly easier than most open source projects.
Note: If you are intending to use Tower as the Control Machine, do not use a source install. Please use OS packagemanager (eg. apt/yum) or pip to install a stable version.
To install from source.
$ git clone git://github.com/ansible/ansible.git --recursive$ cd ./ansible
Using Bash:
$ source ./hacking/env-setup
Using Fish:
$ . ./hacking/env-setup.fish
If you want to suppress spurious warnings/errors, use:
$ source ./hacking/env-setup -q
If you don’t have pip installed in your version of Python, install pip:
$ sudo easy_install pip
Ansible also uses the following Python modules that need to be installed1:
$ sudo pip install paramiko PyYAML Jinja2 httplib2 six
Note when updating ansible, be sure to not only update the source tree, but also the “submodules” in git which pointat Ansible’s own modules (not the same kind of modules, alas).
$ git pull --rebase$ git submodule update --init --recursive
Once running the env-setup script you’ll be running from checkout and the default inventory file will be/etc/ansible/hosts. You can optionally specify an inventory file (see Inventory) other than /etc/ansible/hosts:
$ echo "127.0.0.1" > ~/ansible_hosts$ export ANSIBLE_INVENTORY=~/ansible_hosts
Note: ANSIBLE_INVENTORY is available starting at 1.9 and substitutes the deprecated ANSIBLE_HOSTS
1 If you have issues with the “pycrypto” package install on Mac OSX, which is included as a dependency for paramiko, then you may need totry “CC=clang sudo -E pip install pycrypto”.
4 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
You can read more about the inventory file in later parts of the manual.
Now let’s test things with a ping command:
$ ansible all -m ping --ask-pass
You can also use “sudo make install” if you wish.
Latest Release Via Yum
RPMs are available from yum for EPEL 6, 7, and currently supported Fedora distributions.
Ansible itself can manage earlier operating systems that contain Python 2.4 or higher (so also EL5).
Fedora users can install Ansible directly, though if you are using RHEL or CentOS and have not already done so,configure EPEL
# install the epel-release RPM if needed on CentOS, RHEL, or Scientific Linux$ sudo yum install ansible
You can also build an RPM yourself. From the root of a checkout or tarball, use the make rpm command to build anRPM you can distribute and install. Make sure you have rpm-build, make, and python2-devel installed.
$ git clone git://github.com/ansible/ansible.git --recursive$ cd ./ansible$ make rpm$ sudo rpm -Uvh ./rpm-build/ansible-*.noarch.rpm
Latest Releases Via Apt (Ubuntu)
Ubuntu builds are available in a PPA here.
To configure the PPA on your machine and install ansible run these commands:
$ sudo apt-get install software-properties-common$ sudo apt-add-repository ppa:ansible/ansible$ sudo apt-get update$ sudo apt-get install ansible
Note: On older Ubuntu distributions, “software-properties-common” is called “python-software-properties”.
Debian/Ubuntu packages can also be built from the source checkout, run:
$ make deb
You may also wish to run from source to get the latest, which is covered above.
Latest Releases Via Portage (Gentoo)
$ emerge -av app-admin/ansible
To install the newest version, you may need to unmask the ansible package prior to emerging:
1.1. Introduction 5
Ansible 1.2 Documentation, Release 0.01
$ echo 'app-admin/ansible' >> /etc/portage/package.accept_keywords
Note: If you have Python 3 as a default Python slot on your Gentoo nodes (default setting), then you must setansible_python_interpreter = /usr/bin/python2 in your group or inventory variables.
Latest Releases Via pkg (FreeBSD)
$ sudo pkg install ansible
You may also wish to install from ports, run:
$ sudo make -C /usr/ports/sysutils/ansible install
Latest Releases on Mac OSX
The preferred way to install ansible on a Mac is via pip.
The instructions can be found in Latest Releases Via Pip section.
Latest Releases Via OpenCSW (Solaris)
Ansible is available for Solaris as SysV package from OpenCSW.
# pkgadd -d http://get.opencsw.org/now# /opt/csw/bin/pkgutil -i ansible
Latest Releases Via Pacman (Arch Linux)
Ansible is available in the Community repository:
$ pacman -S ansible
The AUR has a PKGBUILD for pulling directly from Github called ansible-git.
Also see the Ansible page on the ArchWiki.
Note: If you have Python 3 as a default Python slot on your Arch nodes (default setting), then you must setansible_python_interpreter = /usr/bin/python2 in your group or inventory variables.
Latest Releases Via Pip
Ansible can be installed via “pip”, the Python package manager. If ‘pip’ isn’t already available in your version ofPython, you can get pip by:
$ sudo easy_install pip
6 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Then install Ansible with1:
$ sudo pip install ansible
If you are installing on OS X Mavericks, you may encounter some noise from your compiler. A workaround is to dothe following:
$ sudo CFLAGS=-Qunused-arguments CPPFLAGS=-Qunused-arguments pip install ansible
Readers that use virtualenv can also install Ansible under virtualenv, though we’d recommend to not worry about itand just install Ansible globally. Do not use easy_install to install ansible directly.
Tarballs of Tagged Releases
Packaging Ansible or wanting to build a local package yourself, but don’t want to do a git checkout? Tarballs ofreleases are available on the Ansible downloads page.
These releases are also tagged in the git repository with the release version.
See also:
Introduction To Ad-Hoc Commands Examples of basic commands
Playbooks Learning ansible’s configuration management language
Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
irc.freenode.net #ansible IRC chat channel
Getting Started
Topics
• Getting Started
– Foreword
– Remote Connection Information
– Your first commands
– Host Key Checking
Foreword
Now that you’ve read Installation and installed Ansible, it’s time to dig in and get started with some commands.
What we are showing first are not the powerful configuration/deployment/orchestration features of Ansible. Thesefeatures are handled by playbooks which are covered in a separate section.
This section is about how to initially get going. Once you have these concepts down, read Introduction To Ad-HocCommands for some more detail, and then you’ll be ready to dive into playbooks and explore the most interestingparts!
1.1. Introduction 7
Ansible 1.2 Documentation, Release 0.01
Remote Connection Information
Before we get started, it’s important to understand how Ansible communicates with remote machines over SSH.
By default, Ansible 1.3 and later will try to use native OpenSSH for remote communication when possible. Thisenables ControlPersist (a performance feature), Kerberos, and options in ~/.ssh/config such as Jump Host setup. How-ever, when using Enterprise Linux 6 operating systems as the control machine (Red Hat Enterprise Linux and deriva-tives such as CentOS), the version of OpenSSH may be too old to support ControlPersist. On these operating systems,Ansible will fallback into using a high-quality Python implementation of OpenSSH called ‘paramiko’. If you wish touse features like Kerberized SSH and more, consider using Fedora, OS X, or Ubuntu as your control machine until anewer version of OpenSSH is available for your platform – or engage ‘accelerated mode’ in Ansible. See AcceleratedMode.
In releases up to and including Ansible 1.2, the default was strictly paramiko. Native SSH had to be explicitly selectedwith the -c ssh option or set in the configuration file.
Occasionally you’ll encounter a device that doesn’t support SFTP. This is rare, but should it occur, you can switch toSCP mode in Configuration file.
When speaking with remote machines, Ansible by default assumes you are using SSH keys. SSH keys are encouragedbut password authentication can also be used where needed by supplying the option --ask-pass. If using sudofeatures and when sudo requires a password, also supply --ask-sudo-pass.
While it may be common sense, it is worth sharing: Any management system benefits from being run near the ma-chines being managed. If you are running Ansible in a cloud, consider running it from a machine inside that cloud. Inmost cases this will work better than on the open Internet.
As an advanced topic, Ansible doesn’t just have to connect remotely over SSH. The transports are pluggable, and thereare options for managing things locally, as well as managing chroot, lxc, and jail containers. A mode called ‘ansible-pull’ can also invert the system and have systems ‘phone home’ via scheduled git checkouts to pull configurationdirectives from a central repository.
Your first commands
Now that you’ve installed Ansible, it’s time to get started with some basics.
Edit (or create) /etc/ansible/hosts and put one or more remote systems in it. Your public SSH key should be located inauthorized_keys on those systems:
192.168.1.50aserver.example.orgbserver.example.org
This is an inventory file, which is also explained in greater depth here: Inventory.
We’ll assume you are using SSH keys for authentication. To set up SSH agent to avoid retyping passwords, you cando:
$ ssh-agent bash$ ssh-add ~/.ssh/id_rsa
(Depending on your setup, you may wish to use Ansible’s --private-key option to specify a pem file instead)
Now ping all your nodes:
$ ansible all -m ping
Ansible will attempt to remote connect to the machines using your current user name, just like SSH would. To overridethe remote user name, just use the ‘-u’ parameter.
8 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
If you would like to access sudo mode, there are also flags to do that:
# as bruce$ ansible all -m ping -u bruce# as bruce, sudoing to root$ ansible all -m ping -u bruce --sudo# as bruce, sudoing to batman$ ansible all -m ping -u bruce --sudo --sudo-user batman
# With latest version of ansible `sudo` is deprecated so use become# as bruce, sudoing to root$ ansible all -m ping -u bruce -b# as bruce, sudoing to batman$ ansible all -m ping -u bruce -b --become-user batman
(The sudo implementation is changeable in Ansible’s configuration file if you happen to want to use a sudo replace-ment. Flags passed to sudo (like -H) can also be set there.)
Now run a live command on all of your nodes:
$ ansible all -a "/bin/echo hello"
Congratulations! You’ve just contacted your nodes with Ansible. It’s soon going to be time to: read about some morereal-world cases in Introduction To Ad-Hoc Commands, explore what you can do with different modules, and to learnabout the Ansible Playbooks language. Ansible is not just about running commands, it also has powerful configurationmanagement and deployment features. There’s more to explore, but you already have a fully working infrastructure!
Host Key Checking
Ansible 1.2.1 and later have host key checking enabled by default.
If a host is reinstalled and has a different key in ‘known_hosts’, this will result in an error message until corrected. Ifa host is not initially in ‘known_hosts’ this will result in prompting for confirmation of the key, which results in aninteractive experience if using Ansible, from say, cron. You might not want this.
If you understand the implications and wish to disable this behavior, you can do so by editing /etc/ansible/ansible.cfgor ~/.ansible.cfg:
[defaults]host_key_checking = False
Alternatively this can be set by an environment variable:
$ export ANSIBLE_HOST_KEY_CHECKING=False
Also note that host key checking in paramiko mode is reasonably slow, therefore switching to ‘ssh’ is also recom-mended when using this feature. Ansible will log some information about module arguments on the remote systemin the remote syslog, unless a task or play is marked with a “no_log: True” attribute. This is explained later.
To enable basic logging on the control machine see Configuration file document and set the ‘log_path’ configurationfile setting. Enterprise users may also be interested in Ansible Tower. Tower provides a very robust database loggingfeature where it is possible to drill down and see history based on hosts, projects, and particular inventories over time– explorable both graphically and through a REST API.
See also:
Inventory More information about inventory
Introduction To Ad-Hoc Commands Examples of basic commands
1.1. Introduction 9
Ansible 1.2 Documentation, Release 0.01
Playbooks Learning Ansible’s configuration management language
Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
irc.freenode.net #ansible IRC chat channel
Inventory
Topics
• Inventory
– Hosts and Groups
– Host Variables
– Group Variables
– Groups of Groups, and Group Variables
– Splitting Out Host and Group Specific Data
– List of Behavioral Inventory Parameters
Ansible works against multiple systems in your infrastructure at the same time. It does this by selecting portions ofsystems listed in Ansible’s inventory file, which defaults to being saved in the location /etc/ansible/hosts.
Not only is this inventory configurable, but you can also use multiple inventory files at the same time (explained below)and also pull inventory from dynamic or cloud sources, as described in Dynamic Inventory.
Hosts and Groups
The format for /etc/ansible/hosts is an INI-like format and looks like this:
mail.example.com
[webservers]foo.example.combar.example.com
[dbservers]one.example.comtwo.example.comthree.example.com
The things in brackets are group names, which are used in classifying systems and deciding what systems you arecontrolling at what times and for what purpose.
It is ok to put systems in more than one group, for instance a server could be both a webserver and a dbserver. If youdo, note that variables will come from all of the groups they are a member of, and variable precedence is detailed in alater chapter.
If you have hosts that run on non-standard SSH ports you can put the port number after the hostname with a colon.Ports listed in your SSH config file won’t be used with the paramiko connection but will be used with the opensshconnection.
To make things explicit, it is suggested that you set them if things are not running on the default port:
10 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
badwolf.example.com:5309
Suppose you have just static IPs and want to set up some aliases that live in your host file, or you are connectingthrough tunnels. You can also describe hosts like this:
jumper ansible_port=5555 ansible_host=192.168.1.50
In the above example, trying to ansible against the host alias “jumper” (which may not even be a real hostname)will contact 192.168.1.50 on port 5555. Note that this is using a feature of the inventory file to define some specialvariables. Generally speaking this is not the best way to define variables that describe your system policy, but we’llshare suggestions on doing this later. We’re just getting started.
Adding a lot of hosts? If you have a lot of hosts following similar patterns you can do this rather than listing eachhostname:
[webservers]www[01:50].example.com
For numeric patterns, leading zeros can be included or removed, as desired. Ranges are inclusive. You can also definealphabetic ranges:
[databases]db-[a:f].example.com
Note: Ansible 2.0 has deprecated the “ssh” from ansible_ssh_user, ansible_ssh_host, andansible_ssh_port to become ansible_user, ansible_host, and ansible_port. If you are usinga version of Ansible prior to 2.0, you should continue using the older style variables (ansible_ssh_*). Theseshorter variables are ignored, without warning, in older versions of Ansible.
You can also select the connection type and user on a per host basis:
[targets]
localhost ansible_connection=localother1.example.com ansible_connection=ssh ansible_user=mpdehaanother2.example.com ansible_connection=ssh ansible_user=mdehaan
As mentioned above, setting these in the inventory file is only a shorthand, and we’ll discuss how to store them inindividual files in the ‘host_vars’ directory a bit later on.
Host Variables
As alluded to above, it is easy to assign variables to hosts that will be used later in playbooks:
[atlanta]host1 http_port=80 maxRequestsPerChild=808host2 http_port=303 maxRequestsPerChild=909
Group Variables
Variables can also be applied to an entire group at once:
1.1. Introduction 11
Ansible 1.2 Documentation, Release 0.01
[atlanta]host1host2
[atlanta:vars]ntp_server=ntp.atlanta.example.comproxy=proxy.atlanta.example.com
Groups of Groups, and Group Variables
It is also possible to make groups of groups using the :children suffix. Just like above, you can apply variablesusing :vars:
[atlanta]host1host2
[raleigh]host2host3
[southeast:children]atlantaraleigh
[southeast:vars]some_server=foo.southeast.example.comhalon_system_timeout=30self_destruct_countdown=60escape_pods=2
[usa:children]southeastnortheastsouthwestnorthwest
If you need to store lists or hash data, or prefer to keep host and group specific variables separate from the inventoryfile, see the next section.
Splitting Out Host and Group Specific Data
The preferred practice in Ansible is actually not to store variables in the main inventory file.
In addition to storing variables directly in the INI file, host and group variables can be stored in individual files relativeto the inventory file.
These variable files are in YAML format. Valid file extensions include ‘.yml’, ‘.yaml’, ‘.json’, or no file extension.See YAML Syntax if you are new to YAML.
Assuming the inventory file path is:
/etc/ansible/hosts
If the host is named ‘foosball’, and in groups ‘raleigh’ and ‘webservers’, variables in YAML files at the followinglocations will be made available to the host:
12 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
/etc/ansible/group_vars/raleigh # can optionally end in '.yml', '.yaml', or '.json'/etc/ansible/group_vars/webservers/etc/ansible/host_vars/foosball
For instance, suppose you have hosts grouped by datacenter, and each datacenter uses some different servers. The datain the groupfile ‘/etc/ansible/group_vars/raleigh’ for the ‘raleigh’ group might look like:
---ntp_server: acme.example.orgdatabase_server: storage.example.org
It is ok if these files do not exist, as this is an optional feature.
As an advanced use-case, you can create directories named after your groups or hosts, and Ansible will read all thefiles in these directories. An example with the ‘raleigh’ group:
/etc/ansible/group_vars/raleigh/db_settings/etc/ansible/group_vars/raleigh/cluster_settings
All hosts that are in the ‘raleigh’ group will have the variables defined in these files available to them. This can be veryuseful to keep your variables organized when a single file starts to be too big, or when you want to use Ansible Vaulton a part of a group’s variables. Note that this only works on Ansible 1.4 or later.
Tip: In Ansible 1.2 or later the group_vars/ and host_vars/ directories can exist in either the playbook directory OR theinventory directory. If both paths exist, variables in the playbook directory will override variables set in the inventorydirectory.
Tip: Keeping your inventory file and variables in a git repo (or other version control) is an excellent way to trackchanges to your inventory and host variables.
List of Behavioral Inventory Parameters
As alluded to above, setting the following variables controls how ansible interacts with remote hosts.
Host connection:
ansible_connectionConnection type to the host. Candidates are local, smart, ssh or paramiko. The
→˓default is smart.
Note: Ansible 2.0 has deprecated the “ssh” from ansible_ssh_user, ansible_ssh_host, andansible_ssh_port to become ansible_user, ansible_host, and ansible_port. If you are usinga version of Ansible prior to 2.0, you should continue using the older style variables (ansible_ssh_*). Theseshorter variables are ignored, without warning, in older versions of Ansible.
SSH connection:
ansible_hostThe name of the host to connect to, if different from the alias you wish to give to
→˓it.ansible_port
The ssh port number, if not 22ansible_user
The default ssh user name to use.ansible_ssh_pass
1.1. Introduction 13
Ansible 1.2 Documentation, Release 0.01
The ssh password to use (this is insecure, we strongly recommend using --ask-pass→˓or SSH keys)ansible_ssh_private_key_file
Private key file used by ssh. Useful if using multiple keys and you don't want to→˓use SSH agent.ansible_ssh_common_args
This setting is always appended to the default command line forsftp, scp, and ssh. Useful to configure a ``ProxyCommand`` for acertain host (or group).
ansible_sftp_extra_argsThis setting is always appended to the default sftp command line.
ansible_scp_extra_argsThis setting is always appended to the default scp command line.
ansible_ssh_extra_argsThis setting is always appended to the default ssh command line.
ansible_ssh_pipeliningDetermines whether or not to use SSH pipelining. This can override the``pipelining`` setting in ``ansible.cfg``.
Privilege escalation (see Ansible Privilege Escalation for further details):
ansible_becomeEquivalent to ansible_sudo or ansible_su, allows to force privilege escalation
ansible_become_methodAllows to set privilege escalation method
ansible_become_userEquivalent to ansible_sudo_user or ansible_su_user, allows to set the user you
→˓become through privilege escalationansible_become_pass
Equivalent to ansible_sudo_pass or ansible_su_pass, allows you to set the privilege→˓escalation password
Remote host environment parameters:
ansible_shell_typeThe shell type of the target system. Commands are formatted using 'sh'-style syntax
→˓by default. Setting this to 'csh' or 'fish' will cause commands executed on target→˓systems to follow those shell's syntax instead.ansible_python_interpreter
The target host python path. This is useful for systems with morethan one Python or not located at "/usr/bin/python" such as \*BSD, or where /usr/
→˓bin/pythonis not a 2.X series Python. We do not use the "/usr/bin/env" mechanism as that
→˓requires the remote user'spath to be set right and also assumes the "python" executable is named python,
→˓where the executable mightbe named something like "python26".
ansible\_\*\_interpreterWorks for anything such as ruby or perl and works just like ansible_python_
→˓interpreter.This replaces shebang of modules which will run on that host.
Examples from a host file:
some_host ansible_port=2222 ansible_user=manageraws_host ansible_ssh_private_key_file=/home/example/.ssh/aws.pemfreebsd_host ansible_python_interpreter=/usr/local/bin/pythonruby_module_host ansible_ruby_interpreter=/usr/bin/ruby.1.9.3
14 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
See also:
Dynamic Inventory Pulling inventory from dynamic sources, such as cloud providers
Introduction To Ad-Hoc Commands Examples of basic commands
Playbooks Learning Ansible’s configuration, deployment, and orchestration language.
Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
irc.freenode.net #ansible IRC chat channel
Dynamic Inventory
Topics
• Dynamic Inventory
– Example: The Cobbler External Inventory Script
– Example: AWS EC2 External Inventory Script
– Other inventory scripts
– Using Multiple Inventory Sources
– Static Groups of Dynamic Groups
Often a user of a configuration management system will want to keep inventory in a different software system. Ansibleprovides a basic text-based system as described in Inventory but what if you want to use something else?
Frequent examples include pulling inventory from a cloud provider, LDAP, Cobbler, or a piece of expensive enterpriseyCMDB software.
Ansible easily supports all of these options via an external inventory system. The contrib/inventory directory containssome of these already – including options for EC2/Eucalyptus, Rackspace Cloud, and OpenStack, examples of someof which will be detailed below.
Ansible Tower also provides a database to store inventory results that is both web and REST Accessible. Tower syncswith all Ansible dynamic inventory sources you might be using, and also includes a graphical inventory editor. Byhaving a database record of all of your hosts, it’s easy to correlate past event history and see which ones have hadfailures on their last playbook runs.
For information about writing your own dynamic inventory source, see Developing Dynamic Inventory Sources.
Example: The Cobbler External Inventory Script
It is expected that many Ansible users with a reasonable amount of physical hardware may also be Cobbler users.(note: Cobbler was originally written by Michael DeHaan and is now led by James Cammarata, who also works forAnsible, Inc).
While primarily used to kickoff OS installations and manage DHCP and DNS, Cobbler has a generic layer that allowsit to represent data for multiple configuration management systems (even at the same time), and has been referred toas a ‘lightweight CMDB’ by some admins.
To tie Ansible’s inventory to Cobbler (optional), copy this script to /etc/ansible and chmod +x the file. cobblerd willnow need to be running when you are using Ansible and you’ll need to use Ansible’s -i command line option (e.g. -i/etc/ansible/cobbler.py). This particular script will communicate with Cobbler using Cobbler’s XMLRPCAPI.
1.1. Introduction 15
Ansible 1.2 Documentation, Release 0.01
First test the script by running /etc/ansible/cobbler.py directly. You should see some JSON data output,but it may not have anything in it just yet.
Let’s explore what this does. In cobbler, assume a scenario somewhat like the following:
cobbler profile add --name=webserver --distro=CentOS6-x86_64cobbler profile edit --name=webserver --mgmt-classes="webserver" --ksmeta="a=2 b=3"cobbler system edit --name=foo --dns-name="foo.example.com" --mgmt-classes="atlanta" -→˓-ksmeta="c=4"cobbler system edit --name=bar --dns-name="bar.example.com" --mgmt-classes="atlanta" -→˓-ksmeta="c=5"
In the example above, the system ‘foo.example.com’ will be addressable by ansible directly, but will also be address-able when using the group names ‘webserver’ or ‘atlanta’. Since Ansible uses SSH, we’ll try to contact system fooover ‘foo.example.com’, only, never just ‘foo’. Similarly, if you try “ansible foo” it wouldn’t find the system... but“ansible ‘foo*”’ would, because the system DNS name starts with ‘foo’.
The script doesn’t just provide host and group info. In addition, as a bonus, when the ‘setup’ module is run (whichhappens automatically when using playbooks), the variables ‘a’, ‘b’, and ‘c’ will all be auto-populated in the templates:
# file: /srv/motd.j2Welcome, I am templated with a value of a={{ a }}, b={{ b }}, and c={{ c }}
Which could be executed just like this:
ansible webserver -m setupansible webserver -m template -a "src=/tmp/motd.j2 dest=/etc/motd"
Note: The name ‘webserver’ came from cobbler, as did the variables for the config file. You can still pass in yourown variables like normal in Ansible, but variables from the external inventory script will override any that have thesame name.
So, with the template above (motd.j2), this would result in the following data being written to /etc/motd for system‘foo’:
Welcome, I am templated with a value of a=2, b=3, and c=4
And on system ‘bar’ (bar.example.com):
Welcome, I am templated with a value of a=2, b=3, and c=5
And technically, though there is no major good reason to do it, this also works too:
ansible webserver -m shell -a "echo {{ a }}"
So in other words, you can use those variables in arguments/actions as well.
Example: AWS EC2 External Inventory Script
If you use Amazon Web Services EC2, maintaining an inventory file might not be the best approach, because hostsmay come and go over time, be managed by external applications, or you might even be using AWS autoscaling. Forthis reason, you can use the EC2 external inventory script.
You can use this script in one of two ways. The easiest is to use Ansible’s -i command line option and specify thepath to the script after marking it executable:
16 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
ansible -i ec2.py -u ubuntu us-east-1d -m ping
The second option is to copy the script to /etc/ansible/hosts and chmod +x it. You will also need to copy the ec2.inifile to /etc/ansible/ec2.ini. Then you can run ansible as you would normally.
To successfully make an API call to AWS, you will need to configure Boto (the Python interface to AWS). There area variety of methods available, but the simplest is just to export two environment variables:
export AWS_ACCESS_KEY_ID='AK123'export AWS_SECRET_ACCESS_KEY='abc123'
You can test the script by itself to make sure your config is correct:
cd contrib/inventory./ec2.py --list
After a few moments, you should see your entire EC2 inventory across all regions in JSON.
If you use boto profiles to manage multiple AWS accounts, you can pass --profile PROFILE name to the ec2.py script. An example profile might be:
[profile dev]aws_access_key_id = <dev access key>aws_secret_access_key = <dev secret key>
[profile prod]aws_access_key_id = <prod access key>aws_secret_access_key = <prod secret key>
You can then run ec2.py --profile prod to get the inventory for the prod account, this option is not supportedby anisble-playbook though. But you can use the AWS_PROFILE variable - e.g. AWS_PROFILE=prodansible-playbook -i ec2.py myplaybook.yml
Since each region requires its own API call, if you are only using a small set of regions, feel free to edit ec2.iniand list only the regions you are interested in. There are other config options in ec2.ini including cache control,and destination variables.
At their heart, inventory files are simply a mapping from some name to a destination address. The default ec2.inisettings are configured for running Ansible from outside EC2 (from your laptop for example) – and this is not the mostefficient way to manage EC2.
If you are running Ansible from within EC2, internal DNS names and IP addresses may make more sense than publicDNS names. In this case, you can modify the destination_variable in ec2.ini to be the private DNS nameof an instance. This is particularly important when running Ansible within a private subnet inside a VPC, where theonly way to access an instance is via its private IP address. For VPC instances, vpc_destination_variable in ec2.iniprovides a means of using which ever boto.ec2.instance variable makes the most sense for your use case.
The EC2 external inventory provides mappings to instances from several groups:
Global All instances are in group ec2.
Instance ID These are groups of one since instance IDs are unique. e.g. i-00112233 i-a1b1c1d1
Region A group of all instances in an AWS region. e.g. us-east-1 us-west-2
Availability Zone A group of all instances in an availability zone. e.g. us-east-1a us-east-1b
Security Group Instances belong to one or more security groups. A group is created for each security group,with all characters except alphanumerics, dashes (-) converted to underscores (_). Each group is pre-fixed by security_group_ e.g. security_group_default security_group_webserverssecurity_group_Pete_s_Fancy_Group
1.1. Introduction 17
Ansible 1.2 Documentation, Release 0.01
Tags Each instance can have a variety of key/value pairs associated with it called Tags. Themost common tag key is ‘Name’, though anything is possible. Each key/value pair is itsown group of instances, again with special characters converted to underscores, in the formattag_KEY_VALUE e.g. tag_Name_Web can be used as is tag_Name_redis-master-001 becomestag_Name_redis_master_001 tag_aws_cloudformation_logical-id_WebServerGroupbecomes tag_aws_cloudformation_logical_id_WebServerGroup
When the Ansible is interacting with a specific server, the EC2 inventory script is called again with the --hostHOST option. This looks up the HOST in the index cache to get the instance ID, and then makes an API call to AWSto get information about that specific instance. It then makes information about that instance available as variables toyour playbooks. Each variable is prefixed by ec2_. Here are some of the variables available:
• ec2_architecture
• ec2_description
• ec2_dns_name
• ec2_id
• ec2_image_id
• ec2_instance_type
• ec2_ip_address
• ec2_kernel
• ec2_key_name
• ec2_launch_time
• ec2_monitored
• ec2_ownerId
• ec2_placement
• ec2_platform
• ec2_previous_state
• ec2_private_dns_name
• ec2_private_ip_address
• ec2_public_dns_name
• ec2_ramdisk
• ec2_region
• ec2_root_device_name
• ec2_root_device_type
• ec2_security_group_ids
• ec2_security_group_names
• ec2_spot_instance_request_id
• ec2_state
• ec2_state_code
• ec2_state_reason
• ec2_status
18 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• ec2_subnet_id
• ec2_tag_Name
• ec2_tenancy
• ec2_virtualization_type
• ec2_vpc_id
Both ec2_security_group_ids and ec2_security_group_names are comma-separated lists of all secu-rity groups. Each EC2 tag is a variable in the format ec2_tag_KEY.
To see the complete list of variables available for an instance, run the script by itself:
cd contrib/inventory./ec2.py --host ec2-12-12-12-12.compute-1.amazonaws.com
Note that the AWS inventory script will cache results to avoid repeated API calls, and this cache setting is configurablein ec2.ini. To explicitly clear the cache, you can run the ec2.py script with the --refresh-cache parameter:
# ./ec2.py --refresh-cache
Other inventory scripts
In addition to Cobbler and EC2, inventory scripts are also available for:
BSD JailsDigitalOceanGoogle Compute EngineLinodeOpenShiftOpenStack NovaRed Hat's SpaceWalkVagrant (not to be confused with the provisioner in vagrant, which is preferred)Zabbix
Sections on how to use these in more detail will be added over time, but by looking at the “contrib/inventory” directoryof the Ansible checkout it should be very obvious how to use them. The process for the AWS inventory script is thesame.
If you develop an interesting inventory script that might be general purpose, please submit a pull request – we’d likelybe glad to include it in the project.
Using Multiple Inventory Sources
If the location given to -i in Ansible is a directory (or as so configured in ansible.cfg), Ansible can use multipleinventory sources at the same time. When doing so, it is possible to mix both dynamic and statically managed inventorysources in the same ansible run. Instant hybrid cloud!
Static Groups of Dynamic Groups
When defining groups of groups in the static inventory file, the child groups must also be defined in the static inventoryfile, or ansible will return an error. If you want to define a static group of dynamic child groups, define the dynamicgroups as empty in the static inventory file. For example:
1.1. Introduction 19
Ansible 1.2 Documentation, Release 0.01
[tag_Name_staging_foo]
[tag_Name_staging_bar]
[staging:children]tag_Name_staging_footag_Name_staging_bar
See also:
Inventory All about static inventory files
Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
irc.freenode.net #ansible IRC chat channel
Patterns
Topics
• Patterns
Patterns in Ansible are how we decide which hosts to manage. This can mean what hosts to communicate with, but interms of Playbooks it actually means what hosts to apply a particular configuration or IT process to.
We’ll go over how to use the command line in Introduction To Ad-Hoc Commands section, however, basically it lookslike this:
ansible <pattern_goes_here> -m <module_name> -a <arguments>
Such as:
ansible webservers -m service -a "name=httpd state=restarted"
A pattern usually refers to a set of groups (which are sets of hosts) – in the above case, machines in the “webservers”group.
Anyway, to use Ansible, you’ll first need to know how to tell Ansible which hosts in your inventory to talk to. This isdone by designating particular host names or groups of hosts.
The following patterns are equivalent and target all hosts in the inventory:
all
*
It is also possible to address a specific host or set of hosts by name:
one.example.comone.example.com:two.example.com192.168.1.50192.168.1.*
The following patterns address one or more groups. Groups separated by a comma indicate an “OR” configuration.This means the host may be in either one group or the other:
20 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
webserverswebservers:dbservers
You can exclude groups as well, for instance, all machines must be in the group webservers but not in the groupphoenix:
webservers:!phoenix
You can also specify the intersection of two groups. This would mean the hosts must be in the group webservers andthe host must also be in the group staging:
webservers:&staging
You can do combinations:
webservers:dbservers:&staging:!phoenix
The above configuration means “all machines in the groups ‘webservers’ and ‘dbservers’ are to be managed if they arein the group ‘staging’ also, but the machines are not to be managed if they are in the group ‘phoenix’ ... whew!
You can also use variables if you want to pass some group specifiers via the “-e” argument to ansible-playbook, butthis is uncommonly used:
webservers:!{{excluded}}:&{{required}}
You also don’t have to manage by strictly defined groups. Individual host names, IPs and groups, can also be referencedusing wildcards:
*.example.com
*.com
It’s also ok to mix wildcard patterns and groups at the same time:
one*.com:dbservers
You can select a host or subset of hosts from a group by their position. For example, given the following group:
[webservers]cobwebwebbingweber
You can refer to hosts within the group by adding a subscript to the group name:
webservers[0] # == cobwebwebservers[-1] # == weberwebservers[0:1] # == webservers[0],webservers[1]
# == cobweb,webbingwebservers[1:] # == webbing,weber
Most people don’t specify patterns as regular expressions, but you can. Just start the pattern with a ‘~’:
~(web|db).*\.example\.com
While we’re jumping a bit ahead, additionally, you can add an exclusion criteria just by supplying the --limit flagto /usr/bin/ansible or /usr/bin/ansible-playbook:
1.1. Introduction 21
Ansible 1.2 Documentation, Release 0.01
ansible-playbook site.yml --limit datacenter2
And if you want to read the list of hosts from a file, prefix the file name with ‘@’. Since Ansible 1.2:
ansible-playbook site.yml --limit @retry_hosts.txt
Easy enough. See Introduction To Ad-Hoc Commands and then Playbooks for how to apply this knowledge.
Note: With the exception of version 1.9, you can use ‘,’ instead of ‘:’ as a host list separator. The ‘,’ is preferedspecially when dealing with ranges and ipv6.
Note: As of 2.0 the ‘;’ is deprecated as a host list separator.
See also:
Introduction To Ad-Hoc Commands Examples of basic commands
Playbooks Learning ansible’s configuration management language
Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
irc.freenode.net #ansible IRC chat channel
Introduction To Ad-Hoc Commands
Topics
• Introduction To Ad-Hoc Commands
– Parallelism and Shell Commands
– File Transfer
– Managing Packages
– Users and Groups
– Deploying From Source Control
– Managing Services
– Time Limited Background Operations
– Gathering Facts
The following examples show how to use /usr/bin/ansible for running ad hoc tasks.
What’s an ad-hoc command?
An ad-hoc command is something that you might type in to do something really quick, but don’t want to save for later.
This is a good place to start to understand the basics of what Ansible can do prior to learning the playbooks language– ad-hoc commands can also be used to do quick things that you might not necessarily want to write a full playbookfor.
Generally speaking, the true power of Ansible lies in playbooks. Why would you use ad-hoc tasks versus playbooks?
22 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
For instance, if you wanted to power off all of your lab for Christmas vacation, you could execute a quick one-liner inAnsible without writing a playbook.
For configuration management and deployments, though, you’ll want to pick up on using ‘/usr/bin/ansible-playbook’– the concepts you will learn here will port over directly to the playbook language.
(See Playbooks for more information about those)
If you haven’t read Inventory already, please look that over a bit first and then we’ll get going.
Parallelism and Shell Commands
Arbitrary example.
Let’s use Ansible’s command line tool to reboot all web servers in Atlanta, 10 at a time. First, let’s set up SSH-agentso it can remember our credentials:
$ ssh-agent bash$ ssh-add ~/.ssh/id_rsa
If you don’t want to use ssh-agent and want to instead SSH with a password instead of keys, you can with--ask-pass (-k), but it’s much better to just use ssh-agent.
Now to run the command on all servers in a group, in this case, atlanta, in 10 parallel forks:
$ ansible atlanta -a "/sbin/reboot" -f 10
/usr/bin/ansible will default to running from your user account. If you do not like this behavior, pass in “-u username”.If you want to run commands as a different user, it looks like this:
$ ansible atlanta -a "/usr/bin/foo" -u username
Often you’ll not want to just do things from your user account. If you want to run commands through sudo:
$ ansible atlanta -a "/usr/bin/foo" -u username --sudo [--ask-sudo-pass]
Use --ask-sudo-pass (-K) if you are not using passwordless sudo. This will interactively prompt you for thepassword to use. Use of passwordless sudo makes things easier to automate, but it’s not required.
It is also possible to sudo to a user other than root using --sudo-user (-U):
$ ansible atlanta -a "/usr/bin/foo" -u username -U otheruser [--ask-sudo-pass]
Note: Rarely, some users have security rules where they constrain their sudo environment to running specific com-mand paths only. This does not work with ansible’s no-bootstrapping philosophy and hundreds of different modules. Ifdoing this, use Ansible from a special account that does not have this constraint. One way of doing this without sharingaccess to unauthorized users would be gating Ansible with Ansible Tower, which can hold on to an SSH credential andlet members of certain organizations use it on their behalf without having direct access.
Ok, so those are basics. If you didn’t read about patterns and groups yet, go back and read Patterns.
The -f 10 in the above specifies the usage of 10 simultaneous processes to use. You can also set this in Configurationfile to avoid setting it again. The default is actually 5, which is really small and conservative. You are probably goingto want to talk to a lot more simultaneous hosts so feel free to crank this up. If you have more hosts than the value setfor the fork count, Ansible will talk to them, but it will take a little longer. Feel free to push this value as high as yoursystem can handle it!
1.1. Introduction 23
Ansible 1.2 Documentation, Release 0.01
You can also select what Ansible “module” you want to run. Normally commands also take a -m for module name,but the default module name is ‘command’, so we didn’t need to specify that all of the time. We’ll use -m in laterexamples to run some other About Modules.
Note: The command - Executes a command on a remote node module does not support shell variables and things likepiping. If we want to execute a module using a shell, use the ‘shell’ module instead. Read more about the differenceson the About Modules page.
Using the shell - Execute commands in nodes. module looks like this:
$ ansible raleigh -m shell -a 'echo $TERM'
When running any command with the Ansible ad hoc CLI (as opposed to Playbooks), pay particular attention to shellquoting rules, so the local shell doesn’t eat a variable before it gets passed to Ansible. For example, using doublerather than single quotes in the above example would evaluate the variable on the box you were on.
So far we’ve been demoing simple command execution, but most Ansible modules usually do not work like simplescripts. They make the remote system look like a state, and run the commands necessary to get it there. This iscommonly referred to as ‘idempotence’, and is a core design goal of Ansible. However, we also recognize thatrunning arbitrary commands is equally important, so Ansible easily supports both.
File Transfer
Here’s another use case for the /usr/bin/ansible command line. Ansible can SCP lots of files to multiple machines inparallel.
To transfer a file directly to many servers:
$ ansible atlanta -m copy -a "src=/etc/hosts dest=/tmp/hosts"
If you use playbooks, you can also take advantage of the template module, which takes this another step further.(See module and playbook documentation).
The file module allows changing ownership and permissions on files. These same options can be passed directly tothe copy module as well:
$ ansible webservers -m file -a "dest=/srv/foo/a.txt mode=600"$ ansible webservers -m file -a "dest=/srv/foo/b.txt mode=600 owner=mdehaan→˓group=mdehaan"
The file module can also create directories, similar to mkdir -p:
$ ansible webservers -m file -a "dest=/path/to/c mode=755 owner=mdehaan group=mdehaan→˓state=directory"
As well as delete directories (recursively) and delete files:
$ ansible webservers -m file -a "dest=/path/to/c state=absent"
Managing Packages
There are modules available for yum and apt. Here are some examples with yum.
Ensure a package is installed, but don’t update it:
24 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
$ ansible webservers -m yum -a "name=acme state=present"
Ensure a package is installed to a specific version:
$ ansible webservers -m yum -a "name=acme-1.5 state=present"
Ensure a package is at the latest version:
$ ansible webservers -m yum -a "name=acme state=latest"
Ensure a package is not installed:
$ ansible webservers -m yum -a "name=acme state=absent"
Ansible has modules for managing packages under many platforms. If your package manager does not have a moduleavailable for it, you can install for other packages using the command module or (better!) contribute a module forother package managers. Stop by the mailing list for info/details.
Users and Groups
The ‘user’ module allows easy creation and manipulation of existing user accounts, as well as removal of user accountsthat may exist:
$ ansible all -m user -a "name=foo password=<crypted password here>"
$ ansible all -m user -a "name=foo state=absent"
See the About Modules section for details on all of the available options, including how to manipulate groups andgroup membership.
Deploying From Source Control
Deploy your webapp straight from git:
$ ansible webservers -m git -a "repo=git://foo.example.org/repo.git dest=/srv/myapp→˓version=HEAD"
Since Ansible modules can notify change handlers it is possible to tell Ansible to run specific tasks when the code isupdated, such as deploying Perl/Python/PHP/Ruby directly from git and then restarting apache.
Managing Services
Ensure a service is started on all webservers:
$ ansible webservers -m service -a "name=httpd state=started"
Alternatively, restart a service on all webservers:
$ ansible webservers -m service -a "name=httpd state=restarted"
Ensure a service is stopped:
$ ansible webservers -m service -a "name=httpd state=stopped"
1.1. Introduction 25
Ansible 1.2 Documentation, Release 0.01
Time Limited Background Operations
Long running operations can be backgrounded, and their status can be checked on later. If you kick hosts and don’twant to poll, it looks like this:
$ ansible all -B 3600 -P 0 -a "/usr/bin/long_running_operation --do-stuff"
If you do decide you want to check on the job status later, you can use the async_status module, passing it the job idthat was returned when you ran the original job in the background:
$ ansible web1.example.com -m async_status -a "jid=488359678239.2844"
Polling is built-in and looks like this:
$ ansible all -B 1800 -P 60 -a "/usr/bin/long_running_operation --do-stuff"
The above example says “run for 30 minutes max (-B: 30*60=1800), poll for status (-P) every 60 seconds”.
Poll mode is smart so all jobs will be started before polling will begin on any machine. Be sure to use a high enough--forks value if you want to get all of your jobs started very quickly. After the time limit (in seconds) runs out (-B),the process on the remote nodes will be terminated.
Typically you’ll only be backgrounding long-running shell commands or software upgrades only. Backgrounding thecopy module does not do a background file transfer. Playbooks also support polling, and have a simplified syntax forthis.
Gathering Facts
Facts are described in the playbooks section and represent discovered variables about a system. These can be used toimplement conditional execution of tasks but also just to get ad-hoc information about your system. You can see allfacts via:
$ ansible all -m setup
It’s also possible to filter this output to just export certain facts, see the “setup” module documentation for details.
Read more about facts at Variables once you’re ready to read up on Playbooks.
See also:
Configuration file All about the Ansible config file
About Modules A list of available modules
Playbooks Using Ansible for configuration management & deployment
Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
irc.freenode.net #ansible IRC chat channel
Configuration file
Topics
• Configuration file
– Getting the latest configuration
26 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
– Environmental configuration
– Explanation of values by section
* General defaults
· action_plugins
· ansible_managed
· ask_pass
· ask_sudo_pass
· ask_vault_pass
· bin_ansible_callbacks
· callback_plugins
· stdout_callback
· callback_whitelist
· command_warnings
· connection_plugins
· deprecation_warnings
· display_skipped_hosts
· error_on_undefined_vars
· executable
· filter_plugins
· force_color
· force_handlers
· forks
· gathering
· hash_behaviour
· hostfile
· host_key_checking
· inventory
· jinja2_extensions
· library
· log_path
· lookup_plugins
· module_lang
· module_name
· nocolor
· nocows
1.1. Introduction 27
Ansible 1.2 Documentation, Release 0.01
· pattern
· poll_interval
· private_key_file
· remote_port
· remote_tmp
· remote_user
· retry_files_enabled
· retry_files_save_path
· roles_path
· sudo_exe
· sudo_flags
· sudo_user
· system_warnings
· timeout
· transport
· vars_plugins
· vault_password_file
* Privilege Escalation Settings
· become
· become_method
· become_user
· become_ask_pass
· become_allow_same_user
* Paramiko Specific Settings
· record_host_keys
* OpenSSH Specific Settings
· ssh_args
· control_path
· scp_if_ssh
· pipelining
* Accelerated Mode Settings
· accelerate_port
· accelerate_timeout
· accelerate_connect_timeout
· accelerate_daemon_timeout
· accelerate_multi_key
28 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
* Selinux Specific Settings
· special_context_filesystems
* Galaxy Settings
· server
· ignore_certs
Certain settings in Ansible are adjustable via a configuration file. The stock configuration should be sufficient for mostusers, but there may be reasons you would want to change them.
Changes can be made and used in a configuration file which will be processed in the following order:
* ANSIBLE_CONFIG (an environment variable)
* ansible.cfg (in the current directory)
* .ansible.cfg (in the home directory)
* /etc/ansible/ansible.cfg
Prior to 1.5 the order was:
* ansible.cfg (in the current directory)
* ANSIBLE_CONFIG (an environment variable)
* .ansible.cfg (in the home directory)
* /etc/ansible/ansible.cfg
Ansible will process the above list and use the first file found. Settings in files are not merged.
Getting the latest configuration
If installing ansible from a package manager, the latest ansible.cfg should be present in /etc/ansible, possibly as a”.rpmnew” file (or other) as appropriate in the case of updates.
If you have installed from pip or from source, however, you may want to create this file in order to override defaultsettings in Ansible.
You may wish to consult the ansible.cfg in source control for all of the possible latest values.
Environmental configuration
Ansible also allows configuration of settings via environment variables. If these environment variables are set, theywill override any setting loaded from the configuration file. These variables are for brevity not defined here, but look inconstants.py in the source tree if you want to use these. They are mostly considered to be a legacy system as comparedto the config file, but are equally valid.
Explanation of values by section
The configuration file is broken up into sections. Most options are in the “general” section but some sections of thefile are specific to certain connection types.
General defaults
In the [defaults] section of ansible.cfg, the following settings are tunable:
1.1. Introduction 29
Ansible 1.2 Documentation, Release 0.01
action_plugins
Actions are pieces of code in ansible that enable things like module execution, templating, and so forth.
This is a developer-centric feature that allows low-level extensions around Ansible to be loaded from different loca-tions:
action_plugins = ~/.ansible/plugins/action_plugins/:/usr/share/ansible_plugins/action_→˓plugins
Most users will not need to use this feature. See Developing Plugins for more details.
ansible_managed
Ansible-managed is a string that can be inserted into files written by Ansible’s config templating system, if you use astring like:
{{ ansible_managed }}
The default configuration shows who modified a file and when:
ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on→˓{host}
This is useful to tell users that a file has been placed by Ansible and manual changes are likely to be overwritten.
Note that if using this feature, and there is a date in the string, the template will be reported changed each time as thedate is updated.
ask_pass
This controls whether an Ansible playbook should prompt for a password by default. The default behavior is no:
ask_pass=True
If using SSH keys for authentication, it’s probably not needed to change this setting.
ask_sudo_pass
Similar to ask_pass, this controls whether an Ansible playbook should prompt for a sudo password by default whensudoing. The default behavior is also no:
ask_sudo_pass=True
Users on platforms where sudo passwords are enabled should consider changing this setting.
ask_vault_pass
This controls whether an Ansible playbook should prompt for the vault password by default. The default behavior isno:
30 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
ask_vault_pass=True
bin_ansible_callbacks
New in version 1.8.
Controls whether callback plugins are loaded when running /usr/bin/ansible. This may be used to log activity fromthe command line, send notifications, and so on. Callback plugins are always loaded for /usr/bin/ansible-playbook ifpresent and cannot be disabled:
bin_ansible_callbacks=False
Prior to 1.8, callbacks were never loaded for /usr/bin/ansible.
callback_plugins
Callbacks are pieces of code in ansible that get called on specific events, permitting to trigger notifications.
This is a developer-centric feature that allows low-level extensions around Ansible to be loaded from different loca-tions:
callback_plugins = ~/.ansible/plugins/callback_plugins/:/usr/share/ansible_plugins/→˓callback_plugins
Most users will not need to use this feature. See Developing Plugins for more details
stdout_callback
New in version 2.0.
This setting allows you to override the default stdout callback for ansible-playbook:
stdout_callback = skippy
callback_whitelist
New in version 2.0.
Now ansible ships with all included callback plugins ready to use but they are disabled by default. This setting lets youenable a list of additional callbacks. This cannot change or override the default stdout callback, use stdout_callbackfor that:
callback_whitelist = timer,mail
command_warnings
New in version 1.8.
1.1. Introduction 31
Ansible 1.2 Documentation, Release 0.01
By default since Ansible 1.8, Ansible will warn when usage of the shell and command module appear to be simplifiedby using a default Ansible module instead. This can include reminders to use the ‘git’ module instead of shell com-mands to execute ‘git’. Using modules when possible over arbitrary shell commands can lead to more reliable andconsistent playbook runs, and also easier to maintain playbooks:
command_warnings = False
These warnings can be silenced by adjusting the following setting or adding warn=yes or warn=no to the end of thecommand line parameter string, like so:
- name: usage of git that could be replaced with the git moduleshell: git update foo warn=yes
connection_plugins
Connections plugin permit to extend the channel used by ansible to transport commands and files.
This is a developer-centric feature that allows low-level extensions around Ansible to be loaded from different loca-tions:
connection_plugins = ~/.ansible/plugins/connection_plugins/:/usr/share/ansible_→˓plugins/connection_plugins
Most users will not need to use this feature. See Developing Plugins for more details
deprecation_warnings
New in version 1.3.
Allows disabling of deprecating warnings in ansible-playbook output:
deprecation_warnings = True
Deprecation warnings indicate usage of legacy features that are slated for removal in a future release of Ansible.
display_skipped_hosts
If set to False, ansible will not display any status for a task that is skipped. The default behavior is to display skippedtasks:
display_skipped_hosts=True
Note that Ansible will always show the task header for any task, regardless of whether or not the task is skipped.
error_on_undefined_vars
On by default since Ansible 1.3, this causes ansible to fail steps that reference variable names that are likely typoed:
error_on_undefined_vars=True
If set to False, any ‘{{ template_expression }}’ that contains undefined variables will be rendered in a template oransible action line exactly as written.
32 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
executable
This indicates the command to use to spawn a shell under a sudo environment. Users may need to change this to/bin/bash in rare instances when sudo is constrained, but in most cases it may be left as is:
executable = /bin/bash
filter_plugins
Filters are specific functions that can be used to extend the template system.
This is a developer-centric feature that allows low-level extensions around Ansible to be loaded from different loca-tions:
filter_plugins = ~/.ansible/plugins/filter_plugins/:/usr/share/ansible_plugins/filter_→˓plugins
Most users will not need to use this feature. See Developing Plugins for more details
force_color
This options forces color mode even when running without a TTY:
force_color = 1
force_handlers
New in version 1.9.1.
This option causes notified handlers to run on a host even if a failure occurs on that host:
force_handlers = True
The default is False, meaning that handlers will not run if a failure has occurred on a host. This can also be set perplay or on the command line. See Handlers and Failure for more details.
forks
This is the default number of parallel processes to spawn when communicating with remote hosts. Since Ansible 1.3,the fork number is automatically limited to the number of possible hosts, so this is really a limit of how much networkand CPU load you think you can handle. Many users may set this to 50, some set it to 500 or more. If you have a largenumber of hosts, higher values will make actions across all of those hosts complete faster. The default is very veryconservative:
forks=5
gathering
New in 1.6, the ‘gathering’ setting controls the default policy of facts gathering (variables discovered about remotesystems).
1.1. Introduction 33
Ansible 1.2 Documentation, Release 0.01
The value ‘implicit’ is the default, which means that the fact cache will be ignored and facts will be gathered perplay unless ‘gather_facts: False’ is set. The value ‘explicit’ is the inverse, facts will not be gathered unless directlyrequested in the play. The value ‘smart’ means each new host that has no facts discovered will be scanned, but if thesame host is addressed in multiple plays it will not be contacted again in the playbook run. This option can be usefulfor those wishing to save fact gathering time. Both ‘smart’ and ‘explicit’ will use the fact cache:
gathering = smart
hash_behaviour
Ansible by default will override variables in specific precedence orders, as described in Variables. When a variable ofhigher precedence wins, it will replace the other value.
Some users prefer that variables that are hashes (aka ‘dictionaries’ in Python terms) are merged. This setting is called‘merge’. This is not the default behavior and it does not affect variables whose values are scalars (integers, strings)or arrays. We generally recommend not using this setting unless you think you have an absolute need for it, andplaybooks in the official examples repos do not use this setting:
hash_behaviour=replace
The valid values are either ‘replace’ (the default) or ‘merge’.
If you want to merge hashes without changing the global settings, use the combine filter described in Jinja2 filters.
hostfile
This is a deprecated setting since 1.9, please look at inventory for the new setting.
host_key_checking
As described in Getting Started, host key checking is on by default in Ansible 1.3 and later. If you understand theimplications and wish to disable it, you may do so here by setting the value to False:
host_key_checking=True
inventory
This is the default location of the inventory file, script, or directory that Ansible will use to determine what hosts it hasavailable to talk to:
inventory = /etc/ansible/hosts
It used to be called hostfile in Ansible before 1.9
jinja2_extensions
This is a developer-specific feature that allows enabling additional Jinja2 extensions:
jinja2_extensions = jinja2.ext.do,jinja2.ext.i18n
If you do not know what these do, you probably don’t need to change this setting :)
34 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
library
This is the default location Ansible looks to find modules:
library = /usr/share/ansible
Ansible knows how to look in multiple locations if you feed it a colon separated path, and it also will look for modulesin the ”./library” directory alongside a playbook.
log_path
If present and configured in ansible.cfg, Ansible will log information about executions at the designated location. Besure the user running Ansible has permissions on the logfile:
log_path=/var/log/ansible.log
This behavior is not on by default. Note that ansible will, without this setting, record module arguments called to thesyslog of managed machines. Password arguments are excluded.
For Enterprise users seeking more detailed logging history, you may be interested in Ansible Tower.
lookup_plugins
This is a developer-centric feature that allows low-level extensions around Ansible to be loaded from different loca-tions:
lookup_plugins = ~/.ansible/plugins/lookup_plugins/:/usr/share/ansible_plugins/lookup_→˓plugins
Most users will not need to use this feature. See Developing Plugins for more details
module_lang
This is to set the default language to communicate between the module and the system. By default, the value is ‘C’:
module_lang = en_US.UTF-8
module_name
This is the default module name (-m) value for /usr/bin/ansible. The default is the ‘command’ module. Remember thecommand module doesn’t support shell variables, pipes, or quotes, so you might wish to change it to ‘shell’:
module_name = command
nocolor
By default ansible will try to colorize output to give a better indication of failure and status information. If you dislikethis behavior you can turn it off by setting ‘nocolor’ to 1:
1.1. Introduction 35
Ansible 1.2 Documentation, Release 0.01
nocolor=0
nocows
By default ansible will take advantage of cowsay if installed to make /usr/bin/ansible-playbook runs more exciting.Why? We believe systems management should be a happy experience. If you do not like the cows, you can disablethem by setting ‘nocows’ to 1:
nocows=0
pattern
This is the default group of hosts to talk to in a playbook if no “hosts:” stanza is supplied. The default is to talk to allhosts. You may wish to change this to protect yourself from surprises:
hosts=*
Note that /usr/bin/ansible always requires a host pattern and does not use this setting, only /usr/bin/ansible-playbook.
poll_interval
For asynchronous tasks in Ansible (covered in Asynchronous Actions and Polling), this is how often to check backon the status of those tasks when an explicit poll interval is not supplied. The default is a reasonably moderate 15seconds which is a tradeoff between checking in frequently and providing a quick turnaround when something mayhave completed:
poll_interval=15
private_key_file
If you are using a pem file to authenticate with machines rather than SSH agent or passwords, you can set the defaultvalue here to avoid re-specifying --private-key with every invocation:
private_key_file=/path/to/file.pem
remote_port
This sets the default SSH port on all of your systems, for systems that didn’t specify an alternative value in inventory.The default is the standard 22:
remote_port = 22
remote_tmp
Ansible works by transferring modules to your remote machines, running them, and then cleaning up after itself. Insome cases, you may not wish to use the default location and would like to change the path. You can do so by alteringthis setting:
36 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
remote_tmp = $HOME/.ansible/tmp
The default is to use a subdirectory of the user’s home directory. Ansible will then choose a random directory nameinside this location.
remote_user
This is the default username ansible will connect as for /usr/bin/ansible-playbook. Note that /usr/bin/ansible willalways default to the current user if this is not defined:
remote_user = root
retry_files_enabled
This controls whether a failed Ansible playbook should create a .retry file. The default setting is True:
retry_files_enabled = False
retry_files_save_path
The retry files save path is where Ansible will save .retry files when a playbook fails and retry_files_enabled is True(the default). The default location is ~/ and can be changed to any writeable path:
retry_files_save_path = ~/.ansible-retry
The directory will be created if it does not already exist.
roles_path
The roles path indicate additional directories beyond the ‘roles/’ subdirectory of a playbook project to search to findAnsible roles. For instance, if there was a source control repository of common roles and a different repository ofplaybooks, you might choose to establish a convention to checkout roles in /opt/mysite/roles like so:
roles_path = /opt/mysite/roles
Additional paths can be provided separated by colon characters, in the same way as other pathstrings:
roles_path = /opt/mysite/roles:/opt/othersite/roles
Roles will be first searched for in the playbook directory. Should a role not be found, it will indicate all the possiblepaths that were searched.
sudo_exe
If using an alternative sudo implementation on remote machines, the path to sudo can be replaced here provided thesudo implementation is matching CLI flags with the standard sudo:
sudo_exe=sudo
1.1. Introduction 37
Ansible 1.2 Documentation, Release 0.01
sudo_flags
Additional flags to pass to sudo when engaging sudo support. The default is ‘-H -S -n’ which sets the HOME envi-ronment variable, prompts for passwords via STDIN, and avoids prompting the user for input of any kind. Note that‘-n’ will conflict with using password-less sudo auth, such as pam_ssh_agent_auth. In some situations you may wishto add or remove flags, but in general most users will not need to change this setting::
sudo_flags=-H -S -n
sudo_user
This is the default user to sudo to if --sudo-user is not specified or ‘sudo_user’ is not specified in an Ansibleplaybook. The default is the most logical: ‘root’:
sudo_user=root
system_warnings
New in version 1.6.
Allows disabling of warnings related to potential issues on the system running ansible itself (not on the managedhosts):
system_warnings = True
These may include warnings about 3rd party packages or other conditions that should be resolved if possible.
timeout
This is the default SSH timeout to use on connection attempts:
timeout = 10
transport
This is the default transport to use if “-c <transport_name>” is not specified to /usr/bin/ansible or /usr/bin/ansible-playbook. The default is ‘smart’, which will use ‘ssh’ (OpenSSH based) if the local operating system is new enoughto support ControlPersist technology, and then will otherwise use ‘paramiko’. Other transport options include ‘local’,‘chroot’, ‘jail’, and so on.
Users should usually leave this setting as ‘smart’ and let their playbooks choose an alternate setting when needed withthe ‘connection:’ play parameter:
transport = paramiko
vars_plugins
This is a developer-centric feature that allows low-level extensions around Ansible to be loaded from different loca-tions:
38 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
vars_plugins = ~/.ansible/plugins/vars_plugins/:/usr/share/ansible_plugins/vars_→˓plugins
Most users will not need to use this feature. See Developing Plugins for more details
vault_password_file
New in version 1.7.
Configures the path to the Vault password file as an alternative to specifying --vault-password-file on thecommand line:
vault_password_file = /path/to/vault_password_file
As of 1.7 this file can also be a script. If you are using a script instead of a flat file, ensure that it is marked asexecutable, and that the password is printed to standard output. If your script needs to prompt for data, prompts canbe sent to standard error.
Privilege Escalation Settings
Ansible can use existing privilege escalation systems to allow a user to execute tasks as another. As of 1.9 ‘become’supersedes the old sudo/su, while still being backwards compatible. Settings live under the [privilege_escalation]header.
become
The equivalent of adding sudo: or su: to a play or task, set to true/yes to activate privilege escalation. The defaultbehavior is no:
become=True
become_method
Set the privilege escalation method. The default is sudo, other options are su, pbrun, pfexec, doas:
become_method=su
become_user
The equivalent to ansible_sudo_user or ansible_su_user, allows to set the user you become through privilege escala-tion. The default is ‘root’:
become_user=root
become_ask_pass
Ask for privilege escalation password, the default is False:
1.1. Introduction 39
Ansible 1.2 Documentation, Release 0.01
become_ask_pass=True
become_allow_same_user
Most of the time, using sudo to run a command as the same user who is running sudo itself is unnecessary over-head, so Ansible does not allow it. However, depending on the sudo configuration, it may be necessary to runa command as the same user through sudo, such as to switch SELinux contexts. For this reason, you can setbecome_allow_same_user to True and disable this optimization.
Paramiko Specific Settings
Paramiko is the default SSH connection implementation on Enterprise Linux 6 or earlier, and is not used by default onother platforms. Settings live under the [paramiko] header.
record_host_keys
The default setting of yes will record newly discovered and approved (if host key checking is enabled) hosts in theuser’s hostfile. This setting may be inefficient for large numbers of hosts, and in those situations, using the ssh transportis definitely recommended instead. Setting it to False will improve performance and is recommended when host keychecking is disabled:
record_host_keys=True
OpenSSH Specific Settings
Under the [ssh_connection] header, the following settings are tunable for SSH connections. OpenSSH is the defaultconnection type for Ansible on OSes that are new enough to support ControlPersist. (This means basically all operatingsystems except Enterprise Linux 6 or earlier).
ssh_args
If set, this will pass a specific set of options to Ansible rather than Ansible’s usual defaults:
ssh_args = -o ControlMaster=auto -o ControlPersist=60s
In particular, users may wish to raise the ControlPersist time to encourage performance. A value of 30 minutes maybe appropriate. If ssh_args is set, the default control_path setting is not used.
control_path
This is the location to save ControlPath sockets. This defaults to:
control_path=%(directory)s/ansible-ssh-%%h-%%p-%%r
On some systems with very long hostnames or very long path names (caused by long user names or deeply nestedhome directories) this can exceed the character limit on file socket names (108 characters for most platforms). In thatcase, you may wish to shorten the string to something like the below:
40 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
control_path = %(directory)s/%%h-%%r
Ansible 1.4 and later will instruct users to run with “-vvvv” in situations where it hits this problem and if so it is easyto tell there is too long of a Control Path filename. This may be frequently encountered on EC2. This setting is ignoredif ssh_args is set.
scp_if_ssh
Occasionally users may be managing a remote system that doesn’t have SFTP enabled. If set to True, we can causescp to be used to transfer remote files instead:
scp_if_ssh=False
There’s really no reason to change this unless problems are encountered, and then there’s also no real drawback tomanaging the switch. Most environments support SFTP by default and this doesn’t usually need to be changed.
pipelining
Enabling pipelining reduces the number of SSH operations required to execute a module on the remote server, byexecuting many ansible modules without actual file transfer. This can result in a very significant performance im-provement when enabled, however when using “sudo:” operations you must first disable ‘requiretty’ in /etc/sudoerson all managed hosts.
By default, this option is disabled to preserve compatibility with sudoers configurations that have requiretty (the defaulton many distros), but is highly recommended if you can enable it, eliminating the need for Accelerated Mode:
pipelining=False
Accelerated Mode Settings
Under the [accelerate] header, the following settings are tunable for Accelerated Mode. Acceleration is a usefulperformance feature to use if you cannot enable pipelining in your environment, but is probably not needed if you can.
accelerate_port
New in version 1.3.
This is the port to use for accelerated mode:
accelerate_port = 5099
accelerate_timeout
New in version 1.4.
This setting controls the timeout for receiving data from a client. If no data is received during this time, the socketconnection will be closed. A keepalive packet is sent back to the controller every 15 seconds, so this timeout shouldnot be set lower than 15 (by default, the timeout is 30 seconds):
1.1. Introduction 41
Ansible 1.2 Documentation, Release 0.01
accelerate_timeout = 30
accelerate_connect_timeout
New in version 1.4.
This setting controls the timeout for the socket connect call, and should be kept relatively low. The connection to theaccelerate_port will be attempted 3 times before Ansible will fall back to ssh or paramiko (depending on your defaultconnection setting) to try and start the accelerate daemon remotely. The default setting is 1.0 seconds:
accelerate_connect_timeout = 1.0
Note, this value can be set to less than one second, however it is probably not a good idea to do so unless you’re ona very fast and reliable LAN. If you’re connecting to systems over the internet, it may be necessary to increase thistimeout.
accelerate_daemon_timeout
New in version 1.6.
This setting controls the timeout for the accelerated daemon, as measured in minutes. The default daemon timeout is30 minutes:
accelerate_daemon_timeout = 30
Note, prior to 1.6, the timeout was hard-coded from the time of the daemon’s launch. For version 1.6+, the timeout isnow based on the last activity to the daemon and is configurable via this option.
accelerate_multi_key
New in version 1.6.
If enabled, this setting allows multiple private keys to be uploaded to the daemon. Any clients connecting to thedaemon must also enable this option:
accelerate_multi_key = yes
New clients first connect to the target node over SSH to upload the key, which is done via a local socket file, so theymust have the same access as the user that launched the daemon originally.
Selinux Specific Settings
These are settings that control SELinux interactions.
special_context_filesystems
New in version 1.9.
This is a list of file systems that require special treatment when dealing with security context. The normal behaviouris for operations to copy the existing context or use the user default, this changes it to use a file system dependentcontext. The default list is: nfs,vboxsf,fuse,ramfs:
42 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
special_context_filesystems = nfs,vboxsf,fuse,ramfs,myspecialfs
Galaxy Settings
The following options can be set in the [galaxy] section of ansible.cfg:
server
Override the default Galaxy server value of https://galaxy.ansible.com. Useful if you have a hosted version of theGalaxy web app or want to point to the testing site https://galaxy-qa.ansible.com. It does not work against private,hosted repos, which Galaxy can use for fetching and installing roles.
ignore_certs
If set to yes, ansible-galaxy will not validate TLS certificates. Handy for testing against a server with a self-signedcertificate .
BSD support
Topics
• BSD support
– Working with BSD
– Bootstrapping BSD
– Setting python interpreter
– What modules are available
– You can also use a BSD as the control machine
– BSD Facts
– BSD Contributions
Working with BSD
As you may have already read, Ansible manages Linux/Unix machines using SSH by default. Ansible handles BSDmachines in the same manner.
Depending on your control machine, Ansible will try to default to using OpenSSH. This works fine when using SSHkeys to authenticate, but when using SSH passwords, Ansible relies on sshpass. Most versions of sshpass do not dealwell with BSD login prompts, so in these cases we recommend changing the transport to paramiko. You can do thisin ansible.cfg globaly or set it as an inventory/group/host variable:
[freebsd]mybsdhost1 ansible_connection=paramiko
1.1. Introduction 43
Ansible 1.2 Documentation, Release 0.01
Ansible is agentless by default, but it needs some software installed on the target machines, mainly Python 2.4 orhigher with an included json library (which is standard in Python 2.5 and above). Without python you can still usethe raw module to execute commands. This module is very limited, however it can be used to bootstrap Ansible onBSDs.
Bootstrapping BSD
For Ansible to effectively manage your machine, we need to install Python along with a json library, in this case weare using Python 2.7 which already has json included. On your control machine you can simply execute the followingfor most versions of FreeBSD:
ansible -m raw -a “pkg_add -r python27” mybsdhost1
Once this is done you can now use other Ansible modules aside from the raw module.
Note: This example uses pkg_add, you should be able to substitute for the appropriate tool for your BSD, also youmight need to look up the exact package name you need.
Setting python interpreter
To support the multitude of Unix/Linux OSs and distributions, Ansible cannot rely on the environment or envto find the correct Python. By default, modules point at /usr/bin/python as this is the most common lo-cation. On the BSDs you cannot rely on this so you should tell ansible where python is located, through theansible_python_interpreter inventory variable:
[freebsd:vars]ansible_python_interpreter=/usr/local/bin/python2.7
If you use plugins other than those included with Ansible you might need to set similar variables for bash, perl orruby, depending on how the plugin was written:
[freebsd:vars]ansible_python_interpreter=/usr/local/bin/pythonansible_perl_interpreter=/usr/bin/perl5
What modules are available
Most of the core Ansible modules are written for a combination of Linux/Unix machines and arbitrary web services;most should work fine on the BSDs with the exception of those that are aimed at Linux specific technologies (i.e. lvg).
You can also use a BSD as the control machine
It should be as simple as installing the Ansible package or follow the pip or ‘from source’ instructions.
BSD Facts
Ansible gathers facts from the BSDs as it would from Linux machines, but since the data, names and structures can bedifferent for network, disks and other devices, one should expect the output to be different, but still familiar to a BSDadministrator.
44 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
BSD Contributions
BSD support is important for Ansible. Even though the majority of our contributors use and target Linux we havean active BSD community and will strive to be as BSD friendly as possible. Report any issues you see with BSDincompatibilities, even better to submit a pull request with the fix!
See also:
Introduction To Ad-Hoc Commands Examples of basic commands
Playbooks Learning ansible’s configuration management language
Developing Modules How to write modules
Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
irc.freenode.net #ansible IRC chat channel
Windows Support
Topics
• Windows Support
– Windows: How Does It Work
– Installing on the Control Machine
* Active Directory Support
· Installing python-kerberos dependencies
· Installing python-kerberos
· Configuring Kerberos
· Testing a kerberos connection
· Troubleshooting kerberos connections
– Inventory
– Windows System Prep
– Getting to PowerShell 3.0 or higher
– What modules are available
– Developers: Supported modules and how it works
– Reminder: You Must Have a Linux Control Machine
– Windows Facts
– Windows Playbook Examples
– Windows Contributions
Windows: How Does It Work
As you may have already read, Ansible manages Linux/Unix machines using SSH by default.
1.1. Introduction 45
Ansible 1.2 Documentation, Release 0.01
Starting in version 1.7, Ansible also contains support for managing Windows machines. This uses native PowerShellremoting, rather than SSH.
Ansible will still be run from a Linux control machine, and uses the “winrm” Python module to talk to remote hosts.
No additional software needs to be installed on the remote machines for Ansible to manage them, it still maintains theagentless properties that make it popular on Linux/Unix.
Note that it is expected you have a basic understanding of Ansible prior to jumping into this section, so if you haven’twritten a Linux playbook first, it might be worthwhile to dig in there first.
Installing on the Control Machine
On a Linux control machine:
pip install "pywinrm>=0.1.1"
Active Directory Support
If you wish to connect to domain accounts published through Active Directory (as opposed to local accounts createdon the remote host), you will need to install the “python-kerberos” module on the Ansible control host (and the MITkrb5 libraries it depends on). The Ansible control host also requires a properly configured computer account in ActiveDirectory.
Installing python-kerberos dependencies
# Via Yumyum -y install python-devel krb5-devel krb5-libs krb5-workstation
# Via Apt (Ubuntu)sudo apt-get install python-dev libkrb5-dev
# Via Portage (Gentoo)emerge -av app-crypt/mit-krb5emerge -av dev-python/setuptools
# Via pkg (FreeBSD)sudo pkg install security/krb5
# Via OpenCSW (Solaris)pkgadd -d http://get.opencsw.org/now/opt/csw/bin/pkgutil -U/opt/csw/bin/pkgutil -y -i libkrb5_3
# Via Pacman (Arch Linux)pacman -S krb5
Installing python-kerberos
Once you’ve installed the necessary dependencies, the python-kerberos wrapper can be installed via pip:
pip install kerberos
46 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Kerberos is installed and configured by default on OS X and many Linux distributions. If your control machine hasnot already done this for you, you will need to.
Configuring Kerberos
Edit your /etc/krb5.conf (which should be installed as a result of installing packages above) and add the followinginformation for each domain you need to connect to:
In the section that starts with
[realms]
add the full domain name and the fully qualified domain names of your primary and secondary Active Directorydomain controllers. It should look something like this:
[realms]
MY.DOMAIN.COM = {kdc = domain-controller1.my.domain.comkdc = domain-controller2.my.domain.com
}
and in the [domain_realm] section add a line like the following for each domain you want to access:
[domain_realm].my.domain.com = MY.DOMAIN.COM
You may wish to configure other settings here, such as the default domain.
Testing a kerberos connection
If you have installed krb5-workstation (yum) or krb5-user (apt-get) you can use the following command to test thatyou can be authorised by your domain controller.
kinit [email protected]
Note that the domain part has to be fully qualified and must be in upper case.
To see what tickets if any you have acquired, use the command klist
klist
Troubleshooting kerberos connections
If you unable to connect using kerberos, check the following:
Ensure that forward and reverse DNS lookups are working properly on your domain.
To test this, ping the windows host you want to control by name then use the ip address returned with nslookup. Youshould get the same name back from DNS when you use nslookup on the ip address.
If you get different hostnames back than the name you originally pinged, speak to your active directory administratorand get them to check that DNS Scavenging is enabled and that DNS and DHCP are updating each other.
Ensure that the Ansible controller has a properly configured computer account in the domain.
1.1. Introduction 47
Ansible 1.2 Documentation, Release 0.01
Check your Ansible controller’s clock is synchronised with your domain controller. Kerberos is time sensitive and alittle clock drift can cause tickets not be granted.
Check you are using the real fully qualified domain name for the domain. Sometimes domains are commonly knownto users by aliases. To check this run:
kinit -C [email protected]
If the domain name returned by klist is different from the domain name you requested, you are requesting using analias, and you need to update your krb5.conf so you are using the fully qualified domain name, not its alias.
Inventory
Ansible’s windows support relies on a few standard variables to indicate the username, password, and connection type(windows) of the remote hosts. These variables are most easily set up in inventory. This is used instead of SSH-keysor passwords as normally fed into Ansible:
[windows]winserver1.example.comwinserver2.example.com
Note: Ansible 2.0 has deprecated the “ssh” from ansible_ssh_user, ansible_ssh_host, andansible_ssh_port to become ansible_user, ansible_host, and ansible_port. If you are usinga version of Ansible prior to 2.0, you should continue using the older style variables (ansible_ssh_*). Theseshorter variables are ignored, without warning, in older versions of Ansible.
In group_vars/windows.yml, define the following inventory variables:
# it is suggested that these be encrypted with ansible-vault:# ansible-vault edit group_vars/windows.yml
ansible_user: Administratoransible_password: SecretPasswordGoesHereansible_port: 5986ansible_connection: winrm# The following is necessary for Python 2.7.9+ when using default WinRM self-signed→˓certificates:ansible_winrm_server_cert_validation: ignore
Although Ansible is mostly an SSH-oriented system, Windows management will not happen overSSH (yet <http://blogs.msdn.com/b/powershell/archive/2015/06/03/looking-forward-microsoft-support-for-secure-shell-ssh.aspx>).
If you have installed the kerberos module and ansible_user contains @ (e.g. username@realm), Ansiblewill first attempt Kerberos authentication. This method uses the principal you are authenticated to Kerberos with onthe control machine and not ‘‘ansible_user‘‘. If that fails, either because you are not signed into Kerberos on thecontrol machine or because the corresponding domain account on the remote host is not available, then Ansible willfall back to “plain” username/password authentication.
When using your playbook, don’t forget to specify –ask-vault-pass to provide the password to unlock the file.
Test your configuration like so, by trying to contact your Windows nodes. Note this is not an ICMP ping, but tests theAnsible communication channel that leverages Windows remoting:
48 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
ansible windows [-i inventory] -m win_ping --ask-vault-pass
If you haven’t done anything to prep your systems yet, this won’t work yet. This is covered in a later section abouthow to enable PowerShell remoting - and if necessary - how to upgrade PowerShell to a version that is 3 or higher.
You’ll run this command again later though, to make sure everything is working.
Since 2.0, the following custom inventory variables are also supported for additional configuration of WinRM connec-tions:
* ``ansible_winrm_scheme``: Specify the connection scheme (``http`` or ``https``) to→˓use for the WinRM connection. Ansible uses ``https`` by default unless the port is→˓5985.
* ``ansible_winrm_path``: Specify an alternate path to the WinRM endpoint. Ansible→˓uses ``/wsman`` by default.
* ``ansible_winrm_realm``: Specify the realm to use for Kerberos authentication. If→˓the username contains ``@``, Ansible will use the part of the username after ``@``→˓by default.
* ``ansible_winrm_transport``: Specify one or more transports as a comma-separated→˓list. By default, Ansible will use ``kerberos,plaintext`` if the ``kerberos``→˓module is installed and a realm is defined, otherwise ``plaintext``.
* ``ansible_winrm_server_cert_validation``: Specify the server certificate validation→˓mode (``ignore`` or ``validate``). Ansible defaults to ``validate`` on Python 2.7.9→˓and higher, which will result in certificate validation errors against the Windows→˓self-signed certificates. Unless verifiable certificates have been configured on→˓the WinRM listeners, this should be set to ``ignore``
* ``ansible_winrm_*``: Any additional keyword arguments supported by ``winrm.→˓Protocol`` may be provided.
Windows System Prep
In order for Ansible to manage your windows machines, you will have to enable PowerShell remoting configured.
To automate setup of WinRM, you can run this PowerShell script on the remote machine.
Admins may wish to modify this setup slightly, for instance to increase the timeframe of the certificate.
Note: On Windows 7 and Server 2008 R2 machines, due to a bug in Windows Management Framework 3.0, it maybe necessary to install this hotfix http://support.microsoft.com/kb/2842230 to avoid receiving out of memory and stackoverflow exceptions. Newly-installed Server 2008 R2 systems which are not fully up to date with windows updatesare known to have this issue.
Windows 8.1 and Server 2012 R2 are not affected by this issue as they come with Windows Management Framework4.0.
Getting to PowerShell 3.0 or higher
PowerShell 3.0 or higher is needed for most provided Ansible modules for Windows, and is also required to run theabove setup script. Note that PowerShell 3.0 is only supported on Windows 7 SP1, Windows Server 2008 SP1, andlater releases of Windows.
Looking at an Ansible checkout, copy the examples/scripts/upgrade_to_ps3.ps1 script onto the remote host and run aPowerShell console as an administrator. You will now be running PowerShell 3 and can try connectivity again usingthe win_ping technique referenced above.
1.1. Introduction 49
Ansible 1.2 Documentation, Release 0.01
What modules are available
Most of the Ansible modules in core Ansible are written for a combination of Linux/Unix machines and arbitrary webservices, though there are various Windows modules as listed in the “windows” subcategory of the Ansible moduleindex.
Browse this index to see what is available.
In many cases, it may not be necessary to even write or use an Ansible module.
In particular, the “script” module can be used to run arbitrary PowerShell scripts, allowing Windows administratorsfamiliar with PowerShell a very native way to do things, as in the following playbook:
- hosts: windowstasks:- script: foo.ps1 --argument --other-argument
Note there are a few other Ansible modules that don’t start with “win” that also function, including “slurp”, “raw”,and “setup” (which is how fact gathering works).
Developers: Supported modules and how it works
Developing Ansible modules are covered in a later section of the documentation, with a focus on Linux/Unix. What ifyou want to write Windows modules for Ansible though?
For Windows, Ansible modules are implemented in PowerShell. Skim those Linux/Unix module development chaptersbefore proceeding.
Windows modules live in a “windows/” subfolder in the Ansible “library/” subtree. For example, if a module is named“library/windows/win_ping”, there will be embedded documentation in the “win_ping” file, and the actual PowerShellcode will live in a “win_ping.ps1” file. Take a look at the sources and this will make more sense.
Modules (ps1 files) should start as follows:
#!powershell# <license>
# WANT_JSON# POWERSHELL_COMMON
# code goes here, reading in stdin as JSON and outputting JSON
The above magic is necessary to tell Ansible to mix in some common code and also know how to push modules out.The common code contains some nice wrappers around working with hash data structures and emitting JSON results,and possibly a few more useful things. Regular Ansible has this same concept for reusing Python code - this is just thewindows equivalent.
What modules you see in windows/ are just a start. Additional modules may be submitted as pull requests to github.
Reminder: You Must Have a Linux Control Machine
Note running Ansible from a Windows control machine is NOT a goal of the project. Refrain from asking for thisfeature, as it limits what technologies, features, and code we can use in the main project in the future. A Linux controlmachine will be required to manage Windows hosts.
Cygwin is not supported, so please do not ask questions about Ansible running from Cygwin.
50 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Windows Facts
Just as with Linux/Unix, facts can be gathered for windows hosts, which will return things such as the operating systemversion. To see what variables are available about a windows host, run the following:
ansible winhost.example.com -m setup
Note that this command invocation is exactly the same as the Linux/Unix equivalent.
Windows Playbook Examples
Look to the list of windows modules for most of what is possible, though also some modules like “raw” and “script”also work on Windows, as do “fetch” and “slurp”.
Here is an example of pushing and running a PowerShell script:
- name: test script modulehosts: windowstasks:- name: run test script
script: files/test_script.ps1
Running individual commands uses the ‘raw’ module, as opposed to the shell or command module as is common onLinux/Unix operating systems:
- name: test raw modulehosts: windowstasks:- name: run ipconfig
raw: ipconfigregister: ipconfig
- debug: var=ipconfig
And for a final example, here’s how to use the win_stat module to test for file existence. Note that the data returned bythe win_stat module is slightly different than what is provided by the Linux equivalent:
- name: test stat modulehosts: windowstasks:- name: test stat module on file
win_stat: path="C:/Windows/win.ini"register: stat_file
- debug: var=stat_file
- name: check stat_file resultassert:
that:- "stat_file.stat.exists"- "not stat_file.stat.isdir"- "stat_file.stat.size > 0"- "stat_file.stat.md5"
Again, recall that the Windows modules are all listed in the Windows category of modules, with the exception that the“raw”, “script”, and “fetch” modules are also available. These modules do not start with a “win” prefix.
1.1. Introduction 51
Ansible 1.2 Documentation, Release 0.01
Windows Contributions
Windows support in Ansible is still very new, and contributions are quite welcome, whether this is in the form of newmodules, tweaks to existing modules, documentation, or something else. Please stop by the ansible-devel mailing listif you would like to get involved and say hi.
See also:
Developing Modules How to write modules
Playbooks Learning Ansible’s configuration management language
List of Windows Modules Windows specific module list, all implemented in PowerShell
Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
irc.freenode.net #ansible IRC chat channel
Quickstart Video
We’ve recorded a short video that shows how to get started with Ansible that you may like to use alongside thedocumentation.
The quickstart video is about 30 minutes long and will show you some of the basics about your first steps with Ansible.
Enjoy, and be sure to visit the rest of the documentation to learn more.
Playbooks
Playbooks are Ansible’s configuration, deployment, and orchestration language. They can describe a policy you wantyour remote systems to enforce, or a set of steps in a general IT process.
If Ansible modules are the tools in your workshop, playbooks are your design plans.
At a basic level, playbooks can be used to manage configurations of and deployments to remote machines. At a moreadvanced level, they can sequence multi-tier rollouts involving rolling updates, and can delegate actions to other hosts,interacting with monitoring servers and load balancers along the way.
While there’s a lot of information here, there’s no need to learn everything at once. You can start small and pick upmore features over time as you need them.
Playbooks are designed to be human-readable and are developed in a basic text language. There are multiple ways toorganize playbooks and the files they include, and we’ll offer up some suggestions on that and making the most out ofAnsible.
It is recommended to look at Example Playbooks while reading along with the playbook documentation. Theseillustrate best practices as well as how to put many of the various concepts together.
Intro to Playbooks
About Playbooks
Playbooks are a completely different way to use ansible than in adhoc task execution mode, and are particularlypowerful.
Simply put, playbooks are the basis for a really simple configuration management and multi-machine deploymentsystem, unlike any that already exist, and one that is very well suited to deploying complex applications.
52 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Playbooks can declare configurations, but they can also orchestrate steps of any manual ordered process, even asdifferent steps must bounce back and forth between sets of machines in particular orders. They can launch taskssynchronously or asynchronously.
While you might run the main /usr/bin/ansible program for ad-hoc tasks, playbooks are more likely to be keptin source control and used to push out your configuration or assure the configurations of your remote systems are inspec.
There are also some full sets of playbooks illustrating a lot of these techniques in the ansible-examples repository.We’d recommend looking at these in another tab as you go along.
There are also many jumping off points after you learn playbooks, so hop back to the documentation index after you’redone with this section.
Playbook Language Example
Playbooks are expressed in YAML format (see YAML Syntax) and have a minimum of syntax, which intentionally triesto not be a programming language or script, but rather a model of a configuration or a process.
Each playbook is composed of one or more ‘plays’ in a list.
The goal of a play is to map a group of hosts to some well defined roles, represented by things ansible calls tasks. Ata basic level, a task is nothing more than a call to an ansible module, which you should have learned about in earlierchapters.
By composing a playbook of multiple ‘plays’, it is possible to orchestrate multi-machine deployments, running certainsteps on all machines in the webservers group, then certain steps on the database server group, then more commandsback on the webservers group, etc.
“plays” are more or less a sports analogy. You can have quite a lot of plays that affect your systems to do differentthings. It’s not as if you were just defining one particular state or model, and you can run different plays at differenttimes.
For starters, here’s a playbook that contains just one play:
---- hosts: webservers
vars:http_port: 80max_clients: 200
remote_user: roottasks:- name: ensure apache is at the latest versionyum: name=httpd state=latest
- name: write the apache config filetemplate: src=/srv/httpd.j2 dest=/etc/httpd.confnotify:- restart apache
- name: ensure apache is running (and enable it at boot)service: name=httpd state=started enabled=yes
handlers:- name: restart apache
service: name=httpd state=restarted
We can also break task items out over multiple lines using the YAML dictionary types to supply module arguments.This can be helpful when working with tasks that have really long parameters or modules that take many parametersto keep them well structured. Below is another version of the above example but using YAML dictionaries to supplythe modules with their key=value arguments.:
1.3. Playbooks 53
Ansible 1.2 Documentation, Release 0.01
---- hosts: webservers
vars:http_port: 80max_clients: 200
remote_user: roottasks:- name: ensure apache is at the latest versionyum:
name: httpdstate: latest
- name: write the apache config filetemplate:
src: /srv/httpd.j2dest: /etc/httpd.conf
notify:- restart apache
- name: ensure apache is runningservice:
name: httpdstate: started
handlers:- name: restart apache
service:name: httpdstate: restarted
Playbooks can contain multiple plays. You may have a playbook that targets first the web servers, and then the databaseservers. For example:
---- hosts: webservers
remote_user: root
tasks:- name: ensure apache is at the latest versionyum: name=httpd state=latest
- name: write the apache config filetemplate: src=/srv/httpd.j2 dest=/etc/httpd.conf
- hosts: databasesremote_user: root
tasks:- name: ensure postgresql is at the latest versionyum: name=postgresql state=latest
- name: ensure that postgresql is startedservice: name=postgresql state=running
You can use this method to switch between the host group you’re targeting, the username logging into the remoteservers, whether to sudo or not, and so forth. Plays, like tasks, run in the order specified in the playbook: top tobottom.
Below, we’ll break down what the various features of the playbook language are.
Basics
54 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Hosts and Users
For each play in a playbook, you get to choose which machines in your infrastructure to target and what remote userto complete the steps (called tasks) as.
The hosts line is a list of one or more groups or host patterns, separated by colons, as described in the Patternsdocumentation. The remote_user is just the name of the user account:
---- hosts: webservers
remote_user: root
Note: The remote_user parameter was formerly called just user. It was renamed in Ansible 1.4 to make it moredistinguishable from the user module (used to create users on remote systems).
Remote users can also be defined per task:
---- hosts: webservers
remote_user: roottasks:- name: test connection
ping:remote_user: yourname
Note: The remote_user parameter for tasks was added in 1.4.
Support for running things as another user is also available (see Become (Privilege Escalation)):
---- hosts: webservers
remote_user: yournamesudo: yes
You can also use sudo on a particular task instead of the whole play:
---- hosts: webservers
remote_user: yournametasks:- service: name=nginx state=started
become: yesbecome_method: sudo
Note: The become syntax deprecates the old sudo/su specific syntax beginning in 1.9.
You can also login as you, and then become a user different than root:
---- hosts: webservers
remote_user: yournamebecome: yesbecome_user: postgres
1.3. Playbooks 55
Ansible 1.2 Documentation, Release 0.01
You can also use other privilege escalation methods, like su:
---- hosts: webservers
remote_user: yournamebecome: yesbecome_method: su
If you need to specify a password to sudo, run ansible-playbook with --ask-become-pass or when usingthe old sudo syntax --ask-sudo-pass (-K). If you run a become playbook and the playbook seems to hang, it’sprobably stuck at the privilege escalation prompt. Just Control-C to kill it and run it again adding the appropriatepassword.
Important: When using become_user to a user other than root, the module arguments are briefly written intoa random tempfile in /tmp. These are deleted immediately after the command is executed. This only occurs whenchanging privileges from a user like ‘bob’ to ‘timmy’, not when going from ‘bob’ to ‘root’, or logging in directlyas ‘bob’ or ‘root’. If it concerns you that this data is briefly readable (not writable), avoid transferring unencryptedpasswords with become_user set. In other cases, /tmp is not used and this does not come into play. Ansible alsotakes care to not log password parameters.
Tasks list
Each play contains a list of tasks. Tasks are executed in order, one at a time, against all machines matched by the hostpattern, before moving on to the next task. It is important to understand that, within a play, all hosts are going to getthe same task directives. It is the purpose of a play to map a selection of hosts to tasks.
When running the playbook, which runs top to bottom, hosts with failed tasks are taken out of the rotation for theentire playbook. If things fail, simply correct the playbook file and rerun.
The goal of each task is to execute a module, with very specific arguments. Variables, as mentioned above, can beused in arguments to modules.
Modules are ‘idempotent’, meaning if you run them again, they will make only the changes they must in order to bringthe system to the desired state. This makes it very safe to rerun the same playbook multiple times. They won’t changethings unless they have to change things.
The command and shell modules will typically rerun the same command again, which is totally ok if the commandis something like chmod or setsebool, etc. Though there is a creates flag available which can be used to makethese modules also idempotent.
Every task should have a name, which is included in the output from running the playbook. This is output for humans,so it is nice to have reasonably good descriptions of each task step. If the name is not provided though, the string fedto ‘action’ will be used for output.
Tasks can be declared using the legacy action: module options format, but it is recommended that you usethe more conventional module: options format. This recommended format is used throughout the documenta-tion, but you may encounter the older format in some playbooks.
Here is what a basic task looks like. As with most modules, the service module takes key=value arguments:
tasks:- name: make sure apache is runningservice: name=httpd state=running
56 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
The command and shell modules are the only modules that just take a list of arguments and don’t use the key=valueform. This makes them work as simply as you would expect:
tasks:- name: disable selinuxcommand: /sbin/setenforce 0
The command and shell module care about return codes, so if you have a command whose successful exit code is notzero, you may wish to do this:
tasks:- name: run this command and ignore the resultshell: /usr/bin/somecommand || /bin/true
Or this:
tasks:- name: run this command and ignore the resultshell: /usr/bin/somecommandignore_errors: True
If the action line is getting too long for comfort you can break it on a space and indent any continuation lines:
tasks:- name: Copy ansible inventory file to clientcopy: src=/etc/ansible/hosts dest=/etc/ansible/hosts
owner=root group=root mode=0644
Variables can be used in action lines. Suppose you defined a variable called vhost in the vars section, you coulddo this:
tasks:- name: create a virtual host file for {{ vhost }}template: src=somefile.j2 dest=/etc/httpd/conf.d/{{ vhost }}
Those same variables are usable in templates, which we’ll get to later.
Now in a very basic playbook all the tasks will be listed directly in that play, though it will usually make more senseto break up tasks using the include: directive. We’ll show that a bit later.
Action Shorthand
New in version 0.8.
Ansible prefers listing modules like this in 0.8 and later:
template: src=templates/foo.j2 dest=/etc/foo.conf
You will notice in earlier versions, this was only available as:
action: template src=templates/foo.j2 dest=/etc/foo.conf
The old form continues to work in newer versions without any plan of deprecation.
1.3. Playbooks 57
Ansible 1.2 Documentation, Release 0.01
Handlers: Running Operations On Change
As we’ve mentioned, modules are written to be ‘idempotent’ and can relay when they have made a change on theremote system. Playbooks recognize this and have a basic event system that can be used to respond to change.
These ‘notify’ actions are triggered at the end of each block of tasks in a playbook, and will only be triggered onceeven if notified by multiple different tasks.
For instance, multiple resources may indicate that apache needs to be restarted because they have changed a configfile, but apache will only be bounced once to avoid unnecessary restarts.
Here’s an example of restarting two services when the contents of a file change, but only if the file changes:
- name: template configuration filetemplate: src=template.j2 dest=/etc/foo.confnotify:
- restart memcached- restart apache
The things listed in the notify section of a task are called handlers.
Handlers are lists of tasks, not really any different from regular tasks, that are referenced by a globally unique name.Handlers are what notifiers notify. If nothing notifies a handler, it will not run. Regardless of how many things notifya handler, it will run only once, after all of the tasks complete in a particular play.
Here’s an example handlers section:
handlers:- name: restart memcached
service: name=memcached state=restarted- name: restart apache
service: name=apache state=restarted
Handlers are best used to restart services and trigger reboots. You probably won’t need them for much else.
Note:
• Notify handlers are always run in the order written.
• Handler names live in a global namespace.
• If two handler tasks have the same name, only one will run. *
• You cannot notify a handler that is defined inside of an include
Roles are described later on, but it’s worthwhile to point out that:
• handlers notified within pre_tasks, tasks, and post_tasks sections are automatically flushed in the endof section where they were notified;
• handlers notified within roles section are automatically flushed in the end of tasks section, but before anytasks handlers.
If you ever want to flush all the handler commands immediately though, in 1.2 and later, you can:
tasks:- shell: some tasks go here- meta: flush_handlers- shell: some other tasks
58 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
In the above example any queued up handlers would be processed early when the meta statement was reached. Thisis a bit of a niche case but can come in handy from time to time.
Executing A Playbook
Now that you’ve learned playbook syntax, how do you run a playbook? It’s simple. Let’s run a playbook using aparallelism level of 10:
ansible-playbook playbook.yml -f 10
Ansible-Pull
Should you want to invert the architecture of Ansible, so that nodes check in to a central location, instead of pushingconfiguration out to them, you can.
The ansible-pull is a small script that will checkout a repo of configuration instructions from git, and then runansible-playbook against that content.
Assuming you load balance your checkout location, ansible-pull scales essentially infinitely.
Run ansible-pull --help for details.
There’s also a clever playbook available to configure ansible-pull via a crontab from push mode.
Tips and Tricks
Look at the bottom of the playbook execution for a summary of the nodes that were targeted and how they performed.General failures and fatal “unreachable” communication attempts are kept separate in the counts.
If you ever want to see detailed output from successful modules as well as unsuccessful ones, use the --verboseflag. This is available in Ansible 0.5 and later.
Ansible playbook output is vastly upgraded if the cowsay package is installed. Try it!
To see what hosts would be affected by a playbook before you run it, you can do this:
ansible-playbook playbook.yml --list-hosts
See also:
YAML Syntax Learn about YAML syntax
Best Practices Various tips about managing playbooks in the real world
Ansible Documentation Hop back to the documentation index for a lot of special topics about playbooks
About Modules Learn about available modules
Developing Modules Learn how to extend Ansible by writing your own modules
Patterns Learn about how to select hosts
Github examples directory Complete end-to-end playbook examples
Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
1.3. Playbooks 59
Ansible 1.2 Documentation, Release 0.01
Playbook Roles and Include Statements
Topics
• Playbook Roles and Include Statements
– Introduction
– Task Include Files And Encouraging Reuse
– Roles
– Role Default Variables
– Role Dependencies
– Embedding Modules In Roles
– Ansible Galaxy
Introduction
While it is possible to write a playbook in one very large file (and you might start out learning playbooks this way),eventually you’ll want to reuse files and start to organize things.
At a basic level, including task files allows you to break up bits of configuration policy into smaller files. Task includespull in tasks from other files. Since handlers are tasks too, you can also include handler files from the ‘handlers:’section.
See Playbooks if you need a review of these concepts.
Playbooks can also include plays from other playbook files. When that is done, the plays will be inserted into theplaybook to form a longer list of plays.
When you start to think about it – tasks, handlers, variables, and so on – begin to form larger concepts. You startto think about modeling what something is, rather than how to make something look like something. It’s no longer“apply this handful of THINGS to these hosts”, you say “these hosts are dbservers” or “these hosts are webservers”. Inprogramming, we might call that “encapsulating” how things work. For instance, you can drive a car without knowinghow the engine works.
Roles in Ansible build on the idea of include files and combine them to form clean, reusable abstractions – they allowyou to focus more on the big picture and only dive down into the details when needed.
We’ll start with understanding includes so roles make more sense, but our ultimate goal should be understanding roles– roles are great and you should use them every time you write playbooks.
See the ansible-examples repository on GitHub for lots of examples of all of this put together. You may wish to havethis open in a separate tab as you dive in.
Task Include Files And Encouraging Reuse
Suppose you want to reuse lists of tasks between plays or playbooks. You can use include files to do this. Use ofincluded task lists is a great way to define a role that system is going to fulfill. Remember, the goal of a play in aplaybook is to map a group of systems into multiple roles. Let’s see what this looks like...
A task include file simply contains a flat list of tasks, like so:
60 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
---# possibly saved as tasks/foo.yml
- name: placeholder foocommand: /bin/foo
- name: placeholder barcommand: /bin/bar
Include directives look like this, and can be mixed in with regular tasks in a playbook:
tasks:
- include: tasks/foo.yml
You can also pass variables into includes. We call this a ‘parameterized include’.
For instance, if deploying multiple wordpress instances, I could contain all of my wordpress tasks in a single word-press.yml file, and use it like so:
tasks:- include: wordpress.yml wp_user=timmy- include: wordpress.yml wp_user=alice- include: wordpress.yml wp_user=bob
Starting in 1.0, variables can also be passed to include files using an alternative syntax, which also supports structuredvariables:
tasks:
- include: wordpress.ymlvars:
wp_user: timmyssh_keys:- keys/one.txt- keys/two.txt
Using either syntax, variables passed in can then be used in the included files. We’ll cover them in Variables. You canreference them like this:
{{ wp_user }}
(In addition to the explicitly passed-in parameters, all variables from the vars section are also available for use here aswell.)
Playbooks can include other playbooks too, but that’s mentioned in a later section.
Note: As of 1.0, task include statements can be used at arbitrary depth. They were previously limited to a singlelevel, so task includes could not include other files containing task includes.
Includes can also be used in the ‘handlers’ section, for instance, if you want to define how to restart apache, you onlyhave to do that once for all of your playbooks. You might make a handlers.yml that looks like:
---# this might be in a file like handlers/handlers.yml- name: restart apache
service: name=apache state=restarted
1.3. Playbooks 61
Ansible 1.2 Documentation, Release 0.01
And in your main playbook file, just include it like so, at the bottom of a play:
handlers:- include: handlers/handlers.yml
You can mix in includes along with your regular non-included tasks and handlers.
Includes can also be used to import one playbook file into another. This allows you to define a top-level playbook thatis composed of other playbooks.
For example:
- name: this is a play at the top level of a filehosts: allremote_user: root
tasks:
- name: say hitags: fooshell: echo "hi..."
- include: load_balancers.yml- include: webservers.yml- include: dbservers.yml
Note that you cannot do variable substitution when including one playbook inside another.
Note: You can not conditionally pass the location to an include file, like you can with ‘vars_files’. If you find yourselfneeding to do this, consider how you can restructure your playbook to be more class/role oriented. This is to say youcannot use a ‘fact’ to decide what include file to use. All hosts contained within the play are going to get the sametasks. (‘when‘ provides some ability for hosts to conditionally skip tasks).
Roles
New in version 1.2.
Now that you have learned about tasks and handlers, what is the best way to organize your playbooks? The shortanswer is to use roles! Roles are ways of automatically loading certain vars_files, tasks, and handlers based on aknown file structure. Grouping content by roles also allows easy sharing of roles with other users.
Roles are just automation around ‘include’ directives as described above, and really don’t contain much additionalmagic beyond some improvements to search path handling for referenced files. However, that can be a big thing!
Example project structure:
site.ymlwebservers.ymlfooservers.ymlroles/
common/files/templates/tasks/handlers/
62 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
vars/defaults/meta/
webservers/files/templates/tasks/handlers/vars/defaults/meta/
In a playbook, it would look like this:
---- hosts: webservers
roles:- common- webservers
This designates the following behaviors, for each role ‘x’:
• If roles/x/tasks/main.yml exists, tasks listed therein will be added to the play
• If roles/x/handlers/main.yml exists, handlers listed therein will be added to the play
• If roles/x/vars/main.yml exists, variables listed therein will be added to the play
• If roles/x/meta/main.yml exists, any role dependencies listed therein will be added to the list of roles (1.3 andlater)
• Any copy, script, template or include tasks (in the role) can reference files in roles/x/{files,templates,tasks}/ (dirdepends on task) without having to path them relatively or absolutely
In Ansible 1.4 and later you can configure a roles_path to search for roles. Use this to check all of your common rolesout to one location, and share them easily between multiple playbook projects. See Configuration file for details abouthow to set this up in ansible.cfg.
Note: Role dependencies are discussed below.
If any files are not present, they are just ignored. So it’s ok to not have a ‘vars/’ subdirectory for the role, for instance.
Note, you are still allowed to list tasks, vars_files, and handlers “loose” in playbooks without using roles, but rolesare a good organizational feature and are highly recommended. If there are loose things in the playbook, the roles areevaluated first.
Also, should you wish to parameterize roles, by adding variables, you can do so, like this:
---
- hosts: webserversroles:- common- { role: foo_app_instance, dir: '/opt/a', port: 5000 }- { role: foo_app_instance, dir: '/opt/b', port: 5001 }
While it’s probably not something you should do often, you can also conditionally apply roles like so:
1.3. Playbooks 63
Ansible 1.2 Documentation, Release 0.01
---
- hosts: webserversroles:- { role: some_role, when: "ansible_os_family == 'RedHat'" }
This works by applying the conditional to every task in the role. Conditionals are covered later on in the documentation.
Finally, you may wish to assign tags to the roles you specify. You can do so inline::
---
- hosts: webserversroles:- { role: foo, tags: ["bar", "baz"] }
Note that this tags all of the tasks in that role with the tags specified, overriding any tags that are specified inside therole. If you find yourself building a role with lots of tags and you want to call subsets of the role at different times,you should consider just splitting that role into multiple roles.
If the play still has a ‘tasks’ section, those tasks are executed after roles are applied.
If you want to define certain tasks to happen before AND after roles are applied, you can do this:
---
- hosts: webservers
pre_tasks:- shell: echo 'hello'
roles:- { role: some_role }
tasks:- shell: echo 'still busy'
post_tasks:- shell: echo 'goodbye'
Note: If using tags with tasks (described later as a means of only running part of a playbook), be sure to also tagyour pre_tasks and post_tasks and pass those along as well, especially if the pre and post tasks are used for monitoringoutage window control or load balancing.
Role Default Variables
New in version 1.3.
Role default variables allow you to set default variables for included or dependent roles (see below). To create defaults,simply add a defaults/main.yml file in your role directory. These variables will have the lowest priority of any variablesavailable, and can be easily overridden by any other variable, including inventory variables.
Role Dependencies
New in version 1.3.
64 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Role dependencies allow you to automatically pull in other roles when using a role. Role dependencies are stored inthe meta/main.yml file contained within the role directory. This file should contain a list of roles and parameters toinsert before the specified role, such as the following in an example roles/myapp/meta/main.yml:
---dependencies:
- { role: common, some_parameter: 3 }- { role: apache, port: 80 }- { role: postgres, dbname: blarg, other_parameter: 12 }
Role dependencies can also be specified as a full path, just like top level roles:
---dependencies:
- { role: '/path/to/common/roles/foo', x: 1 }
Role dependencies can also be installed from source control repos or tar files (via galaxy) using comma separatedformat of path, an optional version (tag, commit, branch etc) and optional friendly role name (an attempt is made toderive a role name from the repo name or archive filename). Both through the command line or via a requirements.ymlpassed to ansible-galaxy.
Roles dependencies are always executed before the role that includes them, and are recursive. By default, roles canalso only be added as a dependency once - if another role also lists it as a dependency it will not be run again. Thisbehavior can be overridden by adding allow_duplicates: yes to the meta/main.yml file. For example, a role named‘car’ could add a role named ‘wheel’ to its dependencies as follows:
---dependencies:- { role: wheel, n: 1 }- { role: wheel, n: 2 }- { role: wheel, n: 3 }- { role: wheel, n: 4 }
And the meta/main.yml for wheel contained the following:
---allow_duplicates: yesdependencies:- { role: tire }- { role: brake }
The resulting order of execution would be as follows:
tire(n=1)brake(n=1)wheel(n=1)tire(n=2)brake(n=2)wheel(n=2)...car
Note: Variable inheritance and scope are detailed in the Variables.
1.3. Playbooks 65
Ansible 1.2 Documentation, Release 0.01
Embedding Modules In Roles
This is an advanced topic that should not be relevant for most users.
If you write a custom module (see Developing Modules) you may wish to distribute it as part of a role. Generallyspeaking, Ansible as a project is very interested in taking high-quality modules into ansible core for inclusion, so thisshouldn’t be the norm, but it’s quite easy to do.
A good example for this is if you worked at a company called AcmeWidgets, and wrote an internal module that helpedconfigure your internal software, and you wanted other people in your organization to easily use this module – but youdidn’t want to tell everyone how to configure their Ansible library path.
Alongside the ‘tasks’ and ‘handlers’ structure of a role, add a directory named ‘library’. In this ‘library’ directory,then include the module directly inside of it.
Assuming you had this:
roles/my_custom_modules/
library/module1module2
The module will be usable in the role itself, as well as any roles that are called after this role, as follows:
- hosts: webserversroles:- my_custom_modules- some_other_role_using_my_custom_modules- yet_another_role_using_my_custom_modules
This can also be used, with some limitations, to modify modules in Ansible’s core distribution, such as to use de-velopment versions of modules before they are released in production releases. This is not always advisable as APIsignatures may change in core components, however, and is not always guaranteed to work. It can be a handy way ofcarrying a patch against a core module, however, should you have good reason for this. Naturally the project prefersthat contributions be directed back to github whenever possible via a pull request.
Ansible Galaxy
Ansible Galaxy is a free site for finding, downloading, rating, and reviewing all kinds of community developed Ansibleroles and can be a great way to get a jumpstart on your automation projects.
You can sign up with social auth, and the download client ‘ansible-galaxy’ is included in Ansible 1.4.2 and later.
Read the “About” page on the Galaxy site for more information.
See also:
Ansible Galaxy How to share roles on galaxy, role management
YAML Syntax Learn about YAML syntax
Playbooks Review the basic Playbook language features
Best Practices Various tips about managing playbooks in the real world
Variables All about variables in playbooks
Conditionals Conditionals in playbooks
Loops Loops in playbooks
66 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
About Modules Learn about available modules
Developing Modules Learn how to extend Ansible by writing your own modules
GitHub Ansible examples Complete playbook files from the GitHub project source
Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
Variables
Topics
• Variables
– What Makes A Valid Variable Name
– Variables Defined in Inventory
– Variables Defined in a Playbook
– Variables defined from included files and roles
– Using Variables: About Jinja2
– Jinja2 Filters
– Hey Wait, A YAML Gotcha
– Information discovered from systems: Facts
– Turning Off Facts
– Local Facts (Facts.d)
– Fact Caching
– Registered Variables
– Accessing Complex Variable Data
– Magic Variables, and How To Access Information About Other Hosts
– Variable File Separation
– Passing Variables On The Command Line
– Variable Precedence: Where Should I Put A Variable?
– Variable Scopes
– Variable Examples
While automation exists to make it easier to make things repeatable, all of your systems are likely not exactly alike.
On some systems you may want to set some behavior or configuration that is slightly different from others.
Also, some of the observed behavior or state of remote systems might need to influence how you configure thosesystems. (Such as you might need to find out the IP address of a system and even use it as a configuration value onanother system).
You might have some templates for configuration files that are mostly the same, but slightly different based on thosevariables.
Variables in Ansible are how we deal with differences between systems.
1.3. Playbooks 67
Ansible 1.2 Documentation, Release 0.01
To understand variables you’ll also want to dig into Conditionals and Loops. Useful things like the group_by moduleand the when conditional can also be used with variables, and to help manage differences between systems.
It’s highly recommended that you consult the ansible-examples github repository to see a lot of examples of variablesput to use.
For best practices advice, refer to Variables and Vaults in the Best Practices chapter.
What Makes A Valid Variable Name
Before we start using variables it’s important to know what are valid variable names.
Variable names should be letters, numbers, and underscores. Variables should always start with a letter.
foo_port is a great variable. foo5 is fine too.
foo-port, foo port, foo.port and 12 are not valid variable names.
YAML also supports dictionaries which map keys to values. For instance:
foo:field1: onefield2: two
You can then reference a specific field in the dictionary using either bracket notation or dot notation:
foo['field1']foo.field1
These will both reference the same value (“one”). However, if you choose to use dot notation be aware that some keyscan cause problems because they collide with attributes and methods of python dictionaries. You should use bracketnotation instead of dot notation if you use keys which start and end with two underscores (Those are reserved forspecial meanings in python) or are any of the known public attributes:
add, append, as_integer_ratio, bit_length, capitalize, center, clear, conjugate, copy,count, decode, denominator, difference, difference_update, discard, encode, endswith,expandtabs, extend, find, format, fromhex, fromkeys, get, has_key, hex, imag, index,insert, intersection, intersection_update, isalnum, isalpha, isdecimal, isdigit,isdisjoint, is_integer, islower, isnumeric, isspace, issubset, issuperset, istitle,isupper, items, iteritems, iterkeys, itervalues, join, keys, ljust, lower, lstrip,numerator, partition, pop, popitem, real, remove, replace, reverse, rfind, rindex, rjust,rpartition, rsplit, rstrip, setdefault, sort, split, splitlines, startswith, strip,swapcase, symmetric_difference, symmetric_difference_update, title, translate, union,update, upper, values, viewitems, viewkeys, viewvalues, zfill.
Variables Defined in Inventory
We’ve actually already covered a lot about variables in another section, so far this shouldn’t be terribly new, but a bitof a refresher.
Often you’ll want to set variables based on what groups a machine is in. For instance, maybe machines in Boston wantto use ‘boston.ntp.example.com’ as an NTP server.
See the Inventory document for multiple ways on how to define variables in inventory.
68 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Variables Defined in a Playbook
In a playbook, it’s possible to define variables directly inline like so:
- hosts: webserversvars:http_port: 80
This can be nice as it’s right there when you are reading the playbook.
Variables defined from included files and roles
It turns out we’ve already talked about variables in another place too.
As described in Playbook Roles and Include Statements, variables can also be included in the playbook via includefiles, which may or may not be part of an “Ansible Role”. Usage of roles is preferred as it provides a nice organizationalsystem.
Using Variables: About Jinja2
It’s nice enough to know about how to define variables, but how do you use them?
Ansible allows you to reference variables in your playbooks using the Jinja2 templating system. While you can do alot of complex things in Jinja, only the basics are things you really need to learn at first.
For instance, in a simple template, you can do something like:
My amp goes to {{ max_amp_value }}
And that will provide the most basic form of variable substitution.
This is also valid directly in playbooks, and you’ll occasionally want to do things like:
template: src=foo.cfg.j2 dest={{ remote_install_path }}/foo.cfg
In the above example, we used a variable to help decide where to place a file.
Inside a template you automatically have access to all of the variables that are in scope for a host. Actually it’s morethan that – you can also read variables about other hosts. We’ll show how to do that in a bit.
Note: ansible allows Jinja2 loops and conditionals in templates, but in playbooks, we do not use them. Ansibleplaybooks are pure machine-parseable YAML. This is a rather important feature as it means it is possible to code-generate pieces of files, or to have other ecosystem tools read Ansible files. Not everyone will need this but it canunlock possibilities.
Jinja2 Filters
Note: These are infrequently utilized features. Use them if they fit a use case you have, but this is optional knowledge.
Filters in Jinja2 are a way of transforming template expressions from one kind of data into another. Jinja2 ships withmany of these. See builtin filters in the official Jinja2 template documentation.
1.3. Playbooks 69
Ansible 1.2 Documentation, Release 0.01
In addition to those, Ansible supplies many more. See the Jinja2 filters document for a list of available filters andexample usage guide.
Hey Wait, A YAML Gotcha
YAML syntax requires that if you start a value with {{ foo }} you quote the whole line, since it wants to be sureyou aren’t trying to start a YAML dictionary. This is covered on the YAML Syntax page.
This won’t work:
- hosts: app_serversvars:
app_path: {{ base_path }}/22
Do it like this and you’ll be fine:
- hosts: app_serversvars:
app_path: "{{ base_path }}/22"
Information discovered from systems: Facts
There are other places where variables can come from, but these are a type of variable that are discovered, not set bythe user.
Facts are information derived from speaking with your remote systems.
An example of this might be the ip address of the remote host, or what the operating system is.
To see what information is available, try the following:
ansible hostname -m setup
This will return a ginormous amount of variable data, which may look like this, as taken from Ansible 1.4 on a Ubuntu12.04 system:
"ansible_all_ipv4_addresses": ["REDACTED IP ADDRESS"
],"ansible_all_ipv6_addresses": [
"REDACTED IPV6 ADDRESS"],"ansible_architecture": "x86_64","ansible_bios_date": "09/20/2012","ansible_bios_version": "6.00","ansible_cmdline": {
"BOOT_IMAGE": "/boot/vmlinuz-3.5.0-23-generic","quiet": true,"ro": true,"root": "UUID=4195bff4-e157-4e41-8701-e93f0aec9e22","splash": true
},"ansible_date_time": {
"date": "2013-10-02","day": "02","epoch": "1380756810","hour": "19",
70 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
"iso8601": "2013-10-02T23:33:30Z","iso8601_micro": "2013-10-02T23:33:30.036070Z","minute": "33","month": "10","second": "30","time": "19:33:30","tz": "EDT","year": "2013"
},"ansible_default_ipv4": {
"address": "REDACTED","alias": "eth0","gateway": "REDACTED","interface": "eth0","macaddress": "REDACTED","mtu": 1500,"netmask": "255.255.255.0","network": "REDACTED","type": "ether"
},"ansible_default_ipv6": {},"ansible_devices": {
"fd0": {"holders": [],"host": "","model": null,"partitions": {},"removable": "1","rotational": "1","scheduler_mode": "deadline","sectors": "0","sectorsize": "512","size": "0.00 Bytes","support_discard": "0","vendor": null
},"sda": {
"holders": [],"host": "SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X
→˓Fusion-MPT Dual Ultra320 SCSI (rev 01)","model": "VMware Virtual S","partitions": {
"sda1": {"sectors": "39843840","sectorsize": 512,"size": "19.00 GB","start": "2048"
},"sda2": {
"sectors": "2","sectorsize": 512,"size": "1.00 KB","start": "39847934"
},"sda5": {
"sectors": "2093056","sectorsize": 512,"size": "1022.00 MB",
1.3. Playbooks 71
Ansible 1.2 Documentation, Release 0.01
"start": "39847936"}
},"removable": "0","rotational": "1","scheduler_mode": "deadline","sectors": "41943040","sectorsize": "512","size": "20.00 GB","support_discard": "0","vendor": "VMware,"
},"sr0": {
"holders": [],"host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)","model": "VMware IDE CDR10","partitions": {},"removable": "1","rotational": "1","scheduler_mode": "deadline","sectors": "2097151","sectorsize": "512","size": "1024.00 MB","support_discard": "0","vendor": "NECVMWar"
}},"ansible_distribution": "Ubuntu","ansible_distribution_release": "precise","ansible_distribution_version": "12.04","ansible_domain": "","ansible_env": {
"COLORTERM": "gnome-terminal","DISPLAY": ":0","HOME": "/home/mdehaan","LANG": "C","LESSCLOSE": "/usr/bin/lesspipe %s %s","LESSOPEN": "| /usr/bin/lesspipe %s","LOGNAME": "root","LS_COLORS": "rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;
→˓01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;→˓44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;→˓31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.→˓lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.→˓deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.→˓ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.→˓gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.→˓xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;→˓35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.→˓webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;→˓35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;→˓35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;→˓35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;→˓36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.→˓mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.→˓xspf=00;36:",
"MAIL": "/var/mail/root","OLDPWD": "/root/ansible/docsite",
72 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
"PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","PWD": "/root/ansible","SHELL": "/bin/bash","SHLVL": "1","SUDO_COMMAND": "/bin/bash","SUDO_GID": "1000","SUDO_UID": "1000","SUDO_USER": "mdehaan","TERM": "xterm","USER": "root","USERNAME": "root","XAUTHORITY": "/home/mdehaan/.Xauthority","_": "/usr/local/bin/ansible"
},"ansible_eth0": {
"active": true,"device": "eth0","ipv4": {
"address": "REDACTED","netmask": "255.255.255.0","network": "REDACTED"
},"ipv6": [
{"address": "REDACTED","prefix": "64","scope": "link"
}],"macaddress": "REDACTED","module": "e1000","mtu": 1500,"type": "ether"
},"ansible_form_factor": "Other","ansible_fqdn": "ubuntu2.example.com","ansible_hostname": "ubuntu2","ansible_interfaces": [
"lo","eth0"
],"ansible_kernel": "3.5.0-23-generic","ansible_lo": {
"active": true,"device": "lo","ipv4": {
"address": "127.0.0.1","netmask": "255.0.0.0","network": "127.0.0.0"
},"ipv6": [
{"address": "::1","prefix": "128","scope": "host"
}],"mtu": 16436,
1.3. Playbooks 73
Ansible 1.2 Documentation, Release 0.01
"type": "loopback"},"ansible_lsb": {
"codename": "precise","description": "Ubuntu 12.04.2 LTS","id": "Ubuntu","major_release": "12","release": "12.04"
},"ansible_machine": "x86_64","ansible_memfree_mb": 74,"ansible_memtotal_mb": 991,"ansible_mounts": [
{"device": "/dev/sda1","fstype": "ext4","mount": "/","options": "rw,errors=remount-ro","size_available": 15032406016,"size_total": 20079898624
}],"ansible_nodename": "ubuntu2.example.com","ansible_os_family": "Debian","ansible_pkg_mgr": "apt","ansible_processor": [
"Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz"],"ansible_processor_cores": 1,"ansible_processor_count": 1,"ansible_processor_threads_per_core": 1,"ansible_processor_vcpus": 1,"ansible_product_name": "VMware Virtual Platform","ansible_product_serial": "REDACTED","ansible_product_uuid": "REDACTED","ansible_product_version": "None","ansible_python_version": "2.7.3","ansible_selinux": false,"ansible_ssh_host_key_dsa_public": "REDACTED KEY VALUE""ansible_ssh_host_key_ecdsa_public": "REDACTED KEY VALUE""ansible_ssh_host_key_rsa_public": "REDACTED KEY VALUE""ansible_swapfree_mb": 665,"ansible_swaptotal_mb": 1021,"ansible_system": "Linux","ansible_system_vendor": "VMware, Inc.","ansible_user_id": "root","ansible_userspace_architecture": "x86_64","ansible_userspace_bits": "64","ansible_virtualization_role": "guest","ansible_virtualization_type": "VMware"
In the above the model of the first harddrive may be referenced in a template or playbook as:
{{ ansible_devices.sda.model }}
Similarly, the hostname as the system reports it is:
74 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
{{ ansible_nodename }}
and the unqualified hostname shows the string before the first period(.):
{{ ansible_hostname }}
Facts are frequently used in conditionals (see Conditionals) and also in templates.
Facts can be also used to create dynamic groups of hosts that match particular criteria, see the About Modules docu-mentation on group_by for details, as well as in generalized conditional statements as discussed in the Conditionalschapter.
Turning Off Facts
If you know you don’t need any fact data about your hosts, and know everything about your systems centrally, youcan turn off fact gathering. This has advantages in scaling Ansible in push mode with very large numbers of systems,mainly, or if you are using Ansible on experimental platforms. In any play, just do this:
- hosts: whatevergather_facts: no
Local Facts (Facts.d)
New in version 1.3.
As discussed in the playbooks chapter, Ansible facts are a way of getting data about remote systems for use in playbookvariables.
Usually these are discovered automatically by the setup module in Ansible. Users can also write custom facts modules,as described in the API guide. However, what if you want to have a simple way to provide system or user provideddata for use in Ansible variables, without writing a fact module?
For instance, what if you want users to be able to control some aspect about how their systems are managed? “Facts.d”is one such mechanism.
Note: Perhaps “local facts” is a bit of a misnomer, it means “locally supplied user values” as opposed to “centrallysupplied user values”, or what facts are – “locally dynamically determined values”.
If a remotely managed system has an /etc/ansible/facts.d directory, any files in this directory ending in.fact, can be JSON, INI, or executable files returning JSON, and these can supply local facts in Ansible.
For instance assume a /etc/ansible/facts.d/preferences.fact:
[general]asdf=1bar=2
This will produce a hash variable fact named general with asdf and bar as members. To validate this, run thefollowing:
ansible <hostname> -m setup -a "filter=ansible_local"
And you will see the following fact added:
1.3. Playbooks 75
Ansible 1.2 Documentation, Release 0.01
"ansible_local": {"preferences": {
"general": {"asdf" : "1","bar" : "2"
}}
}
And this data can be accessed in a template/playbook as:
{{ ansible_local.preferences.general.asdf }}
The local namespace prevents any user supplied fact from overriding system facts or variables defined elsewhere inthe playbook.
If you have a playbook that is copying over a custom fact and then running it, making an explicit call to re-run thesetup module can allow that fact to be used during that particular play. Otherwise, it will be available in the next playthat gathers fact information. Here is an example of what that might look like:
- hosts: webserverstasks:- name: create directory for ansible custom facts
file: state=directory recurse=yes path=/etc/ansible/facts.d- name: install custom impi fact
copy: src=ipmi.fact dest=/etc/ansible/facts.d- name: re-read facts after adding custom fact
setup: filter=ansible_local
In this pattern however, you could also write a fact module as well, and may wish to consider this as an option.
Fact Caching
New in version 1.8.
As shown elsewhere in the docs, it is possible for one server to reference variables about another, like so:
{{ hostvars['asdf.example.com']['ansible_os_family'] }}
With “Fact Caching” disabled, in order to do this, Ansible must have already talked to ‘asdf.example.com’ in thecurrent play, or another play up higher in the playbook. This is the default configuration of ansible.
To avoid this, Ansible 1.8 allows the ability to save facts between playbook runs, but this feature must be manuallyenabled. Why might this be useful?
Imagine, for instance, a very large infrastructure with thousands of hosts. Fact caching could be configured to runnightly, but configuration of a small set of servers could run ad-hoc or periodically throughout the day. With fact-caching enabled, it would not be necessary to “hit” all servers to reference variables and information about them.
With fact caching enabled, it is possible for machine in one group to reference variables about machines in theother group, despite the fact that they have not been communicated with in the current execution of /usr/bin/ansible-playbook.
To benefit from cached facts, you will want to change the gathering setting to smart or explicit or setgather_facts to False in most plays.
Currently, Ansible ships with two persistent cache plugins: redis and jsonfile.
To configure fact caching using redis, enable it in ansible.cfg as follows:
76 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
[defaults]gathering = smartfact_caching = redisfact_caching_timeout = 86400# seconds
To get redis up and running, perform the equivalent OS commands:
yum install redisservice redis startpip install redis
Note that the Python redis library should be installed from pip, the version packaged in EPEL is too old for use byAnsible.
In current embodiments, this feature is in beta-level state and the Redis plugin does not support port or passwordconfiguration, this is expected to change in the near future.
To configure fact caching using jsonfile, enable it in ansible.cfg as follows:
[defaults]gathering = smartfact_caching = jsonfilefact_caching_connection = /path/to/cachedirfact_caching_timeout = 86400# seconds
fact_caching_connection is a local filesystem path to a writeable directory (ansible will attempt to create thedirectory if one does not exist).
fact_caching_timeout is the number of seconds to cache the recorded facts.
Registered Variables
Another major use of variables is running a command and using the result of that command to save the result into avariable. Results will vary from module to module. Use of -v when executing playbooks will show possible valuesfor the results.
The value of a task being executed in ansible can be saved in a variable and used later. See some examples of this inthe Conditionals chapter.
While it’s mentioned elsewhere in that document too, here’s a quick syntax example:
- hosts: web_servers
tasks:
- shell: /usr/bin/fooregister: foo_resultignore_errors: True
- shell: /usr/bin/barwhen: foo_result.rc == 5
Registered variables are valid on the host the remainder of the playbook run, which is the same as the lifetime of“facts” in Ansible. Effectively registered variables are just like facts.
1.3. Playbooks 77
Ansible 1.2 Documentation, Release 0.01
Note: If a task fails or is skipped, the variable still is registered with a failure or skipped status, the only way to avoidregistering a variable is using tags.
Accessing Complex Variable Data
We already talked about facts a little higher up in the documentation.
Some provided facts, like networking information, are made available as nested data structures. To access them asimple {{ foo }} is not sufficient, but it is still easy to do. Here’s how we get an IP address:
{{ ansible_eth0["ipv4"]["address"] }}
OR alternatively:
{{ ansible_eth0.ipv4.address }}
Similarly, this is how we access the first element of an array:
{{ foo[0] }}
Magic Variables, and How To Access Information About Other Hosts
Even if you didn’t define them yourself, Ansible provides a few variables for you automatically. The most importantof these are hostvars, group_names, and groups. Users should not use these names themselves as they arereserved. environment is also reserved.
hostvars lets you ask about the variables of another host, including facts that have been gathered about that host.If, at this point, you haven’t talked to that host yet in any play in the playbook or set of playbooks, you can get at thevariables, but you will not be able to see the facts.
If your database server wants to use the value of a ‘fact’ from another node, or an inventory variable assigned toanother node, it’s easy to do so within a template or even an action line:
{{ hostvars['test.example.com']['ansible_distribution'] }}
Additionally, group_names is a list (array) of all the groups the current host is in. This can be used in templatesusing Jinja2 syntax to make template source files that vary based on the group membership (or role) of the host:
{% if 'webserver' in group_names %}# some part of a configuration file that only applies to webservers
{% endif %}
groups is a list of all the groups (and hosts) in the inventory. This can be used to enumerate all hosts within a group.For example:
{% for host in groups['app_servers'] %}# something that applies to all app servers.
{% endfor %}
A frequently used idiom is walking a group to find all IP addresses in that group:
{% for host in groups['app_servers'] %}{{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}
78 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
An example of this could include pointing a frontend proxy server to all of the app servers, setting up the correctfirewall rules between servers, etc. You need to make sure that the facts of those hosts have been populated beforethough, for example by running a play against them if the facts have not been cached recently (fact caching was addedin Ansible 1.8).
Additionally, inventory_hostname is the name of the hostname as configured in Ansible’s inventory host file.This can be useful for when you don’t want to rely on the discovered hostname ansible_hostname or for othermysterious reasons. If you have a long FQDN, inventory_hostname_short also contains the part up to thefirst period, without the rest of the domain.
play_hosts is available as a list of hostnames that are in scope for the current play. This may be useful for fillingout templates with multiple hostnames or for injecting the list into the rules for a load balancer.
delegate_to is the inventory hostname of the host that the current task has been delegated to using delegate_tokeyword.
Don’t worry about any of this unless you think you need it. You’ll know when you do.
Also available, inventory_dir is the pathname of the directory holding Ansible’s inventory host file,inventory_file is the pathname and the filename pointing to the Ansible’s inventory host file.
And finally, role_path will return the current role’s pathname (since 1.8). This will only work inside a role.
Variable File Separation
It’s a great idea to keep your playbooks under source control, but you may wish to make the playbook source publicwhile keeping certain important variables private. Similarly, sometimes you may just want to keep certain informationin different files, away from the main playbook.
You can do this by using an external variables file, or files, just like this:
---
- hosts: allremote_user: rootvars:favcolor: blue
vars_files:- /vars/external_vars.yml
tasks:
- name: this is just a placeholdercommand: /bin/echo foo
This removes the risk of sharing sensitive data with others when sharing your playbook source with them.
The contents of each variables file is a simple YAML dictionary, like this:
---# in the above example, this would be vars/external_vars.ymlsomevar: somevaluepassword: magic
Note: It’s also possible to keep per-host and per-group variables in very similar files, this is covered in Splitting OutHost and Group Specific Data.
1.3. Playbooks 79
Ansible 1.2 Documentation, Release 0.01
Passing Variables On The Command Line
In addition to vars_prompt and vars_files, it is possible to send variables over the Ansible command line.This is particularly useful when writing a generic release playbook where you may want to pass in the version of theapplication to deploy:
ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo"
This is useful, for, among other things, setting the hosts group or the user for the playbook.
Example:
---
- hosts: '{{ hosts }}'remote_user: '{{ user }}'
tasks:- ...
ansible-playbook release.yml --extra-vars "hosts=vipers user=starbuck"
As of Ansible 1.2, you can also pass in extra vars as quoted JSON, like so:
--extra-vars '{"pacman":"mrs","ghosts":["inky","pinky","clyde","sue"]}'
The key=value form is obviously simpler, but it’s there if you need it!
As of Ansible 1.3, extra vars can be loaded from a JSON file with the @ syntax:
--extra-vars "@some_file.json"
Also as of Ansible 1.3, extra vars can be formatted as YAML, either on the command line or in a file as above.
Variable Precedence: Where Should I Put A Variable?
A lot of folks may ask about how variables override another. Ultimately it’s Ansible’s philosophy that it’s better youknow where to put a variable, and then you have to think about it a lot less.
Avoid defining the variable “x” in 47 places and then ask the question “which x gets used”. Why? Because that’s notAnsible’s Zen philosophy of doing things.
There is only one Empire State Building. One Mona Lisa, etc. Figure out where to define a variable, and don’t makeit complicated.
However, let’s go ahead and get precedence out of the way! It exists. It’s a real thing, and you might have a use for it.
If multiple variables of the same name are defined in different places, they get overwritten in a certain order.
Note: Ansible 2.0 has deprecated the “ssh” from ansible_ssh_user, ansible_ssh_host, andansible_ssh_port to become ansible_user, ansible_host, and ansible_port. If you are usinga version of Ansible prior to 2.0, you should continue using the older style variables (ansible_ssh_*). Theseshorter variables are ignored, without warning, in older versions of Ansible.
In 1.x the precedence is (last listed wins):
• then “role defaults”, which are the most “defaulty” and lose in priority to everything.
80 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• then come the variables defined in inventory
• then come the facts discovered about a system
• then comes “most everything else” (command line switches, vars in play, included vars, role vars, etc)
• then come connection variables (ansible_user, etc)
• extra vars (-e in the command line) always win
Note: In versions prior to 1.5.4, facts discovered about a system were in the “most everything else” category above.
In 2.x we have made the order of precedence more specific (last listed wins):
• role defaults1
• inventory vars2
• inventory group_vars
• inventory host_vars
• playbook group_vars
• playbook host_vars
• host facts
• registered vars
• set_facts
• play vars
• play vars_prompt
• play vars_files
• role and include vars
• block vars (only for tasks in block)
• task vars (only for the task)
• extra vars
Basically, anything that goes into “role defaults” (the defaults folder inside the role) is the most malleable and easilyoverridden. Anything in the vars directory of the role overrides previous versions of that variable in namespace. Theidea here to follow is that the more explicit you get in scope, the more precedence it takes with command line -e extravars always winning. Host and/or inventory variables can win over role defaults, but not explicit includes like the varsdirectory or an include_vars task.
Note: Within any section, redefining a var will overwrite the previous instance. If multiple groups have the samevariable, the last one loaded wins. If you define a variable twice in a play’s vars: section, the 2nd one wins.
Note: the previous describes the default config hash_behavior=replace, switch to ‘merge’ to only partially overwrite.
Another important thing to consider (for all versions) is that connection specific variables override config, commandline and play specific options and directives. For example:
1 Tasks in each role will see their own role’s defaults. Tasks defined outside of a role will see the last role’s defaults.2 Variables defined in inventory file or provided by dynamic inventory.
1.3. Playbooks 81
Ansible 1.2 Documentation, Release 0.01
ansible_ssh_user will override `-u <user>` and `remote_user: <user>`
This is done so host specific settings can override the general settings. These variables are normally defined per hostor group in inventory, but they behave like other variables, so if you really want to override the remote user globallyeven over inventory you can use extra vars:
ansible... -e "ansible_ssh_user=<user>"
Variable Scopes
Ansible has 3 main scopes:
• Global: this is set by config, environment variables and the command line
• Play: each play and contained structures, vars entries, include_vars, role defaults and vars.
• Host: variables directly associated to a host, like inventory, facts or registered task outputs
Variable Examples
That seems a little theoretical. Let’s show some examples and where you would choose to put what based on the kindof control you might want over values.
First off, group variables are super powerful.
Site wide defaults should be defined as a group_vars/all setting. Group variables are generally placed alongsideyour inventory file. They can also be returned by a dynamic inventory script (see Dynamic Inventory) or defined inthings like Ansible Tower from the UI or API:
---# file: /etc/ansible/group_vars/all# this is the site wide defaultntp_server: default-time.example.com
Regional information might be defined in a group_vars/region variable. If this group is a child of the allgroup (which it is, because all groups are), it will override the group that is higher up and more general:
---# file: /etc/ansible/group_vars/bostonntp_server: boston-time.example.com
If for some crazy reason we wanted to tell just a specific host to use a specific NTP server, it would then override thegroup variable!:
---# file: /etc/ansible/host_vars/xyz.boston.example.comntp_server: override.example.com
So that covers inventory and what you would normally set there. It’s a great place for things that deal with geographyor behavior. Since groups are frequently the entity that maps roles onto hosts, it is sometimes a shortcut to set variableson the group instead of defining them on a role. You could go either way.
Remember: Child groups override parent groups, and hosts always override their groups.
Next up: learning about role variable precedence.
82 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
We’ll pretty much assume you are using roles at this point. You should be using roles for sure. Roles are great. Youare using roles aren’t you? Hint hint.
Ok, so if you are writing a redistributable role with reasonable defaults, put those in the roles/x/defaults/main.yml file. This means the role will bring along a default value but ANYTHING in Ansible will override it. It’sjust a default. That’s why it says “defaults” :) See Playbook Roles and Include Statements for more info about this:
---# file: roles/x/defaults/main.yml# if not overridden in inventory or as a parameter, this is the value that will be→˓usedhttp_port: 80
If you are writing a role and want to ensure the value in the role is absolutely used in that role, and is not going tobe overridden by inventory, you should put it in roles/x/vars/main.yml like so, and inventory values cannotoverride it. -e however, still will:
---# file: roles/x/vars/main.yml# this will absolutely be used in this rolehttp_port: 80
So the above is a great way to plug in constants about the role that are always true. If you are not sharing your rolewith others, app specific behaviors like ports is fine to put in here. But if you are sharing roles with others, puttingvariables in here might be bad. Nobody will be able to override them with inventory, but they still can by passing aparameter to the role.
Parameterized roles are useful.
If you are using a role and want to override a default, pass it as a parameter to the role like so:
roles:- { role: apache, http_port: 8080 }
This makes it clear to the playbook reader that you’ve made a conscious choice to override some default in the role, orpass in some configuration that the role can’t assume by itself. It also allows you to pass something site-specific thatisn’t really part of the role you are sharing with others.
This can often be used for things that might apply to some hosts multiple times, like so:
roles:- { role: app_user, name: Ian }- { role: app_user, name: Terry }- { role: app_user, name: Graham }- { role: app_user, name: John }
That’s a bit arbitrary, but you can see how the same role was invoked multiple Times. In that example it’s quite likelythere was no default for ‘name’ supplied at all. Ansible can yell at you when variables aren’t defined – it’s the defaultbehavior in fact.
So that’s a bit about roles.
There are a few bonus things that go on with roles.
Generally speaking, variables set in one role are available to others. This means if you have a roles/common/vars/main.yml you can set variables in there and make use of them in other roles and elsewhere in your playbook:
roles:- { role: common_settings }
1.3. Playbooks 83
Ansible 1.2 Documentation, Release 0.01
- { role: something, foo: 12 }- { role: something_else }
Note: There are some protections in place to avoid the need to namespace variables. In the above, variables definedin common_settings are most definitely available to ‘something’ and ‘something_else’ tasks, but if “something’s”guaranteed to have foo set at 12, even if somewhere deep in common settings it set foo to 20.
So, that’s precedence, explained in a more direct way. Don’t worry about precedence, just think about if your role isdefining a variable that is a default, or a “live” variable you definitely want to use. Inventory lies in precedence rightin the middle, and if you want to forcibly override something, use -e.
If you found that a little hard to understand, take a look at the ansible-examples repo on our github for a bit more abouthow all of these things can work together.
See also:
Playbooks An introduction to playbooks
Conditionals Conditional statements in playbooks
Jinja2 filters Jinja2 filters and their uses
Loops Looping in playbooks
Playbook Roles and Include Statements Playbook organization by roles
Best Practices Best practices in playbooks
User Mailing List Have a question? Stop by the google group!
irc.freenode.net #ansible IRC chat channel
Jinja2 filters
Topics
• Jinja2 filters
– Filters For Formatting Data
– Filters Often Used With Conditionals
– Forcing Variables To Be Defined
– Defaulting Undefined Variables
– Omitting Undefined Variables and Parameters
– List Filters
– Set Theory Filters
– Version Comparison Filters
– Random Number Filter
– Shuffle Filter
– Math
84 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
– IP address filter
– Hashing filters
– Combining hashes/dictionaries
– Comment Filter
– Other Useful Filters
Filters in Jinja2 are a way of transforming template expressions from one kind of data into another. Jinja2 ships withmany of these. See builtin filters in the official Jinja2 template documentation.
In addition to those, Ansible supplies many more.
Filters For Formatting Data
The following filters will take a data structure in a template and render it in a slightly different format. These areoccasionally useful for debugging:
{{ some_variable | to_json }}{{ some_variable | to_yaml }}
For human readable output, you can use:
{{ some_variable | to_nice_json }}{{ some_variable | to_nice_yaml }}
Alternatively, you may be reading in some already formatted data:
{{ some_variable | from_json }}{{ some_variable | from_yaml }}
for example:
tasks:- shell: cat /some/path/to/file.jsonregister: result
- set_fact: myvar="{{ result.stdout | from_json }}"
Filters Often Used With Conditionals
The following tasks are illustrative of how filters can be used with conditionals:
tasks:
- shell: /usr/bin/fooregister: resultignore_errors: True
- debug: msg="it failed"when: result|failed
# in most cases you'll want a handler, but if you want to do something right now,→˓this is nice- debug: msg="it changed"
1.3. Playbooks 85
Ansible 1.2 Documentation, Release 0.01
when: result|changed
- debug: msg="it succeeded"when: result|success
- debug: msg="it was skipped"when: result|skipped
Forcing Variables To Be Defined
The default behavior from ansible and ansible.cfg is to fail if variables are undefined, but you can turn this off.
This allows an explicit check with this feature off:
{{ variable | mandatory }}
The variable value will be used as is, but the template evaluation will raise an error if it is undefined.
Defaulting Undefined Variables
Jinja2 provides a useful ‘default’ filter, that is often a better approach to failing if a variable is not defined:
{{ some_variable | default(5) }}
In the above example, if the variable ‘some_variable’ is not defined, the value used will be 5, rather than an error beingraised.
Omitting Undefined Variables and Parameters
As of Ansible 1.8, it is possible to use the default filter to omit variables and module parameters using the special omitvariable:
- name: touch files with an optional modefile: dest={{item.path}} state=touch mode={{item.mode|default(omit)}}with_items:- path: /tmp/foo- path: /tmp/bar- path: /tmp/baz
mode: "0444"
For the first two files in the list, the default mode will be determined by the umask of the system as the mode=parameter will not be sent to the file module while the final file will receive the mode=0444 option.
Note: If you are “chaining” additional filters after the default(omit) filter, you should instead do something like this:“{{ foo | default(None) | some_filter or omit }}”. In this example, the default None (python null) value will cause thelater filters to fail, which will trigger the or omit portion of the logic. Using omit in this manner is very specific to thelater filters you’re chaining though, so be prepared for some trial and error if you do this.
List Filters
These filters all operate on list variables.
86 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
New in version 1.8.
To get the minimum value from list of numbers:
{{ list1 | min }}
To get the maximum value from a list of numbers:
{{ [3, 4, 2] | max }}
Set Theory Filters
All these functions return a unique set from sets or lists.
New in version 1.4.
To get a unique set from a list:
{{ list1 | unique }}
To get a union of two lists:
{{ list1 | union(list2) }}
To get the intersection of 2 lists (unique list of all items in both):
{{ list1 | intersect(list2) }}
To get the difference of 2 lists (items in 1 that don’t exist in 2):
{{ list1 | difference(list2) }}
To get the symmetric difference of 2 lists (items exclusive to each list):
{{ list1 | symmetric_difference(list2) }}
Version Comparison Filters
New in version 1.6.
To compare a version number, such as checking if the ansible_distribution_version version is greaterthan or equal to ‘12.04’, you can use the version_compare filter.
The version_compare filter can also be used to evaluate the ansible_distribution_version:
{{ ansible_distribution_version | version_compare('12.04', '>=') }}
If ansible_distribution_version is greater than or equal to 12, this filter will return True, otherwise it willreturn False.
The version_compare filter accepts the following operators:
<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne
This filter also accepts a 3rd parameter, strict which defines if strict version parsing should be used. The default isFalse, and if set as True will use more strict version parsing:
1.3. Playbooks 87
Ansible 1.2 Documentation, Release 0.01
{{ sample_version_var | version_compare('1.0', operator='lt', strict=True) }}
Random Number Filter
New in version 1.6.
This filter can be used similar to the default jinja2 random filter (returning a random item from a sequence of items),but can also generate a random number based on a range.
To get a random item from a list:
{{ ['a','b','c']|random }} => 'c'
To get a random number from 0 to supplied end:
{{ 59 |random}} * * * * root /script/from/cron
Get a random number from 0 to 100 but in steps of 10:
{{ 100 |random(step=10) }} => 70
Get a random number from 1 to 100 but in steps of 10:
{{ 100 |random(1, 10) }} => 31{{ 100 |random(start=1, step=10) }} => 51
Shuffle Filter
New in version 1.8.
This filter will randomize an existing list, giving a different order every invocation.
To get a random list from an existing list:
{{ ['a','b','c']|shuffle }} => ['c','a','b']{{ ['a','b','c']|shuffle }} => ['b','c','a']
note that when used with a non ‘listable’ item it is a noop, otherwise it always returns a list
Math
New in version 1.9.
To see if something is actually a number:
{{ myvar | isnan }}
Get the logarithm (default is e):
{{ myvar | log }}
Get the base 10 logarithm:
{{ myvar | log(10) }}
88 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Give me the power of 2! (or 5):
{{ myvar | pow(2) }}{{ myvar | pow(5) }}
Square root, or the 5th:
{{ myvar | root }}{{ myvar | root(5) }}
Note that jinja2 already provides some like abs() and round().
IP address filter
New in version 1.9.
To test if a string is a valid IP address:
{{ myvar | ipaddr }}
You can also require a specific IP protocol version:
{{ myvar | ipv4 }}{{ myvar | ipv6 }}
IP address filter can also be used to extract specific information from an IP address. For example, to get the IP addressitself from a CIDR, you can use:
{{ '192.0.2.1/24' | ipaddr('address') }}
More information about ipaddr filter and complete usage guide can be found in playbooks_filters_ipaddr.
Hashing filters
New in version 1.9.
To get the sha1 hash of a string:
{{ 'test1'|hash('sha1') }}
To get the md5 hash of a string:
{{ 'test1'|hash('md5') }}
Get a string checksum:
{{ 'test2'|checksum }}
Other hashes (platform dependent):
{{ 'test2'|hash('blowfish') }}
To get a sha512 password hash (random salt):
{{ 'passwordsaresecret'|password_hash('sha512') }}
1.3. Playbooks 89
Ansible 1.2 Documentation, Release 0.01
To get a sha256 password hash with a specific salt:
{{ 'secretpassword'|password_hash('sha256', 'mysecretsalt') }}
Hash types available depend on the master system running ansible, ‘hash’ depends on hashlib password_hash dependson crypt.
Combining hashes/dictionaries
New in version 2.0.
The combine filter allows hashes to be merged. For example, the following would override keys in one hash:
{{ {'a':1, 'b':2}|combine({'b':3}) }}
The resulting hash would be:
{'a':1, 'b':3}
The filter also accepts an optional recursive=True parameter to not only override keys in the first hash, but also recurseinto nested hashes and merge their keys too:
{{ {'a':{'foo':1, 'bar':2}, 'b':2}|combine({'a':{'bar':3, 'baz':4}}, recursive=True) }→˓}
This would result in:
{'a':{'foo':1, 'bar':3, 'baz':4}, 'b':2}
The filter can also take multiple arguments to merge:
{{ a|combine(b, c, d) }}
In this case, keys in d would override those in c, which would override those in b, and so on.
This behaviour does not depend on the value of the hash_behaviour setting in ansible.cfg.
Comment Filter
New in version 2.0.
The comment filter allows to decorate the text with a chosen comment style. For example the following:
{{ "Plain style (default)" | comment }}
will produce this output:
## Plain style (default)#
Similar way can be applied style for C (//...), C block (/*...*/), Erlang (%...) and XML (<!--...-->):
{{ "C style" | comment('c') }}{{ "C block style" | comment('cblock') }}{{ "Erlang style" | comment('erlang') }}{{ "XML style" | comment('xml') }}
90 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
It is also possible to fully customize the comment style:
{{ "Custom style" | comment('plain', prefix='#######\n#', postfix='#\n#######\n ##→˓#\n #') }}
That will create the following output:
######### Custom style########
####
The filter can also be applied to any Ansible variable. For example to make the output of the ansible_managedvariable more readable, we can change the definition in the ansible.cfg file to this:
[defaults]
ansible_managed = This file is managed by Ansible.%ntemplate: {file}date: %Y-%m-%d %H:%M:%Suser: {uid}host: {host}
and then use the variable with the comment filter:
{{ ansible_managed | comment }}
which will produce this output:
## This file is managed by Ansible.## template: /home/ansible/env/dev/ansible_managed/roles/role1/templates/test.j2# date: 2015-09-10 11:02:58# user: ansible# host: myhost#
Other Useful Filters
To add quotes for shell usage:
- shell: echo {{ string_value | quote }}
To use one value on true and another on false (new in version 1.9):
{{ (name == "John") | ternary('Mr','Ms') }}
To concatenate a list into a string:
{{ list | join(" ") }}
To get the last name of a file path, like ‘foo.txt’ out of ‘/etc/asdf/foo.txt’:
1.3. Playbooks 91
Ansible 1.2 Documentation, Release 0.01
{{ path | basename }}
To get the last name of a windows style file path (new in version 2.0):
{{ path | win_basename }}
To separate the windows drive letter from the rest of a file path (new in version 2.0):
{{ path | win_splitdrive }}
To get only the windows drive letter:
{{ path | win_splitdrive | first }}
To get the rest of the path without the drive letter:
{{ path | win_splitdrive | last }}
To get the directory from a path:
{{ path | dirname }}
To get the directory from a windows path (new version 2.0):
{{ path | win_dirname }}
To expand a path containing a tilde (~) character (new in version 1.5):
{{ path | expanduser }}
To get the real path of a link (new in version 1.8):
{{ path | realpath }}
To get the relative path of a link, from a start point (new in version 1.7):
{{ path | relpath('/etc') }}
To get the root and extension of a path or filename (new in version 2.0):
# with path == 'nginx.conf' the return would be ('nginx', '.conf'){{ path | splitext }}
To work with Base64 encoded strings:
{{ encoded | b64decode }}{{ decoded | b64encode }}
To create a UUID from a string (new in version 1.9):
{{ hostname | to_uuid }}
To cast values as certain types, such as when you input a string as “True” from a vars_prompt and the system doesn’tknow it is a boolean value:
- debug: msg=testwhen: some_string_value | bool
92 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
To match strings against a regex, use the “match” or “search” filter:
vars:url: "http://example.com/users/foo/resources/bar"
tasks:- shell: "msg='matched pattern 1'"
when: url | match("http://example.com/users/.*/resources/.*")
- debug: "msg='matched pattern 2'"when: url | search("/users/.*/resources/.*")
‘match’ will require a complete match in the string, while ‘search’ will require a match inside of the string.
New in version 1.6.
To replace text in a string with regex, use the “regex_replace” filter:
# convert "ansible" to "able"{{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\\1') }}
# convert "foobar" to "bar"{{ 'foobar' | regex_replace('^f.*o(.*)$', '\\1') }}
# convert "localhost:80" to "localhost, 80" using named groups{{ 'localhost:80' | regex_replace('^(?P<host>.+):(?P<port>\\d+)$', '\\g<host>, \\g→˓<port>') }}
Note: Prior to ansible 2.0, if “regex_replace” filter was used with variables inside YAML arguments (as opposedto simpler ‘key=value’ arguments), then you needed to escape backreferences (e.g. \\1) with 4 backslashes (\\\\)instead of 2 (\\).
New in version 2.0.
To escape special characters within a regex, use the “regex_escape” filter:
# convert '^f.*o(.*)$' to '\^f\.\*o\(\.\*\)\$'{{ '^f.*o(.*)$' | regex_escape() }}
To make use of one attribute from each item in a list of complex variables, use the “map” filter (see the Jinja2 map()docs for more):
# get a comma-separated list of the mount points (e.g. "/,/mnt/stuff") on a host{{ ansible_mounts|map(attribute='mount')|join(',') }}
A few useful filters are typically added with each new Ansible release. The development documentation shows how toextend Ansible filters by writing your own as plugins, though in general, we encourage new ones to be added to coreso everyone can make use of them.
See also:
Playbooks An introduction to playbooks
Conditionals Conditional statements in playbooks
Variables All about variables
Loops Looping in playbooks
Playbook Roles and Include Statements Playbook organization by roles
1.3. Playbooks 93
Ansible 1.2 Documentation, Release 0.01
Best Practices Best practices in playbooks
User Mailing List Have a question? Stop by the google group!
irc.freenode.net #ansible IRC chat channel
Conditionals
Topics
• Conditionals
– The When Statement
– Loading in Custom Facts
– Applying ‘when’ to roles and includes
– Conditional Imports
– Selecting Files And Templates Based On Variables
– Register Variables
Often the result of a play may depend on the value of a variable, fact (something learned about the remote system), orprevious task result. In some cases, the values of variables may depend on other variables. Further, additional groupscan be created to manage hosts based on whether the hosts match other criteria. There are many options to controlexecution flow in Ansible.
Let’s dig into what they are.
The When Statement
Sometimes you will want to skip a particular step on a particular host. This could be something as simple as notinstalling a certain package if the operating system is a particular version, or it could be something like performingsome cleanup steps if a filesystem is getting full.
This is easy to do in Ansible, with the when clause, which contains a Jinja2 expression (see Variables). It’s actuallypretty simple:
tasks:- name: "shutdown Debian flavored systems"command: /sbin/shutdown -t nowwhen: ansible_os_family == "Debian"
You can also use parentheses to group conditions:
tasks:- name: "shutdown CentOS 6 and Debian 7 systems"command: /sbin/shutdown -t nowwhen: (ansible_distribution == "CentOS" and ansible_distribution_major_version ==
→˓"6") or(ansible_distribution == "Debian" and ansible_distribution_major_version ==
→˓"7")
94 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
A number of Jinja2 “filters” can also be used in when statements, some of which are unique and provided by Ansible.Suppose we want to ignore the error of one statement and then decide to do something conditionally based on successor failure:
tasks:- command: /bin/falseregister: resultignore_errors: True
- command: /bin/somethingwhen: result|failed
- command: /bin/something_elsewhen: result|success
- command: /bin/still/something_elsewhen: result|skipped
Note that was a little bit of foreshadowing on the ‘register’ statement. We’ll get to it a bit later in this chapter.
As a reminder, to see what facts are available on a particular system, you can do:
ansible hostname.example.com -m setup
Tip: Sometimes you’ll get back a variable that’s a string and you’ll want to do a math operation comparison on it. Youcan do this like so:
tasks:- shell: echo "only on Red Hat 6, derivatives, and later"when: ansible_os_family == "RedHat" and ansible_lsb.major_release|int >= 6
Note: the above example requires the lsb_release package on the target host in order to return the ansi-ble_lsb.major_release fact.
Variables defined in the playbooks or inventory can also be used. An example may be the execution of a task based ona variable’s boolean value:
vars:epic: true
Then a conditional execution might look like:
tasks:- shell: echo "This certainly is epic!"
when: epic
or:
tasks:- shell: echo "This certainly isn't epic!"
when: not epic
If a required variable has not been set, you can skip or fail using Jinja2’s defined test. For example:
tasks:- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out. this play requires 'bar'"when: bar is undefined
1.3. Playbooks 95
Ansible 1.2 Documentation, Release 0.01
This is especially useful in combination with the conditional import of vars files (see below).
Note that when combining when with with_items (see Loops), be aware that the when statement is processed separatelyfor each item. This is by design:
tasks:- command: echo {{ item }}
with_items: [ 0, 2, 4, 6, 8, 10 ]when: item > 5
Loading in Custom Facts
It’s also easy to provide your own facts if you want, which is covered in Developing Modules. To run them, just makea call to your own custom fact gathering module at the top of your list of tasks, and variables returned there will beaccessible to future tasks:
tasks:- name: gather site specific fact data
action: site_facts- command: /usr/bin/thingy
when: my_custom_fact_just_retrieved_from_the_remote_system == '1234'
Applying ‘when’ to roles and includes
Note that if you have several tasks that all share the same conditional statement, you can affix the conditional to a taskinclude statement as below. All the tasks get evaluated, but the conditional is applied to each and every task:
- include: tasks/sometasks.ymlwhen: "'reticulating splines' in output"
Note: In versions prior to 2.0 this worked with task includes but not playbook includes. 2.0 allows it to work withboth.
Or with a role:
- hosts: webserversroles:
- { role: debian_stock_config, when: ansible_os_family == 'Debian' }
You will note a lot of ‘skipped’ output by default in Ansible when using this approach on systems that don’t match thecriteria. Read up on the ‘group_by’ module in the About Modules docs for a more streamlined way to accomplish thesame thing.
Conditional Imports
Note: This is an advanced topic that is infrequently used. You can probably skip this section.
Sometimes you will want to do certain things differently in a playbook based on certain criteria. Having one playbookthat works on multiple platforms and OS versions is a good example.
96 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
As an example, the name of the Apache package may be different between CentOS and Debian, but it is easily handledwith a minimum of syntax in an Ansible Playbook:
---- hosts: all
remote_user: rootvars_files:- "vars/common.yml"- [ "vars/{{ ansible_os_family }}.yml", "vars/os_defaults.yml" ]
tasks:- name: make sure apache is runningservice: name={{ apache }} state=running
Note: The variable ‘ansible_os_family’ is being interpolated into the list of filenames being defined for vars_files.
As a reminder, the various YAML files contain just keys and values:
---# for vars/CentOS.ymlapache: httpdsomethingelse: 42
How does this work? If the operating system was ‘CentOS’, the first file Ansible would try to import would be‘vars/CentOS.yml’, followed by ‘/vars/os_defaults.yml’ if that file did not exist. If no files in the list were found, anerror would be raised. On Debian, it would instead first look towards ‘vars/Debian.yml’ instead of ‘vars/CentOS.yml’,before falling back on ‘vars/os_defaults.yml’. Pretty simple.
To use this conditional import feature, you’ll need facter or ohai installed prior to running the playbook, but you canof course push this out with Ansible if you like:
# for facteransible -m yum -a "pkg=facter state=present"ansible -m yum -a "pkg=ruby-json state=present"
# for ohaiansible -m yum -a "pkg=ohai state=present"
Ansible’s approach to configuration – separating variables from tasks, keeps your playbooks from turning into arbitrarycode with ugly nested ifs, conditionals, and so on - and results in more streamlined & auditable configuration rules –especially because there are a minimum of decision points to track.
Selecting Files And Templates Based On Variables
Note: This is an advanced topic that is infrequently used. You can probably skip this section.
Sometimes a configuration file you want to copy, or a template you will use may depend on a variable. The followingconstruct selects the first available file appropriate for the variables of a given host, which is often much cleaner thanputting a lot of if conditionals in a template.
The following example shows how to template out a configuration file that was very different between, say, CentOSand Debian:
1.3. Playbooks 97
Ansible 1.2 Documentation, Release 0.01
- name: template a filetemplate: src={{ item }} dest=/etc/myapp/foo.confwith_first_found:- files:
- {{ ansible_distribution }}.conf- default.conf
paths:- search_location_one/somedir/- /opt/other_location/somedir/
Register Variables
Often in a playbook it may be useful to store the result of a given command in a variable and access it later. Use of thecommand module in this way can in many ways eliminate the need to write site specific facts, for instance, you couldtest for the existence of a particular program.
The ‘register’ keyword decides what variable to save a result in. The resulting variables can be used in templates,action lines, or when statements. It looks like this (in an obviously trivial example):
- name: test playhosts: all
tasks:
- shell: cat /etc/motdregister: motd_contents
- shell: echo "motd contains the word hi"when: motd_contents.stdout.find('hi') != -1
As shown previously, the registered variable’s string contents are accessible with the ‘stdout’ value. The registeredresult can be used in the “with_items” of a task if it is converted into a list (or already is a list) as shown below.“stdout_lines” is already available on the object as well though you could also call “home_dirs.stdout.split()” if youwanted, and could split by other fields:
- name: registered variable usage as a with_items listhosts: all
tasks:
- name: retrieve the list of home directoriescommand: ls /homeregister: home_dirs
- name: add home dirs to the backup spoolerfile: path=/mnt/bkspool/{{ item }} src=/home/{{ item }} state=linkwith_items: home_dirs.stdout_lines# same as with_items: home_dirs.stdout.split()
See also:
Playbooks An introduction to playbooks
Playbook Roles and Include Statements Playbook organization by roles
Best Practices Best practices in playbooks
Conditionals Conditional statements in playbooks
98 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Variables All about variables
User Mailing List Have a question? Stop by the google group!
irc.freenode.net #ansible IRC chat channel
Loops
Often you’ll want to do many things in one task, such as create a lot of users, install a lot of packages, or repeat apolling step until a certain result is reached.
This chapter is all about how to use loops in playbooks.
Topics
• Loops
– Standard Loops
– Nested Loops
– Looping over Hashes
– Looping over Files
– Looping over Fileglobs
– Looping over Parallel Sets of Data
– Looping over Subelements
– Looping over Integer Sequences
– Random Choices
– Do-Until Loops
– Finding First Matched Files
– Iterating Over The Results of a Program Execution
– Looping Over A List With An Index
– Using ini file with a loop
– Flattening A List
– Using register with a loop
– Writing Your Own Iterators
Standard Loops
To save some typing, repeated tasks can be written in short-hand like so:
- name: add several usersuser: name={{ item }} state=present groups=wheelwith_items:
- testuser1- testuser2
1.3. Playbooks 99
Ansible 1.2 Documentation, Release 0.01
If you have defined a YAML list in a variables file, or the ‘vars’ section, you can also do:
with_items: "{{somelist}}"
The above would be the equivalent of:
- name: add user testuser1user: name=testuser1 state=present groups=wheel
- name: add user testuser2user: name=testuser2 state=present groups=wheel
The yum and apt modules use with_items to execute fewer package manager transactions.
Note that the types of items you iterate over with ‘with_items’ do not have to be simple lists of strings. If you have alist of hashes, you can reference subkeys using things like:
- name: add several usersuser: name={{ item.name }} state=present groups={{ item.groups }}with_items:- { name: 'testuser1', groups: 'wheel' }- { name: 'testuser2', groups: 'root' }
Also be aware that when combining when with with_items (or any other loop statement), the when statement is pro-cessed separately for each item. See The When Statement for an example.
Nested Loops
Loops can be nested as well:
- name: give users access to multiple databasesmysql_user: name={{ item[0] }} priv={{ item[1] }}.*:ALL append_privs=yes
→˓password=foowith_nested:- [ 'alice', 'bob' ]- [ 'clientdb', 'employeedb', 'providerdb' ]
As with the case of ‘with_items’ above, you can use previously defined variables.:
- name: here, 'users' contains the above list of employeesmysql_user: name={{ item[0] }} priv={{ item[1] }}.*:ALL append_privs=yes
→˓password=foowith_nested:- "{{users}}"- [ 'clientdb', 'employeedb', 'providerdb' ]
Looping over Hashes
New in version 1.5.
Suppose you have the following variable:
---users:
alice:name: Alice Appleworthtelephone: 123-456-7890
100 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
bob:name: Bob Bananaramatelephone: 987-654-3210
And you want to print every user’s name and phone number. You can loop through the elements of a hash usingwith_dict like this:
tasks:- name: Print phone recordsdebug: msg="User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone
→˓}})"with_dict: "{{users}}"
Looping over Files
with_file iterates over the content of a list of files, item will be set to the content of each file in sequence. It canbe used like this:
---- hosts: all
tasks:
# emit a debug message containing the content of each file.- debug:
msg: "{{item}}"with_file:
- first_example_file- second_example_file
Assuming that first_example_file contained the text “hello” and second_example_file contained thetext “world”, this would result in:
TASK [debug msg={{item}}] ******************************************************ok: [localhost] => (item=hello) => {
"item": "hello","msg": "hello"
}ok: [localhost] => (item=world) => {
"item": "world","msg": "world"
}
Looping over Fileglobs
with_fileglob matches all files in a single directory, non-recursively, that match a pattern. It can be used likethis:
---- hosts: all
tasks:
# first ensure our target directory exists
1.3. Playbooks 101
Ansible 1.2 Documentation, Release 0.01
- file: dest=/etc/fooapp state=directory
# copy each file over that matches the given pattern- copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
with_fileglob:- /playbooks/files/fooapp/*
Note: When using a relative path with with_fileglob in a role, Ansible resolves the path relative to theroles/<rolename>/files directory.
Looping over Parallel Sets of Data
Note: This is an uncommon thing to want to do, but we’re documenting it for completeness. You probably won’t bereaching for this one often.
Suppose you have the following variable data was loaded in via somewhere:
---alpha: [ 'a', 'b', 'c', 'd' ]numbers: [ 1, 2, 3, 4 ]
And you want the set of ‘(a, 1)’ and ‘(b, 2)’ and so on. Use ‘with_together’ to get this:
tasks:- debug: msg="{{ item.0 }} and {{ item.1 }}"
with_together:- "{{alpha}}"- "{{numbers}}"
Looping over Subelements
Suppose you want to do something like loop over a list of users, creating them, and allowing them to login by a certainset of SSH keys.
How might that be accomplished? Let’s assume you had the following defined and loaded in via “vars_files” or maybea “group_vars/all” file:
---users:
- name: aliceauthorized:
- /tmp/alice/onekey.pub- /tmp/alice/twokey.pub
mysql:password: mysql-passwordhosts:- "%"- "127.0.0.1"- "::1"- "localhost"
privs:
102 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- "*.*:SELECT"- "DB1.*:ALL"
- name: bobauthorized:
- /tmp/bob/id_rsa.pubmysql:
password: other-mysql-passwordhosts:- "db1"
privs:- "*.*:SELECT"- "DB2.*:ALL"
It might happen like so:
- user: name={{ item.name }} state=present generate_ssh_key=yeswith_items: "{{users}}"
- authorized_key: "user={{ item.0.name }} key='{{ lookup('file', item.1) }}'"with_subelements:
- users- authorized
Given the mysql hosts and privs subkey lists, you can also iterate over a list in a nested subkey:
- name: Setup MySQL usersmysql_user: name={{ item.0.name }} password={{ item.0.mysql.password }} host={{
→˓item.1 }} priv={{ item.0.mysql.privs | join('/') }}with_subelements:- users- mysql.hosts
Subelements walks a list of hashes (aka dictionaries) and then traverses a list with a given (nested sub-)key inside ofthose records.
Optionally, you can add a third element to the subelements list, that holds a dictionary of flags. Currently you can addthe ‘skip_missing’ flag. If set to True, the lookup plugin will skip the lists items that do not contain the given subkey.Without this flag, or if that flag is set to False, the plugin will yield an error and complain about the missing subkey.
The authorized_key pattern is exactly where it comes up most.
Looping over Integer Sequences
with_sequence generates a sequence of items in ascending numerical order. You can specify a start, end, and anoptional step value.
Arguments should be specified in key=value pairs. If supplied, the ‘format’ is a printf style string.
Numerical values can be specified in decimal, hexadecimal (0x3f8) or octal (0600). Negative numbers are not sup-ported. This works as follows:
---- hosts: all
tasks:
# create groups- group: name=evens state=present
1.3. Playbooks 103
Ansible 1.2 Documentation, Release 0.01
- group: name=odds state=present
# create some test users- user: name={{ item }} state=present groups=evens
with_sequence: start=0 end=32 format=testuser%02x
# create a series of directories with even numbers for some reason- file: dest=/var/stuff/{{ item }} state=directory
with_sequence: start=4 end=16 stride=2
# a simpler way to use the sequence plugin# create 4 groups- group: name=group{{ item }} state=present
with_sequence: count=4
Random Choices
The ‘random_choice’ feature can be used to pick something at random. While it’s not a load balancer (there aremodules for those), it can somewhat be used as a poor man’s loadbalancer in a MacGyver like situation:
- debug: msg={{ item }}with_random_choice:
- "go through the door"- "drink from the goblet"- "press the red button"- "do nothing"
One of the provided strings will be selected at random.
At a more basic level, they can be used to add chaos and excitement to otherwise predictable automation environments.
Do-Until Loops
Sometimes you would want to retry a task until a certain condition is met. Here’s an example:
- action: shell /usr/bin/fooregister: resultuntil: result.stdout.find("all systems go") != -1retries: 5delay: 10
The above example run the shell module recursively till the module’s result has “all systems go” in its stdout or thetask has been retried for 5 times with a delay of 10 seconds. The default value for “retries” is 3 and “delay” is 5.
The task returns the results returned by the last task run. The results of individual retries can be viewed by -vv option.The registered variable will also have a new key “attempts” which will have the number of the retries for the task.
Finding First Matched Files
Note: This is an uncommon thing to want to do, but we’re documenting it for completeness. You probably won’t bereaching for this one often.
104 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This isn’t exactly a loop, but it’s close. What if you want to use a reference to a file based on the first file found thatmatches a given criteria, and some of the filenames are determined by variable names? Yes, you can do that as follows:
- name: INTERFACES | Create Ansible header for /etc/network/interfacestemplate: src={{ item }} dest=/etc/foo.confwith_first_found:- "{{ansible_virtualization_type}}_foo.conf"- "default_foo.conf"
This tool also has a long form version that allows for configurable search paths. Here’s an example:
- name: some configuration templatetemplate: src={{ item }} dest=/etc/file.cfg mode=0444 owner=root group=rootwith_first_found:- files:
- "{{inventory_hostname}}/etc/file.cfg"paths:- ../../../templates.overwrites- ../../../templates
- files:- etc/file.cfg
paths:- templates
Iterating Over The Results of a Program Execution
Note: This is an uncommon thing to want to do, but we’re documenting it for completeness. You probably won’t bereaching for this one often.
Sometimes you might want to execute a program, and based on the output of that program, loop over the results ofthat line by line. Ansible provides a neat way to do that, though you should remember, this is always executed on thecontrol machine, not the local machine:
- name: Example of looping over a command resultshell: /usr/bin/frobnicate {{ item }}with_lines: /usr/bin/frobnications_per_host --param {{ inventory_hostname }}
Ok, that was a bit arbitrary. In fact, if you’re doing something that is inventory related you might just want to writea dynamic inventory source instead (see Dynamic Inventory), but this can be occasionally useful in quick-and-dirtyimplementations.
Should you ever need to execute a command remotely, you would not use the above method. Instead do this:
- name: Example of looping over a REMOTE command resultshell: /usr/bin/somethingregister: command_result
- name: Do something with each resultshell: /usr/bin/something_else --param {{ item }}with_items: "{{command_result.stdout_lines}}"
Looping Over A List With An Index
1.3. Playbooks 105
Ansible 1.2 Documentation, Release 0.01
Note: This is an uncommon thing to want to do, but we’re documenting it for completeness. You probably won’t bereaching for this one often.
If you want to loop over an array and also get the numeric index of where you are in the array as you go, you can alsodo that. It’s uncommonly used:
- name: indexed loop demodebug: msg="at array position {{ item.0 }} there is a value {{ item.1 }}"with_indexed_items: "{{some_list}}"
Using ini file with a loop
The ini plugin can use regexp to retrieve a set of keys. As a consequence, we can loop over this set. Here is the ini filewe’ll use:
[section1]value1=section1/value1value2=section1/value2
[section2]value1=section2/value1value2=section2/value2
Here is an example of using with_ini:
- debug: msg="{{item}}"with_ini: value[1-2] section=section1 file=lookup.ini re=true
And here is the returned value:
{"changed": false,"msg": "All items completed","results": [
{"invocation": {
"module_args": "msg=\"section1/value1\"","module_name": "debug"
},"item": "section1/value1","msg": "section1/value1","verbose_always": true
},{
"invocation": {"module_args": "msg=\"section1/value2\"","module_name": "debug"
},"item": "section1/value2","msg": "section1/value2","verbose_always": true
}]
}
106 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Flattening A List
Note: This is an uncommon thing to want to do, but we’re documenting it for completeness. You probably won’t bereaching for this one often.
In rare instances you might have several lists of lists, and you just want to iterate over every item in all of those lists.Assume a really crazy hypothetical datastructure:
----# file: roles/foo/vars/main.ymlpackages_base:
- [ 'foo-package', 'bar-package' ]packages_apps:
- [ ['one-package', 'two-package' ]]- [ ['red-package'], ['blue-package']]
As you can see the formatting of packages in these lists is all over the place. How can we install all of the packages inboth lists?:
- name: flattened loop demoyum: name={{ item }} state=installedwith_flattened:
- "{{packages_base}}"- "{{packages_apps}}"
That’s how!
Using register with a loop
When using register with a loop the data structure placed in the variable during a loop, will contain a resultsattribute, that is a list of all responses from the module.
Here is an example of using register with with_items:
- shell: echo "{{ item }}"with_items:- one- two
register: echo
This differs from the data structure returned when using register without a loop:
{"changed": true,"msg": "All items completed","results": [
{"changed": true,"cmd": "echo \"one\" ","delta": "0:00:00.003110","end": "2013-12-19 12:00:05.187153","invocation": {
"module_args": "echo \"one\"","module_name": "shell"
},
1.3. Playbooks 107
Ansible 1.2 Documentation, Release 0.01
"item": "one","rc": 0,"start": "2013-12-19 12:00:05.184043","stderr": "","stdout": "one"
},{
"changed": true,"cmd": "echo \"two\" ","delta": "0:00:00.002920","end": "2013-12-19 12:00:05.245502","invocation": {
"module_args": "echo \"two\"","module_name": "shell"
},"item": "two","rc": 0,"start": "2013-12-19 12:00:05.242582","stderr": "","stdout": "two"
}]
}
Subsequent loops over the registered variable to inspect the results may look like:
- name: Fail if return code is not 0fail:msg: "The command ({{ item.cmd }}) did not have a 0 return code"
when: item.rc != 0with_items: "{{echo.results}}"
Loops and Includes
In 2.0 you are able to use with_ loops and task includes (but not playbook includes), this adds the ability to loop overthe set of tasks in one shot. There are a couple of things that you need to keep in mind, a included task that has it’sown with_ loop will overwrite the value of the special item variable. So if you want access to both the include’s itemand the current task’s item you should use set_fact to create a alias to the outer one.:
- include: test.ymlwith_items:- 1- 2- 3
in test.yml:
- set_fact: outer_loop="{{item}}"
- debug: msg="outer item={{outer_loop}} inner item={{item}}"with_items:- a- b- c
108 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Writing Your Own Iterators
While you ordinarily shouldn’t have to, should you wish to write your own ways to loop over arbitrary datastructures,you can read Developing Plugins for some starter information. Each of the above features are implemented as pluginsin ansible, so there are many implementations to reference.
See also:
Playbooks An introduction to playbooks
Playbook Roles and Include Statements Playbook organization by roles
Best Practices Best practices in playbooks
Conditionals Conditional statements in playbooks
Variables All about variables
User Mailing List Have a question? Stop by the google group!
irc.freenode.net #ansible IRC chat channel
Blocks
In 2.0 we added a block feature to allow for logical grouping of tasks and even in play error handling. Most of whatyou can apply to a single task can be applied at the block level, which also makes it much easier to set data or directivescommon to the tasks.
Listing 1.1: Block example
tasks:- block:
- yum: name={{ item }} state=installedwith_items:- httpd- memcached
- template: src=templates/src.j2 dest=/etc/foo.conf
- service: name=bar state=started enabled=True
when: ansible_distribution == 'CentOS'become: truebecome_user: root
In the example above the 3 tasks will be executed only when the block’s when condition is met and enables privilegeescalation for all the enclosed tasks.
Error Handling
Blocks also introduce the ability to handle errors in a way similar to exceptions in most programming languages.
Listing 1.2: Block error handling example
tasks:- block:
- debug: msg='i execute normally'- command: /bin/false- debug: msg='i never execute, cause ERROR!'
1.3. Playbooks 109
Ansible 1.2 Documentation, Release 0.01
rescue:- debug: msg='I caught an error'- command: /bin/false- debug: msg='I also never execute :-('
always:- debug: msg="this always executes"
The tasks in the block would execute normally, if there is any error the rescue section would get executed withwhatever you need to do to recover from the previous error. The always section runs no matter what previous errordid or did not occur in the block and rescue sections.
See also:
Playbooks An introduction to playbooks
Playbook Roles and Include Statements Playbook organization by roles
User Mailing List Have a question? Stop by the google group!
irc.freenode.net #ansible IRC chat channel
Strategies
In 2.0 we added a new way to control play execution, strategy, by default plays will still run as they used to, withwhat we call the linear strategy. All hosts will run each task before any host starts the next task, using the numberof forks (default 5) to parallelize.
The serial directive can ‘batch’ this behaviour to a subset of the hosts, which then run to completion of the playbefore the next ‘batch’ starts.
A second strategy ships with ansible free, which allows each host to run until the end of the play as fast as itcan.:
- hosts: allstrategy: freetasks:...
Strategy Plugins
The strategies are implemented via a new type of plugin, this means that in the future new execution types can beadded, either locally by users or to Ansible itself by a code contribution.
See also:
Playbooks An introduction to playbooks
Playbook Roles and Include Statements Playbook organization by roles
User Mailing List Have a question? Stop by the google group!
irc.freenode.net #ansible IRC chat channel
Best Practices
Here are some tips for making the most of Ansible and Ansible playbooks.
110 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
You can find some example playbooks illustrating these best practices in our ansible-examples repository. (NOTE:These may not use all of the features in the latest release, but are still an excellent reference!).
Topics
• Best Practices
– Content Organization
* Directory Layout
* Use Dynamic Inventory With Clouds
* How to Differentiate Staging vs Production
* Group And Host Variables
* Top Level Playbooks Are Separated By Role
* Task And Handler Organization For A Role
* What This Organization Enables (Examples)
* Deployment vs Configuration Organization
– Staging vs Production
– Rolling Updates
– Always Mention The State
– Group By Roles
– Operating System and Distribution Variance
– Bundling Ansible Modules With Playbooks
– Whitespace and Comments
– Always Name Tasks
– Keep It Simple
– Version Control
– Variables and Vaults
Content Organization
The following section shows one of many possible ways to organize playbook content.
Your usage of Ansible should fit your needs, however, not ours, so feel free to modify this approach and organize asyou see fit.
One thing you will definitely want to do though, is use the “roles” organization feature, which is documented as partof the main playbooks page. See Playbook Roles and Include Statements. You absolutely should be using roles. Rolesare great. Use roles. Roles! Did we say that enough? Roles are great.
Directory Layout
The top level of the directory would contain files and directories like so:
1.3. Playbooks 111
Ansible 1.2 Documentation, Release 0.01
production # inventory file for production serversstaging # inventory file for staging environment
group_vars/group1 # here we assign variables to particular groupsgroup2 # ""
host_vars/hostname1 # if systems need specific variables, put them herehostname2 # ""
library/ # if any custom modules, put them here (optional)filter_plugins/ # if any custom filter plugins, put them here (optional)
site.yml # master playbookwebservers.yml # playbook for webserver tierdbservers.yml # playbook for dbserver tier
roles/common/ # this hierarchy represents a "role"
tasks/ #main.yml # <-- tasks file can include smaller files if warranted
handlers/ #main.yml # <-- handlers file
templates/ # <-- files for use with the template resourcentp.conf.j2 # <------- templates end in .j2
files/ #bar.txt # <-- files for use with the copy resourcefoo.sh # <-- script files for use with the script resource
vars/ #main.yml # <-- variables associated with this role
defaults/ #main.yml # <-- default lower priority variables for this role
meta/ #main.yml # <-- role dependencies
webtier/ # same kind of structure as "common" was above, done for→˓the webtier role
monitoring/ # ""fooapp/ # ""
Use Dynamic Inventory With Clouds
If you are using a cloud provider, you should not be managing your inventory in a static file. See Dynamic Inventory.
This does not just apply to clouds – If you have another system maintaining a canonical list of systems in yourinfrastructure, usage of dynamic inventory is a great idea in general.
How to Differentiate Staging vs Production
If managing static inventory, it is frequently asked how to differentiate different types of environments. The followingexample shows a good way to do this. Similar methods of grouping could be adapted to dynamic inventory (forinstance, consider applying the AWS tag “environment:production”, and you’ll get a group of systems automaticallydiscovered named “ec2_tag_environment_production”.
112 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Let’s show a static inventory example though. Below, the production file contains the inventory of all of your produc-tion hosts.
It is suggested that you define groups based on purpose of the host (roles) and also geography or datacenter location(if applicable):
# file: production
[atlanta-webservers]www-atl-1.example.comwww-atl-2.example.com
[boston-webservers]www-bos-1.example.comwww-bos-2.example.com
[atlanta-dbservers]db-atl-1.example.comdb-atl-2.example.com
[boston-dbservers]db-bos-1.example.com
# webservers in all geos[webservers:children]atlanta-webserversboston-webservers
# dbservers in all geos[dbservers:children]atlanta-dbserversboston-dbservers
# everything in the atlanta geo[atlanta:children]atlanta-webserversatlanta-dbservers
# everything in the boston geo[boston:children]boston-webserversboston-dbservers
Group And Host Variables
This section extends on the previous example.
Groups are nice for organization, but that’s not all groups are good for. You can also assign variables to them! Forinstance, atlanta has its own NTP servers, so when setting up ntp.conf, we should use them. Let’s set those now:
---# file: group_vars/atlantantp: ntp-atlanta.example.combackup: backup-atlanta.example.com
Variables aren’t just for geographic information either! Maybe the webservers have some configuration that doesn’tmake sense for the database servers:
1.3. Playbooks 113
Ansible 1.2 Documentation, Release 0.01
---# file: group_vars/webserversapacheMaxRequestsPerChild: 3000apacheMaxClients: 900
If we had any default values, or values that were universally true, we would put them in a file called group_vars/all:
---# file: group_vars/allntp: ntp-boston.example.combackup: backup-boston.example.com
We can define specific hardware variance in systems in a host_vars file, but avoid doing this unless you need to:
---# file: host_vars/db-bos-1.example.comfoo_agent_port: 86bar_agent_port: 99
Again, if we are using dynamic inventory sources, many dynamic groups are automatically created. So a tag like“class:webserver” would load in variables from the file “group_vars/ec2_tag_class_webserver” automatically.
Top Level Playbooks Are Separated By Role
In site.yml, we include a playbook that defines our entire infrastructure. Note this is SUPER short, because it’s justincluding some other playbooks. Remember, playbooks are nothing more than lists of plays:
---# file: site.yml- include: webservers.yml- include: dbservers.yml
In a file like webservers.yml (also at the top level), we simply map the configuration of the webservers group to theroles performed by the webservers group. Also notice this is incredibly short. For example:
---# file: webservers.yml- hosts: webservers
roles:- common- webtier
The idea here is that we can choose to configure our whole infrastructure by “running” site.yml or we could just chooseto run a subset by running webservers.yml. This is analogous to the “–limit” parameter to ansible but a little moreexplicit:
ansible-playbook site.yml --limit webserversansible-playbook webservers.yml
Task And Handler Organization For A Role
Below is an example tasks file that explains how a role works. Our common role here just sets up NTP, but it could domore if we wanted:
114 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
---# file: roles/common/tasks/main.yml
- name: be sure ntp is installedyum: name=ntp state=installedtags: ntp
- name: be sure ntp is configuredtemplate: src=ntp.conf.j2 dest=/etc/ntp.confnotify:- restart ntpd
tags: ntp
- name: be sure ntpd is running and enabledservice: name=ntpd state=running enabled=yestags: ntp
Here is an example handlers file. As a review, handlers are only fired when certain tasks report changes, and are run atthe end of each play:
---# file: roles/common/handlers/main.yml- name: restart ntpd
service: name=ntpd state=restarted
See Playbook Roles and Include Statements for more information.
What This Organization Enables (Examples)
Above we’ve shared our basic organizational structure.
Now what sort of use cases does this layout enable? Lots! If I want to reconfigure my whole infrastructure, it’s just:
ansible-playbook -i production site.yml
What about just reconfiguring NTP on everything? Easy.:
ansible-playbook -i production site.yml --tags ntp
What about just reconfiguring my webservers?:
ansible-playbook -i production webservers.yml
What about just my webservers in Boston?:
ansible-playbook -i production webservers.yml --limit boston
What about just the first 10, and then the next 10?:
ansible-playbook -i production webservers.yml --limit boston[0-10]ansible-playbook -i production webservers.yml --limit boston[10-20]
And of course just basic ad-hoc stuff is also possible.:
ansible boston -i production -m pingansible boston -i production -m command -a '/sbin/reboot'
1.3. Playbooks 115
Ansible 1.2 Documentation, Release 0.01
And there are some useful commands to know (at least in 1.1 and higher):
# confirm what task names would be run if I ran this command and said "just ntp tasks"ansible-playbook -i production webservers.yml --tags ntp --list-tasks
# confirm what hostnames might be communicated with if I said "limit to boston"ansible-playbook -i production webservers.yml --limit boston --list-hosts
Deployment vs Configuration Organization
The above setup models a typical configuration topology. When doing multi-tier deployments, there are going to besome additional playbooks that hop between tiers to roll out an application. In this case, ‘site.yml’ may be augmentedby playbooks like ‘deploy_exampledotcom.yml’ but the general concepts can still apply.
Consider “playbooks” as a sports metaphor – you don’t have to just have one set of plays to use against your infras-tructure all the time – you can have situational plays that you use at different times and for different purposes.
Ansible allows you to deploy and configure using the same tool, so you would likely reuse groups and just keep theOS configuration in separate playbooks from the app deployment.
Staging vs Production
As also mentioned above, a good way to keep your staging (or testing) and production environments separate is to usea separate inventory file for staging and production. This way you pick with -i what you are targeting. Keeping themall in one file can lead to surprises!
Testing things in a staging environment before trying in production is always a great idea. Your environments neednot be the same size and you can use group variables to control the differences between those environments.
Rolling Updates
Understand the ‘serial’ keyword. If updating a webserver farm you really want to use it to control how many machinesyou are updating at once in the batch.
See Delegation, Rolling Updates, and Local Actions.
Always Mention The State
The ‘state’ parameter is optional to a lot of modules. Whether ‘state=present’ or ‘state=absent’, it’s always best toleave that parameter in your playbooks to make it clear, especially as some modules support additional states.
Group By Roles
We’re somewhat repeating ourselves with this tip, but it’s worth repeating. A system can be in multiple groups. SeeInventory and Patterns. Having groups named after things like webservers and dbservers is repeated in the examplesbecause it’s a very powerful concept.
This allows playbooks to target machines based on role, as well as to assign role specific variables using the groupvariable system.
See Playbook Roles and Include Statements.
116 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Operating System and Distribution Variance
When dealing with a parameter that is different between two different operating systems, a great way to handle this isby using the group_by module.
This makes a dynamic group of hosts matching certain criteria, even if that group is not defined in the inventory file:
---
# talk to all hosts just so we can learn about them- hosts: all
tasks:- group_by: key=os_{{ ansible_distribution }}
# now just on the CentOS hosts...
- hosts: os_CentOSgather_facts: Falsetasks:
- # tasks that only happen on CentOS go here
This will throw all systems into a dynamic group based on the operating system name.
If group-specific settings are needed, this can also be done. For example:
---# file: group_vars/allasdf: 10
---# file: group_vars/os_CentOSasdf: 42
In the above example, CentOS machines get the value of ‘42’ for asdf, but other machines get ‘10’. This can be usednot only to set variables, but also to apply certain roles to only certain systems.
Alternatively, if only variables are needed:
- hosts: alltasks:- include_vars: "os_{{ ansible_distribution }}.yml"- debug: var=asdf
This will pull in variables based on the OS name.
Bundling Ansible Modules With Playbooks
If a playbook has a ”./library” directory relative to its YAML file, this directory can be used to add ansible modulesthat will automatically be in the ansible module path. This is a great way to keep modules that go with a playbooktogether. This is shown in the directory structure example at the start of this section.
Whitespace and Comments
Generous use of whitespace to break things up, and use of comments (which start with ‘#’), is encouraged.
1.3. Playbooks 117
Ansible 1.2 Documentation, Release 0.01
Always Name Tasks
It is possible to leave off the ‘name’ for a given task, though it is recommended to provide a description about whysomething is being done instead. This name is shown when the playbook is run.
Keep It Simple
When you can do something simply, do something simply. Do not reach to use every feature of Ansible together, allat once. Use what works for you. For example, you will probably not need vars, vars_files, vars_promptand --extra-vars all at once, while also using an external inventory file.
If something feels complicated, it probably is, and may be a good opportunity to simplify things.
Version Control
Use version control. Keep your playbooks and inventory file in git (or another version control system), and commitwhen you make changes to them. This way you have an audit trail describing when and why you changed the rulesthat are automating your infrastructure.
Variables and Vaults
For general maintenance, it is often easier to use grep, or similar tools, to find variables in your Ansible setup. Sincevaults obscure these variables, it is best to work with a layer of indirection. When running a playbook, Ansible findsthe variables in the unencrypted file and all sensitive variables come from the encrypted file.
A best practice approach for this is to start with a group_vars/ subdirectory named after the group. Inside of thissubdirectory, create two files named vars and vault. Inside of the vars file, define all of the variables needed,including any sensitive ones. Next, copy all of the sensitive variables over to the vault file and prefix these variableswith vault_. You should adjust the variables in the vars file to point to the matching vault_ variables and ensurethat the vault file is vault encrypted.
This best practice has no limit on the amount of variable and vault files or their names.
See also:
YAML Syntax Learn about YAML syntax
Playbooks Review the basic playbook features
About Modules Learn about available modules
Developing Modules Learn how to extend Ansible by writing your own modules
Patterns Learn about how to select hosts
GitHub examples directory Complete playbook files from the github project source
Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
Playbooks: Special Topics
Here are some playbook features that not everyone may need to learn, but can be quite useful for particular applications.Browsing these topics is recommended as you may find some useful tips here, but feel free to learn the basics of Ansiblefirst and adopt these only if they seem relevant or useful to your environment.
118 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Become (Privilege Escalation)
Ansible can use existing privilege escalation systems to allow a user to execute tasks as another.
Topics
• Become (Privilege Escalation)
– Become
* New directives
* New ansible_ variables
* New command line options
* sudo and su still work!
* Limitations
· Becoming an Unprivileged User
· Connection Plugin Support
· Only one method may be enabled per host
· Can’t limit escalation to certain commands
Become
Before 1.9 Ansible mostly allowed the use of sudo and a limited use of su to allow a login/remote user to become adifferent user and execute tasks, create resources with the 2nd user’s permissions. As of 1.9 become supersedes the oldsudo/su, while still being backwards compatible. This new system also makes it easier to add other privilege escalationtools like pbrun (Powerbroker), pfexec and others.
New directives
become equivalent to adding sudo: or su: to a play or task, set to ‘true’/’yes’ to activate privilege escalation
become_user equivalent to adding ‘sudo_user:’ or ‘su_user:’ to a play or task, set to user with desired privileges
become_method at play or task level overrides the default method set in ansible.cfg, set to‘sudo’/’su’/’pbrun’/’pfexec’/’doas’
New ansible_ variables
Each allows you to set an option per group and/or host
ansible_become equivalent to ansible_sudo or ansible_su, allows to force privilege escalation
ansible_become_method allows to set privilege escalation method
ansible_become_user equivalent to ansible_sudo_user or ansible_su_user, allows to set the user you become throughprivilege escalation
ansible_become_pass equivalent to ansible_sudo_pass or ansible_su_pass, allows you to set the privilege escalationpassword
1.4. Playbooks: Special Topics 119
Ansible 1.2 Documentation, Release 0.01
New command line options
--ask-become-pass ask for privilege escalation password
–become,-b run operations with become (no password implied)
--become-method=BECOME_METHOD privilege escalation method to use (default=sudo), validchoices: [ sudo | su | pbrun | pfexec | doas ]
--become-user=BECOME_USER run operations as this user (default=root)
sudo and su still work!
Old playbooks will not need to be changed, even though they are deprecated, sudo and su directives will continue towork though it is recommended to move to become as they may be retired at one point. You cannot mix directives onthe same object though, Ansible will complain if you try to.
Become will default to using the old sudo/su configs and variables if they exist, but will override them if you specifyany of the new ones.
Limitations
Although privilege escalation is mostly intuitive, there are a few limitations on how it works. Users should be awareof these to avoid surprises.
Becoming an Unprivileged User
Ansible has a limitation with regards to becoming an unprivileged user that can be a security risk if users are not awareof it. Ansible modules are executed on the remote machine by first substituting the parameters into the module file,then copying the file to the remote machine, and finally executing it there. If the module file is executed without usingbecome, when the become user is root, or when the connection to the remote machine is made as root then the modulefile is created with permissions that only allow reading by the user and root.
If the become user is an unprivileged user and then Ansible has no choice but to make the module file world readableas there’s no other way for the user Ansible connects as to save the file so that the user that we’re becoming can readit.
If any of the parameters passed to the module are sensitive in nature then those pieces of data are readable by readingthe module file for the duration of the Ansible module execution. Once the module is done executing Ansible willdelete the temporary file. If you trust the client machines then there’s no problem here. If you do not trust the clientmachines then this is a potential danger.
Ways to resolve this include:
• Use pipelining. When pipelining is enabled, Ansible doesn’t save the module to a temporary file on the client.Instead it pipes the module to the remote python interpreter’s stdin. Pipelining does not work for non-pythonmodules.
• Don’t perform an action on the remote machine by becoming an unprivileged user. Temporary files are protectedby UNIX file permissions when you become root or do not use become.
120 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Connection Plugin Support
Privilege escalation methods must also be supported by the connection plugin used. Most connection plugins willwarn if they do not support become. Some will just ignore it as they always run as root (jail, chroot, etc).
Only one method may be enabled per host
Methods cannot be chained. You cannot use sudo /bin/su - to become a user, you need to have privileges torun the command as that user in sudo or be able to su directly to it (the same for pbrun, pfexec or other supportedmethods).
Can’t limit escalation to certain commands
Privilege escalation permissions have to be general. Ansible does not always use a specific command to do some-thing but runs modules (code) from a temporary file name which changes every time. If you have ‘/sbin/service’ or‘/bin/chmod’ as the allowed commands this will fail with ansible as those paths won’t match with the temporary filethat ansible creates to run the module.
See also:
Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
irc.freenode.net #ansible IRC chat channel
Accelerated Mode
New in version 1.3.
You Might Not Need This!
Are you running Ansible 1.5 or later? If so, you may not need accelerated mode due to a new feature called “SSHpipelining” and should read the pipelining section of the documentation.
For users on 1.5 and later, accelerated mode only makes sense if you (A) are managing from an Enterprise Linux 6 orearlier host and still are on paramiko, or (B) can’t enable TTYs with sudo as described in the pipelining docs.
If you can use pipelining, Ansible will reduce the amount of files transferred over the wire, making everything muchmore efficient, and performance will be on par with accelerated mode in nearly all cases, possibly excluding very largefile transfer. Because less moving parts are involved, pipelining is better than accelerated mode for nearly all use cases.
Accelerated moded remains around in support of EL6 control machines and other constrained environments.
Accelerated Mode Details
While OpenSSH using the ControlPersist feature is quite fast and scalable, there is a certain small amount of overheadinvolved in using SSH connections. While many people will not encounter a need, if you are running on a platformthat doesn’t have ControlPersist support (such as an EL6 control machine), you’ll probably be even more interested intuning options.
Accelerated mode is there to help connections work faster, but still uses SSH for initial secure key exchange. There isno additional public key infrastructure to manage, and this does not require things like NTP or even DNS.
1.4. Playbooks: Special Topics 121
Ansible 1.2 Documentation, Release 0.01
Accelerated mode can be anywhere from 2-6x faster than SSH with ControlPersist enabled, and 10x faster thanparamiko.
Accelerated mode works by launching a temporary daemon over SSH. Once the daemon is running, Ansible willconnect directly to it via a socket connection. Ansible secures this communication by using a temporary AES key thatis exchanged during the SSH connection (this key is different for every host, and is also regenerated periodically).
By default, Ansible will use port 5099 for the accelerated connection, though this is configurable. Once running, thedaemon will accept connections for 30 minutes, after which time it will terminate itself and need to be restarted overSSH.
Accelerated mode offers several improvements over the (deprecated) original fireball mode from which it was based:
• No bootstrapping is required, only a single line needs to be added to each play you wish to run in acceleratedmode.
• Support for sudo commands (see below for more details and caveats) is available.
• There are fewer requirements. ZeroMQ is no longer required, nor are there any special packages beyond python-keyczar
• python 2.5 or higher is required.
In order to use accelerated mode, simply add accelerate: true to your play:
---
- hosts: allaccelerate: true
tasks:
- name: some taskcommand: echo {{ item }}with_items:- foo- bar- baz
If you wish to change the port Ansible will use for the accelerated connection, just add the accelerated_port option:
---
- hosts: allaccelerate: true# default port is 5099accelerate_port: 10000
The accelerate_port option can also be specified in the environment variable ACCELERATE_PORT, or in your ansi-ble.cfg configuration:
[accelerate]accelerate_port = 5099
As noted above, accelerated mode also supports running tasks via sudo, however there are two important caveats:
• You must remove requiretty from your sudoers options.
• Prompting for the sudo password is not yet supported, so the NOPASSWD option is required for sudo’edcommands.
122 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
As of Ansible version 1.6, you can also allow the use of multiple keys for connections from multiple Ansible manage-ment nodes. To do so, add the following option to your ansible.cfg configuration:
accelerate_multi_key = yes
When enabled, the daemon will open a UNIX socket file (by default $ANSIBLE_REMOTE_TEMP/.ansible-accelerate/.local.socket). New connections over SSH can use this socket file to upload new keys to the daemon.
Asynchronous Actions and Polling
By default tasks in playbooks block, meaning the connections stay open until the task is done on each node. This maynot always be desirable, or you may be running operations that take longer than the SSH timeout.
The easiest way to do this is to kick them off all at once and then poll until they are done.
You will also want to use asynchronous mode on very long running operations that might be subject to timeout.
To launch a task asynchronously, specify its maximum runtime and how frequently you would like to poll for status.The default poll value is 10 seconds if you do not specify a value for poll:
---
- hosts: allremote_user: root
tasks:
- name: simulate long running op (15 sec), wait for up to 45 sec, poll every 5 seccommand: /bin/sleep 15async: 45poll: 5
Note: There is no default for the async time limit. If you leave off the ‘async’ keyword, the task runs synchronously,which is Ansible’s default.
Alternatively, if you do not need to wait on the task to complete, you may “fire and forget” by specifying a poll valueof 0:
---
- hosts: allremote_user: root
tasks:
- name: simulate long running op, allow to run for 45 sec, fire and forgetcommand: /bin/sleep 15async: 45poll: 0
Note: You shouldn’t “fire and forget” with operations that require exclusive locks, such as yum transactions, if youexpect to run other commands later in the playbook against those same resources.
1.4. Playbooks: Special Topics 123
Ansible 1.2 Documentation, Release 0.01
Note: Using a higher value for --forkswill result in kicking off asynchronous tasks even faster. This also increasesthe efficiency of polling.
If you would like to perform a variation of the “fire and forget” where you “fire and forget, check on it later” you canperform a task similar to the following:
---# Requires ansible 1.8+- name: 'YUM - fire and forget task'
yum: name=docker-io state=installedasync: 1000poll: 0register: yum_sleeper
- name: 'YUM - check on fire and forget task'async_status: jid={{ yum_sleeper.ansible_job_id }}register: job_resultuntil: job_result.finishedretries: 30
Note: If the value of async: is not high enough, this will cause the “check on it later” task to fail because thetemporary status file that the async_status: is looking for will not have been written or no longer exist
See also:
Playbooks An introduction to playbooks
User Mailing List Have a question? Stop by the google group!
irc.freenode.net #ansible IRC chat channel
Check Mode (“Dry Run”)
New in version 1.1.
Topics
• Check Mode (“Dry Run”)
– Running a task in check mode
– Showing Differences with --diff
When ansible-playbook is executed with --check it will not make any changes on remote systems. Instead, anymodule instrumented to support ‘check mode’ (which contains most of the primary core modules, but it is not requiredthat all modules do this) will report what changes they would have made rather than making them. Other modules thatdo not support check mode will also take no action, but just will not report what changes they might have made.
Check mode is just a simulation, and if you have steps that use conditionals that depend on the results of priorcommands, it may be less useful for you. However it is great for one-node-at-time basic configuration managementuse cases.
Example:
124 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
ansible-playbook foo.yml --check
Running a task in check mode
New in version 1.3.
Sometimes you may want to have a task to be executed even in check mode. To achieve this, use the always_runclause on the task. Its value is a Jinja2 expression, just like the when clause. In simple cases a boolean YAML valuewould be sufficient as a value.
Example:
tasks:
- name: this task is run even in check modecommand: /something/to/run --even-in-check-modealways_run: yes
As a reminder, a task with a when clause evaluated to false, will still be skipped even if it has a always_run clauseevaluated to true.
Showing Differences with --diff
New in version 1.1.
The --diff option to ansible-playbook works great with --check (detailed above) but can also be used by itself.When this flag is supplied, if any templated files on the remote system are changed, and the ansible-playbook CLI willreport back the textual changes made to the file (or, if used with --check, the changes that would have been made).Since the diff feature produces a large amount of output, it is best used when checking a single host at a time, like so:
ansible-playbook foo.yml --check --diff --limit foo.example.com
Delegation, Rolling Updates, and Local Actions
Topics
• Delegation, Rolling Updates, and Local Actions
– Rolling Update Batch Size
– Maximum Failure Percentage
– Delegation
– Delegated facts
– Run Once
– Local Playbooks
– Interrupt execution on any error
Being designed for multi-tier deployments since the beginning, Ansible is great at doing things on one host on behalfof another, or doing local steps with reference to some remote hosts.
1.4. Playbooks: Special Topics 125
Ansible 1.2 Documentation, Release 0.01
This in particular is very applicable when setting up continuous deployment infrastructure or zero downtime rollingupdates, where you might be talking with load balancers or monitoring systems.
Additional features allow for tuning the orders in which things complete, and assigning a batch window size for howmany machines to process at once during a rolling update.
This section covers all of these features. For examples of these items in use, please see the ansible-examples repository.There are quite a few examples of zero-downtime update procedures for different kinds of applications.
You should also consult the About Modules section, various modules like ‘ec2_elb’, ‘nagios’, and ‘bigip_pool’, and‘netscaler’ dovetail neatly with the concepts mentioned here.
You’ll also want to read up on Playbook Roles and Include Statements, as the ‘pre_task’ and ‘post_task’ concepts arethe places where you would typically call these modules.
Rolling Update Batch Size
New in version 0.7.
By default, Ansible will try to manage all of the machines referenced in a play in parallel. For a rolling updates usecase, you can define how many hosts Ansible should manage at a single time by using the ‘’serial” keyword:
- name: test playhosts: webserversserial: 3
In the above example, if we had 100 hosts, 3 hosts in the group ‘webservers’ would complete the play completelybefore moving on to the next 3 hosts.
The ‘’serial” keyword can also be specified as a percentage in Ansible 1.8 and later, which will be applied to the totalnumber of hosts in a play, in order to determine the number of hosts per pass:
- name: test playhosts: webseversserial: "30%"
If the number of hosts does not divide equally into the number of passes, the final pass will contain the remainder.
Note: No matter how small the percentage, the number of hosts per pass will always be 1 or greater.
Maximum Failure Percentage
New in version 1.3.
By default, Ansible will continue executing actions as long as there are hosts in the group that have not yet failed. Insome situations, such as with the rolling updates described above, it may be desirable to abort the play when a certainthreshold of failures have been reached. To achieve this, as of version 1.3 you can set a maximum failure percentageon a play as follows:
- hosts: webserversmax_fail_percentage: 30serial: 10
In the above example, if more than 3 of the 10 servers in the group were to fail, the rest of the play would be aborted.
126 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: The percentage set must be exceeded, not equaled. For example, if serial were set to 4 and you wanted the taskto abort when 2 of the systems failed, the percentage should be set at 49 rather than 50.
Delegation
New in version 0.7.
This isn’t actually rolling update specific but comes up frequently in those cases.
If you want to perform a task on one host with reference to other hosts, use the ‘delegate_to’ keyword on a task. Thisis ideal for placing nodes in a load balanced pool, or removing them. It is also very useful for controlling outagewindows. Using this with the ‘serial’ keyword to control the number of hosts executing at one time is also a good idea:
---
- hosts: webserversserial: 5
tasks:
- name: take out of load balancer poolcommand: /usr/bin/take_out_of_pool {{ inventory_hostname }}delegate_to: 127.0.0.1
- name: actual steps would go hereyum: name=acme-web-stack state=latest
- name: add back to load balancer poolcommand: /usr/bin/add_back_to_pool {{ inventory_hostname }}delegate_to: 127.0.0.1
These commands will run on 127.0.0.1, which is the machine running Ansible. There is also a shorthand syntax thatyou can use on a per-task basis: ‘local_action’. Here is the same playbook as above, but using the shorthand syntaxfor delegating to 127.0.0.1:
---
# ...
tasks:
- name: take out of load balancer poollocal_action: command /usr/bin/take_out_of_pool {{ inventory_hostname }}
# ...
- name: add back to load balancer poollocal_action: command /usr/bin/add_back_to_pool {{ inventory_hostname }}
A common pattern is to use a local action to call ‘rsync’ to recursively copy files to the managed servers. Here is anexample:
---# ...
tasks:
1.4. Playbooks: Special Topics 127
Ansible 1.2 Documentation, Release 0.01
- name: recursively copy files from management server to targetlocal_action: command rsync -a /path/to/files {{ inventory_hostname }}:/path/to/
→˓target/
Note that you must have passphrase-less SSH keys or an ssh-agent configured for this to work, otherwise rsync willneed to ask for a passphrase.
Delegated facts
New in version 2.0.
By default, any fact gathered by a delegated task are assigned to the inventory_hostname (the current host) instead ofthe host which actually produced the facts (the delegated to host). In 2.0, the directive delegate_facts may be set toTrue to assign the task’s gathered facts to the delegated host instead of the current one.:
- hosts: app_serverstasks:- name: gather facts from db servers
setup:delegate_to: "{{item}}"delegate_facts: Truewith_items: "{{groups['dbservers'}}"
The above will gather facts for the machines in the dbservers group and assign the facts to those machines and not toapp_servers. This way you can lookup hostvars[’dbhost1’][’default_ipv4_addresses’][0] even though dbservers werenot part of the play, or left out by using –limit.
Run Once
New in version 1.7.
In some cases there may be a need to only run a task one time and only on one host. This can be achieved byconfiguring “run_once” on a task:
---# ...
tasks:
# ...
- command: /opt/application/upgrade_db.pyrun_once: true
# ...
This can be optionally paired with “delegate_to” to specify an individual host to execute on:
- command: /opt/application/upgrade_db.pyrun_once: truedelegate_to: web01.example.org
When “run_once” is not used with “delegate_to” it will execute on the first host, as defined by inventory, in the group(s)of hosts targeted by the play - e.g. webservers[0] if the play targeted “hosts: webservers”.
128 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This approach is similar to applying a conditional to a task such as:
- command: /opt/application/upgrade_db.pywhen: inventory_hostname == webservers[0]
Note: When used together with “serial”, tasks marked as “run_once” will be ran on one host in each serialbatch. If it’s crucial that the task is run only once regardless of “serial” mode, use inventory_hostname ==my_group_name[0] construct.
Local Playbooks
It may be useful to use a playbook locally, rather than by connecting over SSH. This can be useful for assuring theconfiguration of a system by putting a playbook on a crontab. This may also be used to run a playbook inside an OSinstaller, such as an Anaconda kickstart.
To run an entire playbook locally, just set the “hosts:” line to “hosts: 127.0.0.1” and then run the playbook like so:
ansible-playbook playbook.yml --connection=local
Alternatively, a local connection can be used in a single playbook play, even if other plays in the playbook use thedefault remote connection type:
- hosts: 127.0.0.1connection: local
Interrupt execution on any error
With option ‘’any_errors_fatal” any failure on any host in a multi-host play will be treated as fatal and Ansible willexit immediately without waiting for the other hosts.
Sometimes ‘’serial” execution is unsuitable - number of hosts is unpredictable (because of dynamic inventory), speedis crucial (simultaneous execution is required). But all tasks must be 100% successful to continue playbook execution.
For example there is a service located in many datacenters, there a some load balancers to pass traffic from users toservice. There is a deploy playbook to upgrade service deb-packages. Playbook stages:
• disable traffic on load balancers (must be turned off simultaneously)
• gracefully stop service
• upgrade software (this step includes tests and starting service)
• enable traffic on load balancers (should be turned off simultaneously)
Service can’t be stopped with “alive” load balancers, they must be disabled, all of them. So second stage can’t beplayed if any server failed on “stage 1”.
For datacenter “A” playbook can be written this way:
---- hosts: load_balancers_dc_a
any_errors_fatal: Truetasks:- name: 'shutting down datacenter [ A ]'command: /usr/bin/disable-dc
1.4. Playbooks: Special Topics 129
Ansible 1.2 Documentation, Release 0.01
- hosts: frontends_dc_atasks:- name: 'stopping service'command: /usr/bin/stop-software
- name: 'updating software'command: /usr/bin/upgrade-software
- hosts: load_balancers_dc_atasks:- name: 'Starting datacenter [ A ]'command: /usr/bin/enable-dc
In this example Ansible will start software upgrade on frontends only if all load balancers are successfully disabled.
See also:
Playbooks An introduction to playbooks
Ansible Examples on GitHub Many examples of full-stack deployments
User Mailing List Have a question? Stop by the google group!
irc.freenode.net #ansible IRC chat channel
Setting the Environment (and Working With Proxies)
New in version 1.1.
It is quite possible that you may need to get package updates through a proxy, or even get some package updatesthrough a proxy and access other packages not through a proxy. Or maybe a script you might wish to call may alsoneed certain environment variables set to run properly.
Ansible makes it easy for you to configure your environment by using the ‘environment’ keyword. Here is an example:
- hosts: allremote_user: root
tasks:
- apt: name=cobbler state=installedenvironment:
http_proxy: http://proxy.example.com:8080
The environment can also be stored in a variable, and accessed like so:
- hosts: allremote_user: root
# here we make a variable named "proxy_env" that is a dictionaryvars:proxy_env:
http_proxy: http://proxy.example.com:8080
tasks:
- apt: name=cobbler state=installedenvironment: "{{proxy_env}}"
You can also use it at a playbook level:
130 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- hosts: testhost
roles:- php- nginx
environment:http_proxy: http://proxy.example.com:8080
While just proxy settings were shown above, any number of settings can be supplied. The most logical place to definean environment hash might be a group_vars file, like so:
---# file: group_vars/boston
ntp_server: ntp.bos.example.combackup: bak.bos.example.comproxy_env:
http_proxy: http://proxy.bos.example.com:8080https_proxy: http://proxy.bos.example.com:8080
See also:
Playbooks An introduction to playbooks
User Mailing List Have a question? Stop by the google group!
irc.freenode.net #ansible IRC chat channel
Error Handling In Playbooks
Topics
• Error Handling In Playbooks
– Ignoring Failed Commands
– Handlers and Failure
– Controlling What Defines Failure
– Overriding The Changed Result
– Aborting the play
Ansible normally has defaults that make sure to check the return codes of commands and modules and it fails fast –forcing an error to be dealt with unless you decide otherwise.
Sometimes a command that returns 0 isn’t an error. Sometimes a command might not always need to report that it‘changed’ the remote system. This section describes how to change the default behavior of Ansible for certain tasksso output and error handling behavior is as desired.
Ignoring Failed Commands
New in version 0.6.
1.4. Playbooks: Special Topics 131
Ansible 1.2 Documentation, Release 0.01
Generally playbooks will stop executing any more steps on a host that has a failure. Sometimes, though, you want tocontinue on. To do so, write a task that looks like this:
- name: this will not be counted as a failurecommand: /bin/falseignore_errors: yes
Note that the above system only governs the return value of failure of the particular task, so if you have an undefinedvariable used, it will still raise an error that users will need to address. Neither will this prevent failures on connectionnor execution issues, the task must be able to run and return a value of ‘failed’.
Handlers and Failure
New in version 1.9.1.
When a task fails on a host, handlers which were previously notified will not be run on that host. This can lead to caseswhere an unrelated failure can leave a host in an unexpected state. For example, a task could update a configurationfile and notify a handler to restart some service. If a task later on in the same play fails, the service will not be restarteddespite the configuration change.
You can change this behavior with the --force-handlers command-line option, or by includingforce_handlers: True in a play, or force_handlers = True in ansible.cfg. When handlers are forced,they will run when notified even if a task fails on that host. (Note that certain errors could still prevent the handlerfrom running, such as a host becoming unreachable.)
Controlling What Defines Failure
New in version 1.4.
Suppose the error code of a command is meaningless and to tell if there is a failure what really matters is the output ofthe command, for instance if the string “FAILED” is in the output.
Ansible in 1.4 and later provides a way to specify this behavior as follows:
- name: this command prints FAILED when it failscommand: /usr/bin/example-command -x -y -zregister: command_resultfailed_when: "'FAILED' in command_result.stderr"
In previous version of Ansible, this can be still be accomplished as follows:
- name: this command prints FAILED when it failscommand: /usr/bin/example-command -x -y -zregister: command_resultignore_errors: True
- name: fail the play if the previous command did not succeedfail: msg="the command failed"when: "'FAILED' in command_result.stderr"
Overriding The Changed Result
New in version 1.3.
When a shell/command or other module runs it will typically report “changed” status based on whether it thinks itaffected machine state.
132 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Sometimes you will know, based on the return code or output that it did not make any changes, and wish to overridethe “changed” result such that it does not appear in report output or does not cause handlers to fire:
tasks:
- shell: /usr/bin/billybass --mode="take me to the river"register: bass_resultchanged_when: "bass_result.rc != 2"
# this will never report 'changed' status- shell: wall 'beep'changed_when: False
Aborting the play
Sometimes it’s desirable to abort the entire play on failure, not just skip remaining tasks for a host.
The any_errors_fatal play option will mark all hosts as failed if any fails, causing an immediate abort:
- hosts: somehostsany_errors_fatal: trueroles:- myrole
for finer-grained control max_fail_percentage can be used to abort the run after a given percentage of hosts hasfailed.
See also:
Playbooks An introduction to playbooks
Best Practices Best practices in playbooks
Conditionals Conditional statements in playbooks
Variables All about variables
User Mailing List Have a question? Stop by the google group!
irc.freenode.net #ansible IRC chat channel
Using Lookups
Lookup plugins allow access of data in Ansible from outside sources. These plugins are evaluated on the Ansiblecontrol machine, and can include reading the filesystem but also contacting external datastores and services. Thesevalues are then made available using the standard templating system in Ansible, and are typically used to load variablesor templates with information from those systems.
Note: This is considered an advanced feature, and many users will probably not rely on these features.
Note: Lookups occur on the local computer, not on the remote computer.
1.4. Playbooks: Special Topics 133
Ansible 1.2 Documentation, Release 0.01
Note: Lookups are executed with a cwd relative to the role or play, as opposed to local tasks which are executed withthe cwd of the executed script.
Note: Since 1.9 you can pass wantlist=True to lookups to use in jinja2 template “for” loops.
Topics
• Using Lookups
– Intro to Lookups: Getting File Contents
– The Password Lookup
– The CSV File Lookup
– The INI File Lookup
– The Credstash Lookup
– The DNS Lookup (dig)
– More Lookups
Intro to Lookups: Getting File Contents
The file lookup is the most basic lookup type.
Contents can be read off the filesystem as follows:
- hosts: allvars:
contents: "{{ lookup('file', '/etc/foo.txt') }}"
tasks:
- debug: msg="the value of foo.txt is {{ contents }}"
The Password Lookup
Note: A great alternative to the password lookup plugin, if you don’t need to generate random passwords on a per-host basis, would be to use Vault. Read the documentation there and consider using it first, it will be more desirablefor most applications.
password generates a random plaintext password and stores it in a file at a given filepath.
(Docs about crypted save modes are pending)
If the file exists previously, it will retrieve its contents, behaving just like with_file. Usage of variables like “{{inventory_hostname }}” in the filepath can be used to set up random passwords per host (what simplifies passwordmanagement in ‘host_vars’ variables).
134 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Generated passwords contain a random mix of upper and lowercase ASCII letters, the numbers 0-9 and punctuation(”. , : - _”). The default length of a generated password is 20 characters. This length can be changed by passing anextra parameter:
---- hosts: all
tasks:
# create a mysql user with a random password:- mysql_user: name={{ client }}
password="{{ lookup('password', 'credentials/' + client + '/' +→˓tier + '/' + role + '/mysqlpassword length=15') }}"
priv={{ client }}_{{ tier }}_{{ role }}.*:ALL
(...)
Note: If the file already exists, no data will be written to it. If the file has contents, those contents will be read in asthe password. Empty files cause the password to return as an empty string
Starting in version 1.4, password accepts a “chars” parameter to allow defining a custom character set in the generatedpasswords. It accepts comma separated list of names that are either string module attributes (ascii_letters,digits, etc)or are used literally:
---- hosts: all
tasks:
# create a mysql user with a random password using only ascii letters:- mysql_user: name={{ client }}
password="{{ lookup('password', '/tmp/passwordfile chars=ascii_→˓letters') }}"
priv={{ client }}_{{ tier }}_{{ role }}.*:ALL
# create a mysql user with a random password using only digits:- mysql_user: name={{ client }}
password="{{ lookup('password', '/tmp/passwordfile chars=digits') }}→˓"
priv={{ client }}_{{ tier }}_{{ role }}.*:ALL
# create a mysql user with a random password using many different char sets:- mysql_user: name={{ client }}
password="{{ lookup('password', '/tmp/passwordfile chars=ascii_→˓letters,digits,hexdigits,punctuation') }}"
priv={{ client }}_{{ tier }}_{{ role }}.*:ALL
(...)
To enter comma use two commas ‘„’ somewhere - preferably at the end. Quotes and double quotes are not supported.
The CSV File Lookup
New in version 1.5.
1.4. Playbooks: Special Topics 135
Ansible 1.2 Documentation, Release 0.01
The csvfile lookup reads the contents of a file in CSV (comma-separated value) format. The lookup looks for therow where the first column matches keyname, and returns the value in the second column, unless a different columnis specified.
The example below shows the contents of a CSV file named elements.csv with information about the periodic table ofelements:
Symbol,Atomic Number,Atomic MassH,1,1.008He,2,4.0026Li,3,6.94Be,4,9.012B,5,10.81
We can use the csvfile plugin to look up the atomic number or atomic of Lithium by its symbol:
- debug: msg="The atomic number of Lithium is {{ lookup('csvfile', 'Li file=elements.→˓csv delimiter=,') }}"- debug: msg="The atomic mass of Lithium is {{ lookup('csvfile', 'Li file=elements.→˓csv delimiter=, col=2') }}"
The csvfile lookup supports several arguments. The format for passing arguments is:
lookup('csvfile', 'key arg1=val1 arg2=val2 ...')
The first value in the argument is the key, which must be an entry that appears exactly once in column 0 (the firstcolumn, 0-indexed) of the table. All other arguments are optional.
Field Default Descriptionfile ansible.csv Name of the file to loaddelimiter TAB Delimiter used by CSV file. As a special case, tab can be specified as either TAB or t.col 1 The column to output, indexed by 0default empty string return value if the key is not in the csv file
Note: The default delimiter is TAB, not comma.
The INI File Lookup
New in version 2.0.
The ini lookup reads the contents of a file in INI format (key1=value1). This plugin retrieve the value on the rightside after the equal sign (‘=’) of a given section ([section]). You can also read a property file which - in this case - doesnot contain section.
Here’s a simple example of an INI file with user/password configuration:
[production]# My production informationuser=robertpass=somerandompassword
[integration]# My integration informationuser=gertrudepass=anotherpassword
136 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
We can use the ini plugin to lookup user configuration:
- debug: msg="User in integration is {{ lookup('ini', 'user section=integration→˓file=users.ini') }}"- debug: msg="User in production is {{ lookup('ini', 'user section=production→˓file=users.ini') }}"
Another example for this plugin is for looking for a value on java properties. Here’s a simple properties we’ll take asan example:
user.name=robertuser.pass=somerandompassword
You can retrieve the user.name field with the following lookup:
- debug: msg="user.name is {{ lookup('ini', 'user.name type=properties file=user.→˓properties') }}"
The ini lookup supports several arguments like the csv plugin. The format for passing arguments is:
lookup('ini', 'key [type=<properties|ini>] [section=section] [file=file.ini]→˓[re=true] [default=<defaultvalue>]')
The first value in the argument is the key, which must be an entry that appears exactly once on keys. All otherarguments are optional.
Field Default Descriptiontype ini Type of the file. Can be ini or properties (for java properties).file ansible.ini Name of the file to loadsection global Default section where to lookup for key.re False The key is a regexp.default empty string return value if the key is not in the ini file
Note: In java properties files, there’s no need to specify a section.
The Credstash Lookup
New in version 2.0.
Credstash is a small utility for managing secrets using AWS’s KMS and DynamoDB: https://github.com/LuminalOSS/credstash
First, you need to store your secrets with credstash:
$ credstash put my-github-password secure123
my-github-password has been stored
Example usage:
---- name: "Test credstash lookup plugin -- get my github password"
debug: msg="Credstash lookup! {{ lookup('credstash', 'my-github-password') }}"
You can specify regions or tables to fetch secrets from:
1.4. Playbooks: Special Topics 137
Ansible 1.2 Documentation, Release 0.01
---- name: "Test credstash lookup plugin -- get my other password from us-west-1"
debug: msg="Credstash lookup! {{ lookup('credstash', 'my-other-password', region=→˓'us-west-1') }}"
- name: "Test credstash lookup plugin -- get the company's github password"debug: msg="Credstash lookup! {{ lookup('credstash', 'company-github-password',
→˓table='company-passwords') }}"
If you’re not using 2.0 yet, you can do something similar with the credstash tool and the pipe lookup (see below):
debug: msg="Poor man's credstash lookup! {{ lookup('pipe', 'credstash -r us-west-1→˓get my-other-password') }}"
The DNS Lookup (dig)
New in version 1.9.0.
Warning: This lookup depends on the dnspython library.
The dig lookup runs queries against DNS servers to retrieve DNS records for a specific name (FQDN - fully qualifieddomain name). It is possible to lookup any DNS record in this manner.
There is a couple of different syntaxes that can be used to specify what record should be retrieved, and for which name.It is also possible to explicitly specify the DNS server(s) to use for lookups.
In its simplest form, the dig lookup plugin can be used to retrieve an IPv4 address (DNS A record) associated withFQDN:
Note: If you need to obtain the AAAA record (IPv6 address), you must specify the record type explicitly. Syntax forspecifying the record type is described below.
Note: The trailing dot in most of the examples listed is purely optional, but is specified for completeness/correctnesssake.
- debug: msg="The IPv4 address for example.com. is {{ lookup('dig', 'example.com.')}}"
In addition to (default) A record, it is also possible to specify a different record type that should be queried. This can bedone by either passing-in additional parameter of format qtype=TYPE to the dig lookup, or by appending /TYPEto the FQDN being queried. For example:
- debug: msg="The TXT record for gmail.com. is {{ lookup('dig', 'gmail.com.',→˓'qtype=TXT') }}"- debug: msg="The TXT record for gmail.com. is {{ lookup('dig', 'gmail.com./TXT') }}"
If multiple values are associated with the requested record, the results will be returned as a comma-separated list. Insuch cases you may want to pass option wantlist=True to the plugin, which will result in the record values beingreturned as a list over which you can iterate later on:
138 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- debug: msg="One of the MX records for gmail.com. is {{ item }}"with_items: "{{ lookup('dig', 'gmail.com./MX', wantlist=True) }}"
In case of reverse DNS lookups (PTR records), you can also use a convenience syntax of format IP_ADDRESS/PTR.The following three lines would produce the same output:
- debug: msg="Reverse DNS for 8.8.8.8 is {{ lookup('dig', '8.8.8.8/PTR') }}"- debug: msg="Reverse DNS for 8.8.8.8 is {{ lookup('dig', '8.8.8.8.in-addr.arpa./PTR→˓') }}"- debug: msg="Reverse DNS for 8.8.8.8 is {{ lookup('dig', '8.8.8.8.in-addr.arpa.',→˓'qtype=PTR') }}"
By default, the lookup will rely on system-wide configured DNS servers for performing the query. It is also possibleto explicitly specify DNS servers to query using the @DNS_SERVER_1,DNS_SERVER_2,...,DNS_SERVER_Nnotation. This needs to be passed-in as an additional parameter to the lookup. For example:
- debug: msg="Querying 8.8.8.8 for IPv4 address for example.com. produces {{ lookup(→˓'dig', 'example.com', '@8.8.8.8') }}"
In some cases the DNS records may hold a more complex data structure, or it may be useful to obtain the results ina form of a dictionary for future processing. The dig lookup supports parsing of a number of such records, with theresult being returned as a dictionary. This way it is possible to easily access such nested data. This return format canbe requested by passing-in the flat=0 option to the lookup. For example:
- debug: msg="XMPP service for gmail.com. is available at {{ item.target }} on port {→˓{ item.port }}"with_items: "{{ lookup('dig', '_xmpp-server._tcp.gmail.com./SRV', 'flat=0',
→˓wantlist=True) }}"
Take note that due to the way Ansible lookups work, you must pass the wantlist=True argument to the lookup,otherwise Ansible will report errors.
Currently the dictionary results are supported for the following records:
Note: ALL is not a record per-se, merely the listed fields are available for any record results you retrieve in the formof a dictionary.
1.4. Playbooks: Special Topics 139
Ansible 1.2 Documentation, Release 0.01
Record FieldsALL owner, ttl, typeA addressAAAA addressCNAME targetDNAME targetDLV algorithm, digest_type, key_tag, digestDNSKEY flags, algorithm, protocol, keyDS algorithm, digest_type, key_tag, digestHINFO cpu, osLOC latitude, longitude, altitude, size, horizontal_precision, vertical_precisionMX preference, exchangeNAPTR order, preference, flags, service, regexp, replacementNS targetNSEC3PARAM algorithm, flags, iterations, saltPTR targetRP mbox, txtSOA mname, rname, serial, refresh, retry, expire, minimumSPF stringsSRV priority, weight, port, targetSSHFP algorithm, fp_type, fingerprintTLSA usage, selector, mtype, certTXT strings
More Lookups
Various lookup plugins allow additional ways to iterate over data. In Loops you will learn how to use them to walkover collections of numerous types. However, they can also be used to pull in data from remote sources, such as shellcommands or even key value stores. This section will cover lookup plugins in this capacity.
Here are some examples:
---- hosts: all
tasks:
- debug: msg="{{ lookup('env','HOME') }} is an environment variable"
- debug: msg="{{ item }} is a line from the result of this command"with_lines:- cat /etc/motd
- debug: msg="{{ lookup('pipe','date') }} is the raw result of running this→˓command"
# redis_kv lookup requires the Python redis package- debug: msg="{{ lookup('redis_kv', 'redis://localhost:6379,somekey') }} is
→˓value in Redis for somekey"
# dnstxt lookup requires the Python dnspython package- debug: msg="{{ lookup('dnstxt', 'example.com') }} is a DNS TXT record for
→˓example.com"
- debug: msg="{{ lookup('template', './some_template.j2') }} is a value from→˓evaluation of this template"
140 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# loading a json file from a template as a string- debug: msg="{{ lookup('template', './some_json.json.j2', convert_data=False) }}
→˓ is a value from evaluation of this template"
- debug: msg="{{ lookup('etcd', 'foo') }} is a value from a locally running etcd"
# shelvefile lookup retrieves a string value corresponding to a key inside a→˓Python shelve file
- debug: msg="{{ lookup('shelvefile', 'file=path_to_some_shelve_file.db key=key_→˓to_retrieve') }}
# The following lookups were added in 1.9- debug: msg="{{item}}"
with_url:- 'https://github.com/gremlin.keys'
# outputs the cartesian product of the supplied lists- debug: msg="{{item}}"
with_cartesian:- list1- list2- list3
As an alternative you can also assign lookup plugins to variables or use them elsewhere. This macros are evaluatedeach time they are used in a task (or template):
vars:motd_value: "{{ lookup('file', '/etc/motd') }}"
tasks:
- debug: msg="motd value is {{ motd_value }}"
See also:
Playbooks An introduction to playbooks
Conditionals Conditional statements in playbooks
Variables All about variables
Loops Looping in playbooks
User Mailing List Have a question? Stop by the google group!
irc.freenode.net #ansible IRC chat channel
Prompts
When running a playbook, you may wish to prompt the user for certain input, and can do so with the ‘vars_prompt’section.
A common use for this might be for asking for sensitive data that you do not want to record.
This has uses beyond security, for instance, you may use the same playbook for all software releases and would promptfor a particular release version in a push-script.
Here is a most basic example:
1.4. Playbooks: Special Topics 141
Ansible 1.2 Documentation, Release 0.01
---- hosts: all
remote_user: root
vars:from: "camelot"
vars_prompt:- name: "name"
prompt: "what is your name?"- name: "quest"
prompt: "what is your quest?"- name: "favcolor"
prompt: "what is your favorite color?"
If you have a variable that changes infrequently, it might make sense to provide a default value that can be overridden.This can be accomplished using the default argument:
vars_prompt:
- name: "release_version"prompt: "Product release version"default: "1.0"
An alternative form of vars_prompt allows for hiding input from the user, and may later support some other options,but otherwise works equivalently:
vars_prompt:
- name: "some_password"prompt: "Enter password"private: yes
- name: "release_version"prompt: "Product release version"private: no
If Passlib is installed, vars_prompt can also crypt the entered value so you can use it, for instance, with the user moduleto define a password:
vars_prompt:
- name: "my_password2"prompt: "Enter password2"private: yesencrypt: "sha512_crypt"confirm: yessalt_size: 7
You can use any crypt scheme supported by ‘Passlib’:
• des_crypt - DES Crypt
• bsdi_crypt - BSDi Crypt
• bigcrypt - BigCrypt
• crypt16 - Crypt16
• md5_crypt - MD5 Crypt
142 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• bcrypt - BCrypt
• sha1_crypt - SHA-1 Crypt
• sun_md5_crypt - Sun MD5 Crypt
• sha256_crypt - SHA-256 Crypt
• sha512_crypt - SHA-512 Crypt
• apr_md5_crypt - Apache’s MD5-Crypt variant
• phpass - PHPass’ Portable Hash
• pbkdf2_digest - Generic PBKDF2 Hashes
• cta_pbkdf2_sha1 - Cryptacular’s PBKDF2 hash
• dlitz_pbkdf2_sha1 - Dwayne Litzenberger’s PBKDF2 hash
• scram - SCRAM Hash
• bsd_nthash - FreeBSD’s MCF-compatible nthash encoding
However, the only parameters accepted are ‘salt’ or ‘salt_size’. You can use your own salt using ‘salt’, or have onegenerated automatically using ‘salt_size’. If nothing is specified, a salt of size 8 will be generated.
See also:
Playbooks An introduction to playbooks
Conditionals Conditional statements in playbooks
Variables All about variables
User Mailing List Have a question? Stop by the google group!
irc.freenode.net #ansible IRC chat channel
Tags
If you have a large playbook it may become useful to be able to run a specific part of the configuration without runningthe whole playbook.
Both plays and tasks support a “tags:” attribute for this reason.
Example:
tasks:
- yum: name={{ item }} state=installedwith_items:
- httpd- memcached
tags:- packages
- template: src=templates/src.j2 dest=/etc/foo.conftags:
- configuration
If you wanted to just run the “configuration” and “packages” part of a very long playbook, you could do this:
1.4. Playbooks: Special Topics 143
Ansible 1.2 Documentation, Release 0.01
ansible-playbook example.yml --tags "configuration,packages"
On the other hand, if you want to run a playbook without certain tasks, you could do this:
ansible-playbook example.yml --skip-tags "notification"
You may also apply tags to roles:
roles:- { role: webserver, port: 5000, tags: [ 'web', 'foo' ] }
And you may also tag basic include statements:
- include: foo.yml tags=web,foo
Both of these apply the specified tags to every task inside the included file or role, so that these tasks can be selectivelyrun when the playbook is invoked with the corresponding tags.
Special Tags
There is a special ‘always’ tag that will always run a task, unless specifically skipped (–skip-tags always)
Example:
tasks:
- debug: msg="Always runs"tags:
- always
- debug: msg="runs when you use tag1"tags:
- tag1
There are another 3 special keywords for tags, ‘tagged’, ‘untagged’ and ‘all’, which run only tagged, only untaggedand all tasks respectively.
By default ansible runs as if ‘–tags all’ had been specified.
See also:
Playbooks An introduction to playbooks
Playbook Roles and Include Statements Playbook organization by roles
User Mailing List Have a question? Stop by the google group!
irc.freenode.net #ansible IRC chat channel
Vault
Topics
• Vault
– What Can Be Encrypted With Vault
144 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
– Creating Encrypted Files
– Editing Encrypted Files
– Rekeying Encrypted Files
– Encrypting Unencrypted Files
– Decrypting Encrypted Files
– Viewing Encrypted Files
– Running a Playbook With Vault
– Speeding Up Vault Operations
New in Ansible 1.5, “Vault” is a feature of ansible that allows keeping sensitive data such as passwords or keys inencrypted files, rather than as plaintext in your playbooks or roles. These vault files can then be distributed or placedin source control.
To enable this feature, a command line tool, ansible-vault is used to edit files, and a command line flag –ask-vault-passor –vault-password-file is used. Alternately, you may specify the location of a password file or command Ansible toalways prompt for the password in your ansible.cfg file. These options require no command line flag usage.
For best practices advice, refer to Variables and Vaults.
What Can Be Encrypted With Vault
The vault feature can encrypt any structured data file used by Ansible. This can include “group_vars/” or “host_vars/”inventory variables, variables loaded by “include_vars” or “vars_files”, or variable files passed on the ansible-playbookcommand line with “-e @file.yml” or “-e @file.json”. Role variables and defaults are also included!
Ansible tasks, handlers, and so on are also data so these can be encrypted with vault as well. To hide the names ofvariables that you’re using, you can encrypt the task files in their entirety. However, that might be a little too much andcould annoy your coworkers :)
Creating Encrypted Files
To create a new encrypted data file, run the following command:
ansible-vault create foo.yml
First you will be prompted for a password. The password used with vault currently must be the same for all files youwish to use together at the same time.
After providing a password, the tool will launch whatever editor you have defined with $EDITOR, and defaults to vim.Once you are done with the editor session, the file will be saved as encrypted data.
The default cipher is AES (which is shared-secret based).
Editing Encrypted Files
To edit an encrypted file in place, use the ansible-vault edit command. This command will decrypt the file to atemporary file and allow you to edit the file, saving it back when done and removing the temporary file:
ansible-vault edit foo.yml
1.4. Playbooks: Special Topics 145
Ansible 1.2 Documentation, Release 0.01
Rekeying Encrypted Files
Should you wish to change your password on a vault-encrypted file or files, you can do so with the rekey command:
ansible-vault rekey foo.yml bar.yml baz.yml
This command can rekey multiple data files at once and will ask for the original password and also the new password.
Encrypting Unencrypted Files
If you have existing files that you wish to encrypt, use the ansible-vault encrypt command. This command can operateon multiple files at once:
ansible-vault encrypt foo.yml bar.yml baz.yml
Decrypting Encrypted Files
If you have existing files that you no longer want to keep encrypted, you can permanently decrypt them by running theansible-vault decrypt command. This command will save them unencrypted to the disk, so be sure you do not wantansible-vault edit instead:
ansible-vault decrypt foo.yml bar.yml baz.yml
Viewing Encrypted Files
Available since Ansible 1.8
If you want to view the contents of an encrypted file without editing it, you can use the ansible-vault view command:
ansible-vault view foo.yml bar.yml baz.yml
Running a Playbook With Vault
To run a playbook that contains vault-encrypted data files, you must pass one of two flags. To specify the vault-password interactively:
ansible-playbook site.yml --ask-vault-pass
This prompt will then be used to decrypt (in memory only) any vault encrypted files that are accessed. Currently thisrequires that all files be encrypted with the same password.
Alternatively, passwords can be specified with a file or a script, the script version will require Ansible 1.7 or later.When using this flag, ensure permissions on the file are such that no one else can access your key and do not add yourkey to source control:
ansible-playbook site.yml --vault-password-file ~/.vault_pass.txt
ansible-playbook site.yml --vault-password-file ~/.vault_pass.py
The password should be a string stored as a single line in the file.
If you are using a script instead of a flat file, ensure that it is marked as executable, and that the password is printed tostandard output. If your script needs to prompt for data, prompts can be sent to standard error.
146 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is something you may wish to do if using Ansible from a continuous integration system like Jenkins.
(The –vault-password-file option can also be used with the Ansible-Pull command if you wish, though this wouldrequire distributing the keys to your nodes, so understand the implications – vault is more intended for push mode).
Speeding Up Vault Operations
By default, Ansible uses PyCrypto to encrypt and decrypt vault files. If you have many encrypted files, decryptingthem at startup may cause a perceptible delay. To speed this up, install the cryptography package:
pip install cryptography
Start and Step
This shows a few alternative ways to run playbooks. These modes are very useful for testing new plays or debugging.
Start-at-task
If you want to start executing your playbook at a particular task, you can do so with the --start-at-task option:
ansible-playbook playbook.yml --start-at-task="install packages"
The above will start executing your playbook at a task named “install packages”.
Step
Playbooks can also be executed interactively with --step:
ansible-playbook playbook.yml --step
This will cause ansible to stop on each task, and ask if it should execute that task. Say you had a task called “configuressh”, the playbook run will stop and ask:
Perform task: configure ssh (y/n/c):
Answering “y” will execute the task, answering “n” will skip the task, and answering “c” will continue executing allthe remaining tasks without asking.
About Modules
Introduction
Modules (also referred to as “task plugins” or “library plugins”) are the ones that do the actual work in ansible, theyare what gets executed in each playbook task. But you can also run a single one using the ‘ansible’ command.
Let’s review how we execute three different modules from the command line:
ansible webservers -m service -a "name=httpd state=started"ansible webservers -m pingansible webservers -m command -a "/sbin/reboot -t now"
1.5. About Modules 147
Ansible 1.2 Documentation, Release 0.01
Each module supports taking arguments. Nearly all modules take key=value arguments, space delimited. Somemodules take no arguments, and the command/shell modules simply take the string of the command you want to run.
From playbooks, Ansible modules are executed in a very similar way:
- name: reboot the serversaction: command /sbin/reboot -t now
Which can be abbreviated to:
- name: reboot the serverscommand: /sbin/reboot -t now
Another way to pass arguments to a module is using yaml syntax also called ‘complex args’
- name: restart webserverservice:name: httpdstate: restarted
All modules technically return JSON format data, though if you are using the command line or playbooks, you don’treally need to know much about that. If you’re writing your own module, you care, and this means you do not have towrite modules in any particular language – you get to choose.
Modules strive to be idempotent, meaning they will seek to avoid changes to the system unless a change needs to bemade. When using Ansible playbooks, these modules can trigger ‘change events’ in the form of notifying ‘handlers’to run additional tasks.
Documentation for each module can be accessed from the command line with the ansible-doc tool:
ansible-doc yum
A list of all installed modules is also available:
ansible-doc -l
See also:
Introduction To Ad-Hoc Commands Examples of using modules in /usr/bin/ansible
Playbooks Examples of using modules with /usr/bin/ansible-playbook
Developing Modules How to write your own modules
Python API Examples of using modules with the Python API
Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
irc.freenode.net #ansible IRC chat channel
Core Modules
These are modules that the core ansible team maintains and will always ship with ansible itself. They will also receiveslightly higher priority for all requests than those in the “extras” repos.
The source of these modules is hosted on GitHub in the ansible-modules-core repo.
If you believe you have found a bug in a core module and are already running the latest stable or development versionof Ansible, first look in the issue tracker at github.com/ansible/ansible-modules-core to see if a bug has already beenfiled. If not, we would be grateful if you would file one.
148 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Should you have a question rather than a bug report, inquiries are welcome on the ansible-project google group or onAnsible’s “#ansible” channel, located on irc.freenode.net. Development oriented topics should instead use the similaransible-devel google group.
Documentation updates for these modules can also be edited directly in the module itself and by submitting a pullrequest to the module source code, just look for the “DOCUMENTATION” block in the source tree.
Extras Modules
These modules are currently shipped with Ansible, but might be shipped separately in the future. They are also mostlymaintained by the community. Non-core modules are still fully usable, but may receive slightly lower response ratesfor issues and pull requests.
Popular “extras” modules may be promoted to core modules over time.
This source for these modules is hosted on GitHub in the ansible-modules-extras repo.
If you believe you have found a bug in an extras module and are already running the latest stable or developmentversion of Ansible, first look in the issue tracker at github.com/ansible/ansible-modules-extras to see if a bug hasalready been filed. If not, we would be grateful if you would file one.
Should you have a question rather than a bug report, inquries are welcome on the ansible-project google group or onAnsible’s “#ansible” channel, located on irc.freenode.net. Development oriented topics should instead use the similaransible-devel google group.
Documentation updates for this module can also be edited directly in the module and by submitting a pull request tothe module source code, just look for the “DOCUMENTATION” block in the source tree.
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
Common Return Values
Topics
• Common Return Values
– Facts
– Status
– Other common returns
Ansible modules normally return a data structure that can be registered into a variable, or seen directly when usingthe ansible program as output. Here we document the values common to all modules, each module can optionallydocument its own unique returns. If these docs exist they will be visible through ansible-doc and https://docs.ansible.com.
Facts
Some modules return ‘facts’ to ansible (i.e setup), this is done through a ‘ansible_facts’ key and anything inside willautomatically be available for the current host directly as a variable and there is no need to register this data.
1.5. About Modules 149
Ansible 1.2 Documentation, Release 0.01
Status
Every module must return a status, saying if the module was successful, if anything changed or not. Ansible itself willreturn a status if it skips the module due to a user condition (when: ) or running in check mode when the module doesnot support it.
Other common returns
It is common on failure or success to return a ‘msg’ that either explains the failure or makes a note about the execution.Some modules, specifically those that execute shell or commands directly, will return stdout and stderr, if ansible seesa stdout in the results it will append a stdout_lines which is just a list or the lines in stdout.
See also:
About Modules Learn about available modules
GitHub Core modules directory Browse source of core modules
Github Extras modules directory Browse source of extras modules.
Mailing List Development mailing list
irc.freenode.net #ansible IRC chat channel
Ansible ships with a number of modules (called the ‘module library’) that can be executed directly on remote hosts orthrough Playbooks.
Users can also write their own modules. These modules can control system resources, like services, packages, or files(anything really), or handle executing system commands.
See also:
Introduction To Ad-Hoc Commands Examples of using modules in /usr/bin/ansible
Playbooks Examples of using modules with /usr/bin/ansible-playbook
Developing Modules How to write your own modules
Python API Examples of using modules with the Python API
Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
irc.freenode.net #ansible IRC chat channel
Module Index
All Modules
a10_server - Manage A10 Networks AX/SoftAX/Thunder/vThunder devices
New in version 1.8.
• Synopsis
• Options
• Examples
150 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Notes
• This is an Extras Module
Synopsis
Manage slb server objects on A10 Networks devices via aXAPI
Options
Examples
# Create a new server- a10_server:
host: a10.mydomain.comusername: myadminpassword: mypasswordserver: testserver_ip: 1.1.1.100server_ports:- port_num: 8080protocol: tcp
- port_num: 8443protocol: TCP
Notes
Note: Requires A10 Networks aXAPI 2.1
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
a10_service_group - Manage A10 Networks devices’ service groups
New in version 1.8.
• Synopsis
• Options
• Examples
• Notes
1.6. Module Index 151
Ansible 1.2 Documentation, Release 0.01
• This is an Extras Module
Synopsis
Manage slb service-group objects on A10 Networks devices via aXAPI
Options
Examples
# Create a new service-group- a10_service_group:
host: a10.mydomain.comusername: myadminpassword: mypasswordservice_group: sg-80-tcpservers:- server: foo1.mydomain.comport: 8080
- server: foo2.mydomain.comport: 8080
- server: foo3.mydomain.comport: 8080
- server: foo4.mydomain.comport: 8080status: disabled
Notes
Note: Requires A10 Networks aXAPI 2.1
Note: When a server doesn’t exist and is added to the service-group the server will be created
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
a10_virtual_server - Manage A10 Networks devices’ virtual servers
New in version 1.8.
152 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manage slb virtual server objects on A10 Networks devices via aXAPI
Options
Examples
# Create a new virtual server- a10_virtual_server:
host: a10.mydomain.comusername: myadminpassword: mypasswordvirtual_server: vserver1virtual_server_ip: 1.1.1.1virtual_server_ports:- port: 80protocol: TCPservice_group: sg-80-tcp
- port: 443protocol: HTTPSservice_group: sg-443-https
- port: 8080protocol: httpstatus: disabled
Notes
Note: Requires A10 Networks aXAPI 2.1
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 153
Ansible 1.2 Documentation, Release 0.01
accelerate - Enable accelerated mode on remote node
New in version 1.3.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
This modules launches an ephemeral accelerate daemon on the remote node which Ansible can use to communicatewith nodes at high speed. The daemon listens on a configurable port for a configurable amount of time. Fireball modeis AES encrypted
Requirements
• python >= 2.6
• python-keyczar
Options
Examples
# To use accelerate mode, simply add "accelerate: true" to your play. The→˓initial# key exchange and starting up of the daemon will occur over SSH, but all→˓commands and# subsequent actions will be conducted over the raw socket connection using→˓AES encryption
- hosts: devserversaccelerate: truetasks:
- command: /usr/bin/anything
Notes
Note: See the advanced playbooks chapter for more about using accelerated mode.
154 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
acl - Sets and retrieves file ACL information.
New in version 1.4.
• Synopsis
• Options
• Examples
• Return Values
• Notes
• This is a Core Module
Synopsis
Sets and retrieves file ACL information.
Options
Examples
# Grant user Joe read access to a file- acl: name=/etc/foo.conf entity=joe etype=user permissions="r" state=present
# Removes the acl for Joe on a specific file- acl: name=/etc/foo.conf entity=joe etype=user state=absent
# Sets default acl for joe on foo.d- acl: name=/etc/foo.d entity=joe etype=user permissions=rw default=yes→˓state=present
# Same as previous but using entry shorthand- acl: name=/etc/foo.d entry="default:user:joe:rw-" state=present
# Obtain the acl for a specific file- acl: name=/etc/foo.confregister: acl_info
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
1.6. Module Index 155
Ansible 1.2 Documentation, Release 0.01
Notes
Note: The “acl” module requires that acls are enabled on the target filesystem and that the setfacl and getfacl binariesare installed.
Note: As of Ansible 2.0, this module only supports Linux distributions.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
add_host - add a host (and alternatively a group) to the ansible-playbook in-memory inventory
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Use variables to create new hosts and groups in inventory for use in later plays of the same playbook. Takes variablesso you can define the new hosts more fully.
Options
Examples
# add host to group 'just_created' with variable foo=42- add_host: name={{ ip_from_ec2 }} groups=just_created foo=42
# add a host with a non-standard port local to your machines- add_host: name={{ new_ip }}:{{ new_port }}
# add a host alias that we reach through a tunnel- add_host: hostname={{ new_ip }}
ansible_ssh_host={{ inventory_hostname }}ansible_ssh_port={{ new_port }}
156 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Notes
Note: This module bypasses the play host loop and only runs once for all the hosts in the play, if you need it to iterateuse a with_ directive.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
airbrake_deployment - Notify airbrake about app deployments
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Notify airbrake about app deployments (see http://help.airbrake.io/kb/api-2/deploy-tracking)
Options
Examples
- airbrake_deployment: token=AAAAAAenvironment='staging'user='ansible'revision=4.2
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
alternatives - Manages alternative programs for common commands
New in version 1.6.
1.6. Module Index 157
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Manages symbolic links using the ‘update-alternatives’ tool Useful when multiple programs are installed but providesimilar functionality (e.g. different editors).
Requirements
• update-alternatives
Options
Examples
- name: correct java version selectedalternatives: name=java path=/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java
- name: alternatives link createdalternatives: name=hadoop-conf link=/etc/hadoop/conf path=/etc/hadoop/conf.
→˓ansible
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
apache2_module - enables/disables a module of the Apache2 webserver
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
158 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• This is a Core Module
Synopsis
Enables or disables a specified module of the Apache2 webserver.
Requirements
• a2enmod
• a2dismod
Options
Examples
# enables the Apache2 module "wsgi"- apache2_module: state=present name=wsgi
# disables the Apache2 module "wsgi"- apache2_module: state=absent name=wsgi
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
apk - Manages apk packages
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manages apk packages for Alpine Linux.
1.6. Module Index 159
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Update repositories and install "foo" package- apk: name=foo update_cache=yes
# Update repositories and install "foo" and "bar" packages- apk: name=foo,bar update_cache=yes
# Remove "foo" package- apk: name=foo state=absent
# Remove "foo" and "bar" packages- apk: name=foo,bar state=absent
# Install the package "foo"- apk: name=foo state=present
# Install the packages "foo" and "bar"- apk: name=foo,bar state=present
# Update repositories and update package "foo" to latest version- apk: name=foo state=latest update_cache=yes
# Update repositories and update packages "foo" and "bar" to latest versions- apk: name=foo,bar state=latest update_cache=yes
# Update all installed packages to the latest versions- apk: upgrade=yes
# Update repositories as a separate step- apk: update_cache=yes
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
apt - Manages apt-packages
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
160 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• This is a Core Module
Synopsis
Manages apt packages (such as for Debian/Ubuntu).
Requirements
• python-apt
• aptitude
Options
Examples
# Update repositories cache and install "foo" package- apt: name=foo update_cache=yes
# Remove "foo" package- apt: name=foo state=absent
# Install the package "foo"- apt: name=foo state=present
# Install the version '1.00' of package "foo"- apt: name=foo=1.00 state=present
# Update the repository cache and update package "nginx" to latest version→˓using default release squeeze-backport- apt: name=nginx state=latest default_release=squeeze-backports update_→˓cache=yes
# Install latest version of "openjdk-6-jdk" ignoring "install-recommends"- apt: name=openjdk-6-jdk state=latest install_recommends=no
# Update all packages to the latest version- apt: upgrade=dist
# Run the equivalent of "apt-get update" as a separate step- apt: update_cache=yes
# Only run "update_cache=yes" if the last one is more than 3600 seconds ago- apt: update_cache=yes cache_valid_time=3600
# Pass options to dpkg on run- apt: upgrade=dist update_cache=yes dpkg_options='force-confold,force-→˓confdef'
# Install a .deb package- apt: deb=/tmp/mypackage.deb
1.6. Module Index 161
Ansible 1.2 Documentation, Release 0.01
# Install the build dependencies for package "foo"- apt: pkg=foo state=build-dep
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Three of the upgrade modes (full, safe and its alias yes) require aptitude, otherwise apt-getsuffices.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
apt_key - Add or remove an apt key
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Add or remove an apt key, optionally downloading it
Options
Examples
# Add an apt key by id from a keyserver- apt_key: keyserver=keyserver.ubuntu.com→˓id=36A1D7869245C8950F966E92D8576A8BA88D21E9
# Add an Apt signing key, uses whichever key is at the URL- apt_key: url=https://ftp-master.debian.org/keys/archive-key-6.0.asc→˓state=present
162 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# Add an Apt signing key, will not download if present- apt_key: id=473041FA url=https://ftp-master.debian.org/keys/archive-key-6.→˓0.asc state=present
# Remove an Apt signing key, uses whichever key is at the URL- apt_key: url=https://ftp-master.debian.org/keys/archive-key-6.0.asc→˓state=absent
# Remove a Apt specific signing key, leading 0x is valid- apt_key: id=0x473041FA state=absent
# Add a key from a file on the Ansible server- apt_key: data="{{ lookup('file', 'apt.gpg') }}" state=present
# Add an Apt signing key to a specific keyring file- apt_key: id=473041FA url=https://ftp-master.debian.org/keys/archive-key-6.→˓0.asc keyring=/etc/apt/trusted.gpg.d/debian.gpg state=present
Notes
Note: doesn’t download the key unless it really needs it
Note: as a sanity check, downloaded key id must match the one specified
Note: best practice is to specify the key id and the url
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
apt_repository - Add and remove APT repositories
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
1.6. Module Index 163
Ansible 1.2 Documentation, Release 0.01
Synopsis
Add or remove an APT repositories in Ubuntu and Debian.
Requirements
• python-apt
Options
Examples
# Add specified repository into sources list.apt_repository: repo='deb http://archive.canonical.com/ubuntu hardy partner'→˓state=present
# Add source repository into sources list.apt_repository: repo='deb-src http://archive.canonical.com/ubuntu hardy→˓partner' state=present
# Remove specified repository from sources list.apt_repository: repo='deb http://archive.canonical.com/ubuntu hardy partner'→˓state=absent
# On Ubuntu target: add nginx stable repository from PPA and install its→˓signing key.# On Debian target: adding PPA is not available, so it will fail immediately.apt_repository: repo='ppa:nginx/stable'
Notes
Note: This module works on Debian and Ubuntu and requires python-apt.
Note: This module supports Debian Squeeze (version 6) as well as its successors.
Note: This module treats Debian and Ubuntu distributions separately. So PPA could be installed only on Ubuntumachines.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
164 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
apt_rpm - apt_rpm package manager
New in version 1.5.
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
Manages packages with apt-rpm. Both low-level (rpm) and high-level (apt-get) package manager binaries required.
Options
Examples
# install package foo- apt_rpm: pkg=foo state=present# remove package foo- apt_rpm: pkg=foo state=absent# description: remove packages foo and bar- apt_rpm: pkg=foo,bar state=absent# description: update the package database and install bar (bar will be the→˓updated if a newer version exists)- apt_rpm: name=bar state=present update_cache=yes
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
assemble - Assembles a configuration file from fragments
• Synopsis
• Options
• Examples
• This is a Core Module
1.6. Module Index 165
Ansible 1.2 Documentation, Release 0.01
Synopsis
Assembles a configuration file from fragments. Often a particular program will take a single configuration file and doesnot support a conf.d style structure where it is easy to build up the configuration from multiple sources. assemblewill take a directory of files that can be local or have already been transferred to the system, and concatenate themtogether to produce a destination file. Files are assembled in string sorting order. Puppet calls this idea fragments.
Options
Examples
# Example from Ansible Playbooks- assemble: src=/etc/someapp/fragments dest=/etc/someapp/someapp.conf
# When a delimiter is specified, it will be inserted in between each fragment- assemble: src=/etc/someapp/fragments dest=/etc/someapp/someapp.conf→˓delimiter='### START FRAGMENT ###'
# Copy a new "sshd_config" file into place, after passing validation with→˓sshd- assemble: src=/etc/ssh/conf.d/ dest=/etc/ssh/sshd_config validate='/usr/→˓sbin/sshd -t -f %s'
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
assert - Fail with custom message
New in version 1.5.
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
This module asserts that a given expression is true and can be a simpler alternative to the ‘fail’ module in some cases.
Options
166 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
- assert: { that: "ansible_os_family != 'RedHat'" }
- assert:that:- "'foo' in some_command_result.stdout"- "number_of_the_counting == 3"
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
async_status - Obtain status of asynchronous task
• Synopsis
• Options
• Notes
• This is a Core Module
Synopsis
This module gets the status of an asynchronous task.
Options
Notes
Note: See also http://docs.ansible.com/playbooks_async.html
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 167
Ansible 1.2 Documentation, Release 0.01
at - Schedule the execution of a command or script file via the at command.
New in version 1.5.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Use this module to schedule a command or script file to run once in the future. All jobs are executed in the ‘a’ queue.
Requirements
• at
Options
Examples
# Schedule a command to execute in 20 minutes as root.- at: command="ls -d / > /dev/null" count=20 units="minutes"
# Match a command to an existing job and delete the job.- at: command="ls -d / > /dev/null" state="absent"
# Schedule a command to execute in 20 minutes making sure it is unique in→˓the queue.- at: command="ls -d / > /dev/null" unique=true count=20 units="minutes"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
authorized_key - Adds or removes an SSH authorized key
• Synopsis
• Options
168 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Examples
• This is a Core Module
Synopsis
Adds or removes SSH authorized keys for particular user accounts
Options
Examples
# Example using key data from a local file on the management machine- authorized_key: user=charlie key="{{ lookup('file', '/home/charlie/.ssh/id_→˓rsa.pub') }}"
# Using github url as key source- authorized_key: user=charlie key=https://github.com/charlie.keys
# Using alternate directory locations:- authorized_key: user=charlie
key="{{ lookup('file', '/home/charlie/.ssh/id_rsa.pub') }}"path='/etc/ssh/authorized_keys/charlie'manage_dir=no
# Using with_file- name: Set up authorized_keys for the deploy userauthorized_key: user=deploy
key="{{ item }}"with_file:
- public_keys/doe-jane- public_keys/doe-john
# Using key_options:- authorized_key: user=charlie
key="{{ lookup('file', '/home/charlie/.ssh/id_rsa.pub') }}"key_options='no-port-forwarding,from="10.0.1.1"'
# Set up authorized_keys exclusively with one key- authorized_key: user=root key="{{ item }}" state=present
exclusive=yeswith_file:
- public_keys/doe-jane
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 169
Ansible 1.2 Documentation, Release 0.01
azure - create or terminate a virtual machine in azure
New in version 1.7.
• Synopsis
• Requirements
• Options
• Examples
• This is a Core Module
Synopsis
Creates or terminates azure instances. When created optionally waits for it to be ‘running’.
Requirements
• python >= 2.6
• azure >= 0.7.1
Options
Examples
# Note: None of these examples set subscription_id or management_cert_path# It is assumed that their matching environment variables are set.
# Provision virtual machine example- local_action:
module: azurename: my-virtual-machinerole_size: Smallimage: b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu_DAILY_BUILD-precise-12_
→˓04_3-LTS-amd64-server-20131205-en-us-30GBlocation: 'East US'user: ubuntussh_cert_path: /path/to/azure_x509_cert.pemstorage_account: my-storage-accountwait: yes
# Terminate virtual machine example- local_action:
module: azurename: my-virtual-machinestate: absent
#Create windows machine- hosts: allconnection: local
170 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
tasks:- local_action:
module: azurename: "ben-Winows-23"hostname: "win123"os_type: windowsenable_winrm: yessubscription_id: "{{ azure_sub_id }}"management_cert_path: "{{ azure_cert_path }}"role_size: Smallimage: 'bd507d3a70934695bc2128e3e5a255ba__RightImage-Windows-2012-x64-
→˓v13.5'location: 'East Asia'password: "xxx"storage_account: benooytesuser: adminwait: yesvirtual_network_name: "{{ vnet_name }}"
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
bigip_facts - Collect facts from F5 BIG-IP devices
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Collect facts from F5 BIG-IP devices via iControl SOAP API
Requirements
• bigsuds
1.6. Module Index 171
Ansible 1.2 Documentation, Release 0.01
Options
Examples
## playbook task examples:
---# file bigip-test.yml# ...- hosts: bigip-testtasks:- name: Collect BIG-IP facts
local_action: >bigip_factsserver=lb.mydomain.comuser=adminpassword=mysecretinclude=interface,vlan
Notes
Note: Requires BIG-IP software version >= 11.4
Note: F5 developed module ‘bigsuds’ required (see http://devcentral.f5.com)
Note: Best run as a local_action in your playbook
Note: Tested with manager and above account privilege level
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
bigip_gtm_wide_ip - Manages F5 BIG-IP GTM wide ip
New in version 2.0.
• Synopsis
• Requirements
172 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manages F5 BIG-IP GTM wide ip
Requirements
• bigsuds
Options
Examples
- name: Set lb methodlocal_action: >
bigip_gtm_wide_ipserver=192.168.0.1user=adminpassword=mysecretlb_method=round_robinwide_ip=my-wide-ip.example.com
Notes
Note: Requires BIG-IP software version >= 11.4
Note: F5 developed module ‘bigsuds’ required (see http://devcentral.f5.com)
Note: Best run as a local_action in your playbook
Note: Tested with manager and above account privilege level
This is an Extras Module
For more information on what this means please read Extras Modules
1.6. Module Index 173
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
bigip_monitor_http - Manages F5 BIG-IP LTM http monitors
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manages F5 BIG-IP LTM monitors via iControl SOAP API
Requirements
• bigsuds
Options
Examples
- name: BIGIP F5 | Create HTTP Monitorlocal_action:
module: bigip_monitor_httpstate: presentserver: "{{ f5server }}"user: "{{ f5user }}"password: "{{ f5password }}"name: "{{ item.monitorname }}"send: "{{ item.send }}"receive: "{{ item.receive }}"
with_items: f5monitors- name: BIGIP F5 | Remove HTTP Monitorlocal_action:
module: bigip_monitor_httpstate: absentserver: "{{ f5server }}"user: "{{ f5user }}"password: "{{ f5password }}"name: "{{ monitorname }}"
174 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Notes
Note: Requires BIG-IP software version >= 11
Note: F5 developed module ‘bigsuds’ required (see http://devcentral.f5.com)
Note: Best run as a local_action in your playbook
Note: Monitor API documentation: https://devcentral.f5.com/wiki/iControl.LocalLB__Monitor.ashx
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
bigip_monitor_tcp - Manages F5 BIG-IP LTM tcp monitors
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manages F5 BIG-IP LTM tcp monitors via iControl SOAP API
Requirements
• bigsuds
1.6. Module Index 175
Ansible 1.2 Documentation, Release 0.01
Options
Examples
- name: BIGIP F5 | Create TCP Monitorlocal_action:
module: bigip_monitor_tcpstate: presentserver: "{{ f5server }}"user: "{{ f5user }}"password: "{{ f5password }}"name: "{{ item.monitorname }}"type: tcpsend: "{{ item.send }}"receive: "{{ item.receive }}"
with_items: f5monitors-tcp- name: BIGIP F5 | Create TCP half open Monitorlocal_action:
module: bigip_monitor_tcpstate: presentserver: "{{ f5server }}"user: "{{ f5user }}"password: "{{ f5password }}"name: "{{ item.monitorname }}"type: tcpsend: "{{ item.send }}"receive: "{{ item.receive }}"
with_items: f5monitors-halftcp- name: BIGIP F5 | Remove TCP Monitorlocal_action:
module: bigip_monitor_tcpstate: absentserver: "{{ f5server }}"user: "{{ f5user }}"password: "{{ f5password }}"name: "{{ monitorname }}"
with_flattened:- f5monitors-tcp- f5monitors-halftcp
Notes
Note: Requires BIG-IP software version >= 11
Note: F5 developed module ‘bigsuds’ required (see http://devcentral.f5.com)
Note: Best run as a local_action in your playbook
176 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: Monitor API documentation: https://devcentral.f5.com/wiki/iControl.LocalLB__Monitor.ashx
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
bigip_node - Manages F5 BIG-IP LTM nodes
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manages F5 BIG-IP LTM nodes via iControl SOAP API
Requirements
• bigsuds
Options
Examples
## playbook task examples:
---# file bigip-test.yml# ...- hosts: bigip-testtasks:- name: Add node
local_action: >bigip_nodeserver=lb.mydomain.comuser=admin
1.6. Module Index 177
Ansible 1.2 Documentation, Release 0.01
password=mysecretstate=presentpartition=matthitehost="{{ ansible_default_ipv4["address"] }}"name="{{ ansible_default_ipv4["address"] }}"
# Note that the BIG-IP automatically names the node using the# IP address specified in previous play's host parameter.# Future plays referencing this node no longer use the host# parameter but instead use the name parameter.# Alternatively, you could have specified a name with the# name parameter when state=present.
- name: Modify node descriptionlocal_action: >bigip_nodeserver=lb.mydomain.comuser=adminpassword=mysecretstate=presentpartition=matthitename="{{ ansible_default_ipv4["address"] }}"description="Our best server yet"
- name: Delete nodelocal_action: >
bigip_nodeserver=lb.mydomain.comuser=adminpassword=mysecretstate=absentpartition=matthitename="{{ ansible_default_ipv4["address"] }}"
# The BIG-IP GUI doesn't map directly to the API calls for "Node -># General Properties -> State". The following states map to API monitor# and session states.## Enabled (all traffic allowed):# monitor_state=enabled, session_state=enabled# Disabled (only persistent or active connections allowed):# monitor_state=enabled, session_state=disabled# Forced offline (only active connections allowed):# monitor_state=disabled, session_state=disabled## See https://devcentral.f5.com/questions/icontrol-equivalent-call-for-b-→˓node-down
- name: Force node offlinelocal_action: >
bigip_nodeserver=lb.mydomain.comuser=adminpassword=mysecretstate=presentsession_state=disabledmonitor_state=disabledpartition=matthite
178 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
name="{{ ansible_default_ipv4["address"] }}"
Notes
Note: Requires BIG-IP software version >= 11
Note: F5 developed module ‘bigsuds’ required (see http://devcentral.f5.com)
Note: Best run as a local_action in your playbook
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
bigip_pool - Manages F5 BIG-IP LTM pools
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manages F5 BIG-IP LTM pools via iControl SOAP API
Requirements
• bigsuds
Options
1.6. Module Index 179
Ansible 1.2 Documentation, Release 0.01
Examples
## playbook task examples:
---# file bigip-test.yml# ...- hosts: localhosttasks:- name: Create pool
local_action: >bigip_poolserver=lb.mydomain.comuser=adminpassword=mysecretstate=presentname=matthite-poolpartition=matthitelb_method=least_connection_memberslow_ramp_time=120
- name: Modify load balancer methodlocal_action: >
bigip_poolserver=lb.mydomain.comuser=adminpassword=mysecretstate=presentname=matthite-poolpartition=matthitelb_method=round_robin
- hosts: bigip-testtasks:- name: Add pool member
local_action: >bigip_poolserver=lb.mydomain.comuser=adminpassword=mysecretstate=presentname=matthite-poolpartition=matthitehost="{{ ansible_default_ipv4["address"] }}"port=80
- name: Remove pool member from poollocal_action: >
bigip_poolserver=lb.mydomain.comuser=adminpassword=mysecretstate=absentname=matthite-poolpartition=matthitehost="{{ ansible_default_ipv4["address"] }}"port=80
180 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- hosts: localhosttasks:- name: Delete pool
local_action: >bigip_poolserver=lb.mydomain.comuser=adminpassword=mysecretstate=absentname=matthite-poolpartition=matthite
Notes
Note: Requires BIG-IP software version >= 11
Note: F5 developed module ‘bigsuds’ required (see http://devcentral.f5.com)
Note: Best run as a local_action in your playbook
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
bigip_pool_member - Manages F5 BIG-IP LTM pool members
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manages F5 BIG-IP LTM pool members via iControl SOAP API
1.6. Module Index 181
Ansible 1.2 Documentation, Release 0.01
Requirements
• bigsuds
Options
Examples
## playbook task examples:
---# file bigip-test.yml# ...- hosts: bigip-testtasks:- name: Add pool member
local_action: >bigip_pool_memberserver=lb.mydomain.comuser=adminpassword=mysecretstate=presentpool=matthite-poolpartition=matthitehost="{{ ansible_default_ipv4["address"] }}"port=80description="web server"connection_limit=100rate_limit=50ratio=2
- name: Modify pool member ratio and descriptionlocal_action: >
bigip_pool_memberserver=lb.mydomain.comuser=adminpassword=mysecretstate=presentpool=matthite-poolpartition=matthitehost="{{ ansible_default_ipv4["address"] }}"port=80ratio=1description="nginx server"
- name: Remove pool member from poollocal_action: >
bigip_pool_memberserver=lb.mydomain.comuser=adminpassword=mysecretstate=absentpool=matthite-poolpartition=matthitehost="{{ ansible_default_ipv4["address"] }}"port=80
182 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# The BIG-IP GUI doesn't map directly to the API calls for "Pool -># Members -> State". The following states map to API monitor# and session states.## Enabled (all traffic allowed):# monitor_state=enabled, session_state=enabled# Disabled (only persistent or active connections allowed):# monitor_state=enabled, session_state=disabled# Forced offline (only active connections allowed):# monitor_state=disabled, session_state=disabled## See https://devcentral.f5.com/questions/icontrol-equivalent-call-for-b-
→˓node-down
- name: Force pool member offlinelocal_action: >bigip_pool_memberserver=lb.mydomain.comuser=adminpassword=mysecretstate=presentsession_state=disabledmonitor_state=disabledpool=matthite-poolpartition=matthitehost="{{ ansible_default_ipv4["address"] }}"port=80
Notes
Note: Requires BIG-IP software version >= 11
Note: F5 developed module ‘bigsuds’ required (see http://devcentral.f5.com)
Note: Best run as a local_action in your playbook
Note: Supersedes bigip_pool for managing pool members
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 183
Ansible 1.2 Documentation, Release 0.01
bigpanda - Notify BigPanda about deployments
New in version 1.8.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Notify BigPanda when deployments start and end (successfully or not). Returns a deployment object containing allthe parameters for future module calls.
Options
Examples
- bigpanda: component=myapp version=1.3 token={{ bigpanda_token }}→˓state=started...- bigpanda: component=myapp version=1.3 token={{ bigpanda_token }}→˓state=finished
or using a deployment object:- bigpanda: component=myapp version=1.3 token={{ bigpanda_token }}→˓state=startedregister: deployment
- bigpanda: state=finishedargs: deployment
If outside servers aren't reachable from your machine, use local_action and→˓pass the hostname:- local_action: bigpanda component=myapp version=1.3 hosts={{ansible_→˓hostname}} token={{ bigpanda_token }} state=startedregister: deployment
...- local_action: bigpanda state=finishedargs: deployment
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
184 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
blockinfile - Insert/update/remove a text block surrounded by marker lines.
New in version 2.0.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
This module will insert/update/remove a block of multi-line text surrounded by customizable marker lines.
Options
Examples
- name: insert/update "Match User" configuation block in /etc/ssh/sshd_configblockinfile:
dest: /etc/ssh/sshd_configblock: |
Match User ansible-agentPasswordAuthentication no
- name: insert/update eth0 configuration stanza in /etc/network/interfaces(it might be better to copy files into /etc/network/interfaces.d/)
blockinfile:dest: /etc/network/interfacesblock: |iface eth0 inet static
address 192.168.0.1netmask 255.255.255.0
- name: insert/update HTML surrounded by custom markers after <body> lineblockinfile:
dest: /var/www/html/index.htmlmarker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"insertafter: "<body>"content: |
<h1>Welcome to {{ansible_hostname}}</h1><p>Last updated on {{ansible_date_time.iso8601}}</p>
- name: remove HTML as well as surrounding markersblockinfile:
dest: /var/www/html/index.htmlmarker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"content: ""
1.6. Module Index 185
Ansible 1.2 Documentation, Release 0.01
Notes
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
boundary_meter - Manage boundary meters
New in version 1.3.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
This module manages boundary meters
Requirements
• Boundary API access
• bprobe is required to send data, but not to register a meter
Options
Examples
- name: Create meterboundary_meter: apiid=AAAAAA api_key=BBBBBB state=present name={{
→˓inventory_hostname }}"
- name: Delete meterboundary_meter: apiid=AAAAAA api_key=BBBBBB state=absent name={{ inventory_
→˓hostname }}"
186 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Notes
Note: This module does not yet support boundary tags.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
bower - Manage bower packages with bower
New in version 1.9.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manage bower packages with bower
Options
Examples
description: Install "bootstrap" bower package.- bower: name=bootstrap
description: Install "bootstrap" bower package on version 3.1.1.- bower: name=bootstrap version=3.1.1
description: Remove the "bootstrap" bower package.- bower: name=bootstrap state=absent
description: Install packages based on bower.json.- bower: path=/app/location
description: Update packages based on bower.json to their latest version.- bower: path=/app/location state=latest
1.6. Module Index 187
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
bundler - Manage Ruby Gem dependencies with Bundler
New in version 2.0.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manage installation and Gem version dependencies for Ruby using the Bundler gem
Options
Examples
# Installs gems from a Gemfile in the current directory- bundler: state=present executable=~/.rvm/gems/2.1.5/bin/bundle
# Excludes the production group from installing- bundler: state=present exclude_groups=production
# Only install gems from the default and production groups- bundler: state=present deployment=yes
# Installs gems using a Gemfile in another directory- bundler: state=present gemfile=../rails_project/Gemfile
# Updates Gemfile in another directory- bundler: state=latest chdir=~/rails_project
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
188 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
bzr - Deploy software (or files) from bzr branches
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manage bzr branches to deploy files or software.
Options
Examples
# Example bzr checkout from Ansible Playbooks- bzr: name=bzr+ssh://foosball.example.org/path/to/branch dest=/srv/checkout→˓version=22
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
campfire - Send a message to Campfire
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Send a message to Campfire. Messages with newlines will result in a “Paste” message being sent.
1.6. Module Index 189
Ansible 1.2 Documentation, Release 0.01
Options
Examples
- campfire: subscription=foo token=12345 room=123 msg="Task completed."
- campfire: subscription=foo token=12345 room=123 notify=logginsmsg="Task completed ... with feeling."
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
capabilities - Manage Linux capabilities
New in version 1.6.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
This module manipulates files privileges using the Linux capabilities(7) system.
Options
Examples
# Set cap_sys_chroot+ep on /foo- capabilities: path=/foo capability=cap_sys_chroot+ep state=present
# Remove cap_net_bind_service from /bar- capabilities: path=/bar capability=cap_net_bind_service state=absent
Notes
190 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: The capabilities system will automatically transform operators and flags into the effective set, so (for example,cap_foo=ep will probably become cap_foo+ep). This module does not attempt to determine the final operator andflags to compare, so you will want to ensure that your capabilities argument matches the final capabilities.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
circonus_annotation - create an annotation in circonus
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Create an annotation event with a given category, title and description. Optionally start, end or durations can beprovided
Requirements
• urllib3
• requests
• time
Options
Examples
# Create a simple annotation event with a source, defaults to start and end→˓time of now- circonus_annotation:
api_key: XXXXXXXXXXXXXXXXXtitle: 'App Config Change'description: 'This is a detailed description of the config change'category: 'This category groups like annotations'
1.6. Module Index 191
Ansible 1.2 Documentation, Release 0.01
# Create an annotation with a duration of 5 minutes and a default start time→˓of now- circonus_annotation:
api_key: XXXXXXXXXXXXXXXXXtitle: 'App Config Change'description: 'This is a detailed description of the config change'category: 'This category groups like annotations'duration: 300
# Create an annotation with a start_time and end_time- circonus_annotation:
api_key: XXXXXXXXXXXXXXXXXtitle: 'App Config Change'description: 'This is a detailed description of the config change'category: 'This category groups like annotations'start_time: 1395940006end_time: 1395954407
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
clc_aa_policy - Create or Delete Anti Affinity Policies at CenturyLink Cloud.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
An Ansible module to Create or Delete Anti Affinity Policies at CenturyLink Cloud.
Requirements
• python = 2.7
• requests >= 2.5.0
• clc-sdk
192 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Note - You must set the CLC_V2_API_USERNAME And CLC_V2_API_PASSWD→˓Environment variables before running these examples
---- name: Create AA Policyhosts: localhostgather_facts: Falseconnection: localtasks:
- name: Create an Anti Affinity Policyclc_aa_policy:name: 'Hammer Time'location: 'UK3'state: present
register: policy
- name: debugdebug: var=policy
---- name: Delete AA Policyhosts: localhostgather_facts: Falseconnection: localtasks:
- name: Delete an Anti Affinity Policyclc_aa_policy:name: 'Hammer Time'location: 'UK3'state: absent
register: policy
- name: debugdebug: var=policy
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: To use this module, it is required to set the below environment variables which enables access to the CenturylinkCloud - CLC_V2_API_USERNAME, the account login id for the centurylink cloud - CLC_V2_API_PASSWORD,the account password for the centurylink cloud
Note: Alternatively, the module accepts the API token and account alias. The API token canbe generated using the CLC account login and password via the HTTP api call @ https://api.ctl.io/v2/
1.6. Module Index 193
Ansible 1.2 Documentation, Release 0.01
authentication/login - CLC_V2_API_TOKEN, the API token generated from https://api.ctl.io/v2/authentication/login- CLC_ACCT_ALIAS, the account alias associated with the centurylink cloud
Note: Users can set CLC_V2_API_URL to specify an endpoint for pointing to a different CLC environment.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
clc_alert_policy - Create or Delete Alert Policies at CenturyLink Cloud.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
An Ansible module to Create or Delete Alert Policies at CenturyLink Cloud.
Requirements
• python = 2.7
• requests >= 2.5.0
• clc-sdk
Options
Examples
194 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# Note - You must set the CLC_V2_API_USERNAME And CLC_V2_API_PASSWD→˓Environment variables before running these examples
---- name: Create Alert Policy Examplehosts: localhostgather_facts: Falseconnection: localtasks:
- name: Create an Alert Policy for disk above 80% for 5 minutesclc_alert_policy:alias: wfadname: 'alert for disk > 80%'alert_recipients:
- [email protected] [email protected]
metric: 'disk'duration: '00:05:00'threshold: 80state: present
register: policy
- name: debugdebug: var=policy
---- name: Delete Alert Policy Examplehosts: localhostgather_facts: Falseconnection: localtasks:
- name: Delete an Alert Policyclc_alert_policy:alias: wfadname: 'alert for disk > 80%'state: absent
register: policy
- name: debugdebug: var=policy
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: To use this module, it is required to set the below environment variables which enables access to the CenturylinkCloud - CLC_V2_API_USERNAME, the account login id for the centurylink cloud - CLC_V2_API_PASSWORD,the account password for the centurylink cloud
Note: Alternatively, the module accepts the API token and account alias. The API token can
1.6. Module Index 195
Ansible 1.2 Documentation, Release 0.01
be generated using the CLC account login and password via the HTTP api call @ https://api.ctl.io/v2/authentication/login - CLC_V2_API_TOKEN, the API token generated from https://api.ctl.io/v2/authentication/login- CLC_ACCT_ALIAS, the account alias associated with the centurylink cloud
Note: Users can set CLC_V2_API_URL to specify an endpoint for pointing to a different CLC environment.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
clc_blueprint_package - deploys a blue print package on a set of servers in CenturyLink Cloud.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
An Ansible module to deploy blue print package on a set of servers in CenturyLink Cloud.
Requirements
• python = 2.7
• requests >= 2.5.0
• clc-sdk
Options
Examples
196 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# Note - You must set the CLC_V2_API_USERNAME And CLC_V2_API_PASSWD→˓Environment variables before running these examples
- name: Deploy packageclc_blueprint_package:server_ids:
- UC1TEST-SERVER1- UC1TEST-SERVER2
package_id: 77abb844-579d-478d-3955-c69ab4a7ba1apackage_params: {}
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: To use this module, it is required to set the below environment variables which enables access to the CenturylinkCloud - CLC_V2_API_USERNAME, the account login id for the centurylink cloud - CLC_V2_API_PASSWORD,the account password for the centurylink cloud
Note: Alternatively, the module accepts the API token and account alias. The API token canbe generated using the CLC account login and password via the HTTP api call @ https://api.ctl.io/v2/authentication/login - CLC_V2_API_TOKEN, the API token generated from https://api.ctl.io/v2/authentication/login- CLC_ACCT_ALIAS, the account alias associated with the centurylink cloud
Note: Users can set CLC_V2_API_URL to specify an endpoint for pointing to a different CLC environment.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
clc_firewall_policy - Create/delete/update firewall policies
New in version 2.0.
• Synopsis
• Requirements
• Options
1.6. Module Index 197
Ansible 1.2 Documentation, Release 0.01
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Create or delete or update firewall polices on Centurylink Cloud
Requirements
• python = 2.7
• requests >= 2.5.0
• clc-sdk
Options
Examples
---- name: Create Firewall Policyhosts: localhostgather_facts: Falseconnection: localtasks:
- name: Create / Verify an Firewall Policy at CenturyLink Cloudclc_firewall:source_account_alias: WFADlocation: VA1state: presentsource: 10.128.216.0/24destination: 10.128.216.0/24ports: Anydestination_account_alias: WFAD
---- name: Delete Firewall Policyhosts: localhostgather_facts: Falseconnection: localtasks:
- name: Delete an Firewall Policy at CenturyLink Cloudclc_firewall:source_account_alias: WFADlocation: VA1state: absentfirewall_policy_id: 'c62105233d7a4231bd2e91b9c791e43e1'
198 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: To use this module, it is required to set the below environment variables which enables access to the CenturylinkCloud - CLC_V2_API_USERNAME, the account login id for the centurylink cloud - CLC_V2_API_PASSWORD,the account password for the centurylink cloud
Note: Alternatively, the module accepts the API token and account alias. The API token canbe generated using the CLC account login and password via the HTTP api call @ https://api.ctl.io/v2/authentication/login - CLC_V2_API_TOKEN, the API token generated from https://api.ctl.io/v2/authentication/login- CLC_ACCT_ALIAS, the account alias associated with the centurylink cloud
Note: Users can set CLC_V2_API_URL to specify an endpoint for pointing to a different CLC environment.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
clc_group - Create/delete Server Groups at Centurylink Cloud
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Create or delete Server Groups at Centurylink Centurylink Cloud
1.6. Module Index 199
Ansible 1.2 Documentation, Release 0.01
Requirements
• python = 2.7
• requests >= 2.5.0
• clc-sdk
Options
Examples
# Create a Server Group
---- name: Create Server Grouphosts: localhostgather_facts: Falseconnection: localtasks:
- name: Create / Verify a Server Group at CenturyLink Cloudclc_group:name: 'My Cool Server Group'parent: 'Default Group'state: present
register: clc
- name: debugdebug: var=clc
# Delete a Server Group
---- name: Delete Server Grouphosts: localhostgather_facts: Falseconnection: localtasks:
- name: Delete / Verify Absent a Server Group at CenturyLink Cloudclc_group:name: 'My Cool Server Group'parent: 'Default Group'state: absent
register: clc
- name: debugdebug: var=clc
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
200 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: To use this module, it is required to set the below environment variables which enables access to the CenturylinkCloud - CLC_V2_API_USERNAME, the account login id for the centurylink cloud - CLC_V2_API_PASSWORD,the account password for the centurylink cloud
Note: Alternatively, the module accepts the API token and account alias. The API token canbe generated using the CLC account login and password via the HTTP api call @ https://api.ctl.io/v2/authentication/login - CLC_V2_API_TOKEN, the API token generated from https://api.ctl.io/v2/authentication/login- CLC_ACCT_ALIAS, the account alias associated with the centurylink cloud
Note: Users can set CLC_V2_API_URL to specify an endpoint for pointing to a different CLC environment.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
clc_loadbalancer - Create, Delete shared loadbalancers in CenturyLink Cloud.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
An Ansible module to Create, Delete shared loadbalancers in CenturyLink Cloud.
Requirements
• python = 2.7
• requests >= 2.5.0
• clc-sdk
1.6. Module Index 201
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Note - You must set the CLC_V2_API_USERNAME And CLC_V2_API_PASSWD→˓Environment variables before running these examples- name: Create Loadbalancerhosts: localhostconnection: localtasks:
- name: Actually Create thingsclc_loadbalancer:name: testdescription: testalias: TESTlocation: WA1port: 443nodes:- { 'ipAddress': '10.11.22.123', 'privatePort': 80 }
state: present
- name: Add node to an existing loadbalancer poolhosts: localhostconnection: localtasks:
- name: Actually Create thingsclc_loadbalancer:name: testdescription: testalias: TESTlocation: WA1port: 443nodes:- { 'ipAddress': '10.11.22.234', 'privatePort': 80 }
state: nodes_present
- name: Remove node from an existing loadbalancer poolhosts: localhostconnection: localtasks:
- name: Actually Create thingsclc_loadbalancer:name: testdescription: testalias: TESTlocation: WA1port: 443nodes:- { 'ipAddress': '10.11.22.234', 'privatePort': 80 }
state: nodes_absent
- name: Delete LoadbalancerPoolhosts: localhostconnection: localtasks:
- name: Actually Delete thingsclc_loadbalancer:
202 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
name: testdescription: testalias: TESTlocation: WA1port: 443nodes:- { 'ipAddress': '10.11.22.123', 'privatePort': 80 }
state: port_absent
- name: Delete Loadbalancerhosts: localhostconnection: localtasks:
- name: Actually Delete thingsclc_loadbalancer:name: testdescription: testalias: TESTlocation: WA1port: 443nodes:- { 'ipAddress': '10.11.22.123', 'privatePort': 80 }
state: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: To use this module, it is required to set the below environment variables which enables access to the CenturylinkCloud - CLC_V2_API_USERNAME, the account login id for the centurylink cloud - CLC_V2_API_PASSWORD,the account password for the centurylink cloud
Note: Alternatively, the module accepts the API token and account alias. The API token canbe generated using the CLC account login and password via the HTTP api call @ https://api.ctl.io/v2/authentication/login - CLC_V2_API_TOKEN, the API token generated from https://api.ctl.io/v2/authentication/login- CLC_ACCT_ALIAS, the account alias associated with the centurylink cloud
Note: Users can set CLC_V2_API_URL to specify an endpoint for pointing to a different CLC environment.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 203
Ansible 1.2 Documentation, Release 0.01
clc_modify_server - modify servers in CenturyLink Cloud.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
An Ansible module to modify servers in CenturyLink Cloud.
Requirements
• python = 2.7
• requests >= 2.5.0
• clc-sdk
Options
Examples
# Note - You must set the CLC_V2_API_USERNAME And CLC_V2_API_PASSWD→˓Environment variables before running these examples
- name: set the cpu count to 4 on a serverclc_modify_server:
server_ids:- UC1TESTSVR01- UC1TESTSVR02
cpu: 4state: present
- name: set the memory to 8GB on a serverclc_modify_server:
server_ids:- UC1TESTSVR01- UC1TESTSVR02
memory: 8state: present
- name: set the anti affinity policy on a server
204 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
clc_modify_server:server_ids:
- UC1TESTSVR01- UC1TESTSVR02
anti_affinity_policy_name: 'aa_policy'state: present
- name: remove the anti affinity policy on a serverclc_modify_server:
server_ids:- UC1TESTSVR01- UC1TESTSVR02
anti_affinity_policy_name: 'aa_policy'state: absent
- name: add the alert policy on a serverclc_modify_server:
server_ids:- UC1TESTSVR01- UC1TESTSVR02
alert_policy_name: 'alert_policy'state: present
- name: remove the alert policy on a serverclc_modify_server:
server_ids:- UC1TESTSVR01- UC1TESTSVR02
alert_policy_name: 'alert_policy'state: absent
- name: set the memory to 16GB and cpu to 8 core on a lust if serversclc_modify_server:
server_ids:- UC1TESTSVR01- UC1TESTSVR02
cpu: 8memory: 16state: present
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: To use this module, it is required to set the below environment variables which enables access to the CenturylinkCloud - CLC_V2_API_USERNAME, the account login id for the centurylink cloud - CLC_V2_API_PASSWORD,the account password for the centurylink cloud
Note: Alternatively, the module accepts the API token and account alias. The API token canbe generated using the CLC account login and password via the HTTP api call @ https://api.ctl.io/v2/
1.6. Module Index 205
Ansible 1.2 Documentation, Release 0.01
authentication/login - CLC_V2_API_TOKEN, the API token generated from https://api.ctl.io/v2/authentication/login- CLC_ACCT_ALIAS, the account alias associated with the centurylink cloud
Note: Users can set CLC_V2_API_URL to specify an endpoint for pointing to a different CLC environment.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
clc_publicip - Add and Delete public ips on servers in CenturyLink Cloud.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
An Ansible module to add or delete public ip addresses on an existing server or servers in CenturyLink Cloud.
Requirements
• python = 2.7
• requests >= 2.5.0
• clc-sdk
Options
Examples
206 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# Note - You must set the CLC_V2_API_USERNAME And CLC_V2_API_PASSWD→˓Environment variables before running these examples
- name: Add Public IP to Serverhosts: localhostgather_facts: Falseconnection: localtasks:
- name: Create Public IP For Serversclc_publicip:protocol: 'TCP'ports:
- 80server_ids:
- UC1TEST-SVR01- UC1TEST-SVR02
state: presentregister: clc
- name: debugdebug: var=clc
- name: Delete Public IP from Serverhosts: localhostgather_facts: Falseconnection: localtasks:
- name: Create Public IP For Serversclc_publicip:server_ids:
- UC1TEST-SVR01- UC1TEST-SVR02
state: absentregister: clc
- name: debugdebug: var=clc
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: To use this module, it is required to set the below environment variables which enables access to the CenturylinkCloud - CLC_V2_API_USERNAME, the account login id for the centurylink cloud - CLC_V2_API_PASSWORD,the account password for the centurylink cloud
Note: Alternatively, the module accepts the API token and account alias. The API token canbe generated using the CLC account login and password via the HTTP api call @ https://api.ctl.io/v2/authentication/login - CLC_V2_API_TOKEN, the API token generated from https://api.ctl.io/v2/authentication/login
1.6. Module Index 207
Ansible 1.2 Documentation, Release 0.01
- CLC_ACCT_ALIAS, the account alias associated with the centurylink cloud
Note: Users can set CLC_V2_API_URL to specify an endpoint for pointing to a different CLC environment.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
clc_server - Create, Delete, Start and Stop servers in CenturyLink Cloud.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
An Ansible module to Create, Delete, Start and Stop servers in CenturyLink Cloud.
Requirements
• python = 2.7
• requests >= 2.5.0
• clc-sdk
Options
Examples
# Note - You must set the CLC_V2_API_USERNAME And CLC_V2_API_PASSWD→˓Environment variables before running these examples
- name: Provision a single Ubuntu Server
208 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
clc_server:name: testtemplate: ubuntu-14-64count: 1group: 'Default Group'state: present
- name: Ensure 'Default Group' has exactly 5 serversclc_server:
name: testtemplate: ubuntu-14-64exact_count: 5count_group: 'Default Group'group: 'Default Group'
- name: Stop a Serverclc_server:
server_ids: ['UC1ACCT-TEST01']state: stopped
- name: Start a Serverclc_server:
server_ids: ['UC1ACCT-TEST01']state: started
- name: Delete a Serverclc_server:
server_ids: ['UC1ACCT-TEST01']state: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: To use this module, it is required to set the below environment variables which enables access to the CenturylinkCloud - CLC_V2_API_USERNAME, the account login id for the centurylink cloud - CLC_V2_API_PASSWORD,the account password for the centurylink cloud
Note: Alternatively, the module accepts the API token and account alias. The API token canbe generated using the CLC account login and password via the HTTP api call @ https://api.ctl.io/v2/authentication/login - CLC_V2_API_TOKEN, the API token generated from https://api.ctl.io/v2/authentication/login- CLC_ACCT_ALIAS, the account alias associated with the centurylink cloud
Note: Users can set CLC_V2_API_URL to specify an endpoint for pointing to a different CLC environment.
1.6. Module Index 209
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
clc_server_snapshot - Create, Delete and Restore server snapshots in CenturyLink Cloud.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
An Ansible module to Create, Delete and Restore server snapshots in CenturyLink Cloud.
Requirements
• python = 2.7
• requests >= 2.5.0
• clc-sdk
Options
Examples
# Note - You must set the CLC_V2_API_USERNAME And CLC_V2_API_PASSWD→˓Environment variables before running these examples
- name: Create server snapshotclc_server_snapshot:
server_ids:- UC1TEST-SVR01- UC1TEST-SVR02
expiration_days: 10wait: Truestate: present
210 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- name: Restore server snapshotclc_server_snapshot:
server_ids:- UC1TEST-SVR01- UC1TEST-SVR02
wait: Truestate: restore
- name: Delete server snapshotclc_server_snapshot:
server_ids:- UC1TEST-SVR01- UC1TEST-SVR02
wait: Truestate: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: To use this module, it is required to set the below environment variables which enables access to the CenturylinkCloud - CLC_V2_API_USERNAME, the account login id for the centurylink cloud - CLC_V2_API_PASSWORD,the account password for the centurylink cloud
Note: Alternatively, the module accepts the API token and account alias. The API token canbe generated using the CLC account login and password via the HTTP api call @ https://api.ctl.io/v2/authentication/login - CLC_V2_API_TOKEN, the API token generated from https://api.ctl.io/v2/authentication/login- CLC_ACCT_ALIAS, the account alias associated with the centurylink cloud
Note: Users can set CLC_V2_API_URL to specify an endpoint for pointing to a different CLC environment.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cloudformation - Create or delete an AWS CloudFormation stack
• Synopsis
1.6. Module Index 211
Ansible 1.2 Documentation, Release 0.01
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Launches an AWS CloudFormation stack and waits for it complete.
Requirements
• python >= 2.6
• boto
Options
Examples
# Basic task example- name: launch ansible cloudformation examplecloudformation:
stack_name: "ansible-cloudformation"state: "present"region: "us-east-1"disable_rollback: truetemplate: "files/cloudformation-example.json"template_parameters:
KeyName: "jmartin"DiskType: "ephemeral"InstanceType: "m1.small"ClusterSize: 3
tags:Stack: "ansible-cloudformation"
# Basic role example- name: launch ansible cloudformation examplecloudformation:
stack_name: "ansible-cloudformation"state: "present"region: "us-east-1"disable_rollback: truetemplate: "roles/cloudformation/files/cloudformation-example.json"template_parameters:KeyName: "jmartin"DiskType: "ephemeral"InstanceType: "m1.small"ClusterSize: 3
tags:
212 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Stack: "ansible-cloudformation"
# Removal example- name: tear down old deploymentcloudformation:
stack_name: "ansible-cloudformation-old"state: "absent"
# Use a template from a URL- name: launch ansible cloudformation examplecloudformation:
stack_name="ansible-cloudformation" state=presentregion=us-east-1 disable_rollback=truetemplate_url=https://s3.amazonaws.com/my-bucket/cloudformation.template
args:template_parameters:
KeyName: jmartinDiskType: ephemeralInstanceType: m1.smallClusterSize: 3
tags:Stack: ansible-cloudformation
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cloudtrail - manage CloudTrail creation and deletion
New in version 2.0.
1.6. Module Index 213
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Creates or deletes CloudTrail configuration. Ensures logging is also enabled.
Requirements
• boto
• boto >= 2.21
• python >= 2.6
Options
Examples
- name: enable cloudtraillocal_action: cloudtrail
state=enabled name=main s3_bucket_name=ourbuckets3_key_prefix=cloudtrail region=us-east-1
- name: enable cloudtrail with different configurationlocal_action: cloudtrail
state=enabled name=main s3_bucket_name=ourbucket2s3_key_prefix='' region=us-east-1
- name: remove cloudtraillocal_action: cloudtrail state=disabled name=main region=us-east-1
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
214 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
command - Executes a command on a remote node
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
The command module takes the command name followed by a list of space-delimited arguments. The given commandwill be executed on all selected nodes. It will not be processed through the shell, so variables like $HOME andoperations like "<", ">", "|", and "&" will not work (use the shell module if you need these features).
Options
Examples
# Example from Ansible Playbooks.- command: /sbin/shutdown -t now
# Run the command if the specified file does not exist.- command: /usr/bin/make_database.sh arg1 arg2 creates=/path/to/database
# You can also use the 'args' form to provide the options. This command# will change the working directory to somedir/ and will only run when# /path/to/database doesn't exist.- command: /usr/bin/make_database.sh arg1 arg2args:
1.6. Module Index 215
Ansible 1.2 Documentation, Release 0.01
chdir: somedir/creates: /path/to/database
Notes
Note: If you want to run a command through the shell (say you are using <, >, |, etc), you actually want the shellmodule instead. The command module is much more secure as it’s not affected by the user’s environment.
Note: creates, removes, and chdir can be specified after the command. For instance, if you only want to runa command if a certain file does not exist, use this.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
composer - Dependency Manager for PHP
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Composer is a tool for dependency management in PHP. It allows you to declare the dependent libraries your projectneeds and it will install them in your project for you
Requirements
• php
• composer installed in bin path (recommended /usr/local/bin)
216 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Downloads and installs all the libs and dependencies outlined in the /path/→˓to/project/composer.lock- composer: command=install working_dir=/path/to/project
- composer:command: "require"arguments: "my/package"working_dir: "/path/to/project"
# Clone project and install with all dependencies- composer:
command: "create-project"arguments: "package/package /path/to/project ~1.0"working_dir: "/path/to/project"prefer_dist: "yes"
Notes
Note: Default options that are always appended in each execution are –no-ansi, –no-interaction and –no-progress ifavailable.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
consul - Add, modify & delete services within a consul cluster.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
1.6. Module Index 217
Ansible 1.2 Documentation, Release 0.01
Synopsis
Registers services and checks for an agent with a consul cluster. A service is some process running on the agent nodethat should be advertised by consul’s discovery mechanism. It may optionally supply a check definition, a periodicservice test to notify the consul cluster of service’s health. Checks may also be registered per node e.g. disk usage,or cpu usage and notify the health of the entire node to the cluster. Service level checks do not require a check nameor id as these are derived by Consul from the Service name and id respectively by appending ‘service:’ Node levelchecks require a check_name and optionally a check_id. Currently, there is no complete way to retrieve the script,interval or ttl metadata for a registered check. Without this metadata it is not possible to tell if the data supplied withansible represents a change to a check. As a result this does not attempt to determine changes and will always reporta changed occurred. An api method is planned to supply this metadata so at that stage change management will beadded. See http://consul.io for more details.
Requirements
• python >= 2.6
• python-consul
• requests
Options
Examples
- name: register nginx service with the local consul agentconsul:
service_name: nginxservice_port: 80
- name: register nginx service with curl checkconsul:
service_name: nginxservice_port: 80script: "curl http://localhost"interval: 60s
- name: register nginx with an http checkconsul:
name: nginxservice_port: 80interval: 60shttp: /status
- name: register nginx with some service tagsconsul:
service_name: nginxservice_port: 80tags:- prod- webservers
- name: remove nginx serviceconsul:
218 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
service_name: nginxstate: absent
- name: create a node level check to test disk usageconsul:
check_name: Disk usagecheck_id: disk_usagescript: "/opt/disk_usage.py"interval: 5m
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
consul_acl - manipulate consul acl keys and rules
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
allows the addition, modification and deletion of ACL keys and associated rules in a consul cluster via the agent. Formore details on using and configuring ACLs, see https://www.consul.io/docs/internals/acl.html.
Requirements
• python >= 2.6
• python-consul
• pyhcl
• requests
Options
1.6. Module Index 219
Ansible 1.2 Documentation, Release 0.01
Examples
- name: create an acl token with rulesconsul_acl:
mgmt_token: 'some_management_acl'host: 'consul1.mycluster.io'name: 'Foo access'rules:
- key: 'foo'policy: read
- key: 'private/foo'policy: deny
- name: create an acl with specific token with both key and serivce rulesconsul_acl:
mgmt_token: 'some_management_acl'name: 'Foo access'token: 'some_client_token'rules:
- key: 'foo'policy: read
- service: ''policy: write
- service: 'secret-'policy: deny
- name: remove a tokenconsul_acl:
mgmt_token: 'some_management_acl'host: 'consul1.mycluster.io'token: '172bd5c8-9fe9-11e4-b1b0-3c15c2c9fd5e'state: absent
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
consul_kv - Manipulate entries in the key/value store of a consul cluster.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
220 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
Allows the addition, modification and deletion of key/value entries in a consul cluster via the agent. The entire contentsof the record, including the indices, flags and session are returned as ‘value’. If the key represents a prefix then Notethat when a value is removed, the existing value if any is returned as part of the results. See http://www.consul.io/docs/agent/http.html#kv for more details.
Requirements
• python >= 2.6
• python-consul
• requests
Options
Examples
- name: add or update the value associated with a key in the key/value storeconsul_kv:
key: somekeyvalue: somevalue
- name: remove a key from the storeconsul_kv:
key: somekeystate: absent
- name: add a node to an arbitrary group via consul inventory (see consul.→˓ini)consul_kv:
key: ansible/groups/dc1/somenodevalue: 'top_secret'
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
consul_session - manipulate consul sessions
New in version 2.0.
• Synopsis
• Requirements
• Options
1.6. Module Index 221
Ansible 1.2 Documentation, Release 0.01
• Examples
• This is an Extras Module
Synopsis
allows the addition, modification and deletion of sessions in a consul cluster. These sessions can then be used inconjunction with key value pairs to implement distributed locks. In depth documentation for working with sessionscan be found here http://www.consul.io/docs/internals/sessions.html
Requirements
• python >= 2.6
• python-consul
• requests
Options
Examples
- name: register basic session with consulconsul_session:
name: session1
- name: register a session with an existing checkconsul_session:
name: session_with_checkchecks:- existing_check_name
- name: register a session with lock_delayconsul_session:
name: session_with_delaydelay: 20s
- name: retrieve info about session by idconsul_session: id=session_id state=info
- name: retrieve active sessionsconsul_session: state=list
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
222 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
copy - Copies files to remote locations.
• Synopsis
• Options
• Examples
• Return Values
• Notes
• This is a Core Module
Synopsis
The copy module copies a file on the local box to remote locations. Use the fetch module to copy files from remotelocations to the local box. If you need variable interpolation in copied files, use the template module.
Options
Examples
# Example from Ansible Playbooks- copy: src=/srv/myfiles/foo.conf dest=/etc/foo.conf owner=foo group=foo→˓mode=0644
# The same example as above, but using a symbolic mode equivalent to 0644- copy: src=/srv/myfiles/foo.conf dest=/etc/foo.conf owner=foo group=foo→˓mode="u=rw,g=r,o=r"
# Another symbolic mode example, adding some permissions and removing others- copy: src=/srv/myfiles/foo.conf dest=/etc/foo.conf owner=foo group=foo→˓mode="u+rw,g-wx,o-rwx"
# Copy a new "ntp.conf file into place, backing up the original if it→˓differs from the copied version- copy: src=/mine/ntp.conf dest=/etc/ntp.conf owner=root group=root mode=644→˓backup=yes
# Copy a new "sudoers" file into place, after passing validation with visudo- copy: src=/mine/sudoers dest=/etc/sudoers validate='visudo -cf %s'
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
1.6. Module Index 223
Ansible 1.2 Documentation, Release 0.01
Note: The “copy” module recursively copy facility does not scale to lots (>hundreds) of files. For alternative, seesynchronize module, which is a wrapper around rsync.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cpanm - Manages Perl library dependencies.
New in version 1.6.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manage Perl library dependencies.
Options
Examples
# install Dancer perl package- cpanm: name=Dancer
# install version 0.99_05 of the Plack perl package- cpanm: name=MIYAGAWA/Plack-0.99_05.tar.gz
# install Dancer into the specified locallib- cpanm: name=Dancer locallib=/srv/webapps/my_app/extlib
# install perl dependencies from local directory- cpanm: from_path=/srv/webapps/my_app/src/
# install Dancer perl package without running the unit tests in indicated→˓locallib- cpanm: name=Dancer notest=True locallib=/srv/webapps/my_app/extlib
# install Dancer perl package from a specific mirror- cpanm: name=Dancer mirror=http://cpan.cpantesters.org/
224 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# install Dancer perl package into the system root path- cpanm: name=Dancer system_lib=yes
Notes
Note: Please note that http://search.cpan.org/dist/App-cpanminus/bin/cpanm, cpanm must be installed on the remotehost.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cron - Manage cron.d and crontab entries.
• Synopsis
• Requirements
• Options
• Examples
• This is a Core Module
Synopsis
Use this module to manage crontab entries. This module allows you to create named crontab entries, update, ordelete them. The module includes one line with the description of the crontab entry "#Ansible: <name>"corresponding to the “name” passed to the module, which is used by future ansible/module calls to find/check thestate. The “name” parameter should be unique, and changing the “name” value will result in a new cron task beingcreated (or a different one being removed)
Requirements
• cron
Options
1.6. Module Index 225
Ansible 1.2 Documentation, Release 0.01
Examples
# Ensure a job that runs at 2 and 5 exists.# Creates an entry like "0 5,2 * * ls -alh > /dev/null"- cron: name="check dirs" minute="0" hour="5,2" job="ls -alh > /dev/null"
# Ensure an old job is no longer present. Removes any job that is prefixed# by "#Ansible: an old job" from the crontab- cron: name="an old job" state=absent
# Creates an entry like "@reboot /some/job.sh"- cron: name="a job for reboot" special_time=reboot job="/some/job.sh"
# Creates a cron file under /etc/cron.d- cron: name="yum autoupdate" weekday="2" minute=0 hour=12
user="root" job="YUMINTERACTIVE=0 /usr/sbin/yum-autoupdate"cron_file=ansible_yum-autoupdate
# Removes a cron file from under /etc/cron.d- cron: name="yum autoupdate" cron_file=ansible_yum-autoupdate state=absent
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cronvar - Manage variables in crontabs
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Use this module to manage crontab variables. This module allows you to create, update, or delete cron variabledefinitions.
Requirements
• cron
226 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Ensure a variable exists.# Creates an entry like "[email protected]"- cronvar: name="EMAIL" value="[email protected]"
# Make sure a variable is gone. This will remove any variable named# "LEGACY"- cronvar: name="LEGACY" state=absent
# Adds a variable to a file under /etc/cron.d- cronvar: name="LOGFILE" value="/var/log/yum-autoupdate.log"
user="root" cron_file=ansible_yum-autoupdate
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
crypttab - Encrypted Linux block devices
New in version 1.9.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Control Linux encrypted block devices that are set up during system boot in /etc/crypttab.
Options
Examples
- name: Set the options explicitly a deivce which must already existcrypttab: name=luks-home state=present opts=discard,cipher=aes-cbc-
→˓essiv:sha256
- name: Add the 'discard' option to any existing options for all devicescrypttab: name={{ item.device }} state=opts_present opts=discard
1.6. Module Index 227
Ansible 1.2 Documentation, Release 0.01
with_items: ansible_mountswhen: '/dev/mapper/luks-' in {{ item.device }}
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_account - Manages accounts on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Create, disable, lock, enable and remove accounts.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# create an account in domain 'CUSTOMERS'local_action:module: cs_accountname: customer_xyusername: customer_xypassword: S3Cur3last_name: Doefirst_name: John
228 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
email: [email protected]: CUSTOMERS
# Lock an existing account in domain 'CUSTOMERS'local_action:module: cs_accountname: customer_xydomain: CUSTOMERSstate: locked
# Disable an existing account in domain 'CUSTOMERS'local_action:module: cs_accountname: customer_xydomain: CUSTOMERSstate: disabled
# Enable an existing account in domain 'CUSTOMERS'local_action:module: cs_accountname: customer_xydomain: CUSTOMERSstate: enabled
# Remove an account in domain 'CUSTOMERS'local_action:module: cs_accountname: customer_xydomain: CUSTOMERSstate: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections incloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
1.6. Module Index 229
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_affinitygroup - Manages affinity groups on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Create and remove affinity groups.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# Create a affinity group- local_action:
module: cs_affinitygroupname: haproxyaffinty_type: host anti-affinity
# Remove a affinity group- local_action:
module: cs_affinitygroupname: haproxystate: absent
230 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections incloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_domain - Manages domains on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Create, update and remove domains.
1.6. Module Index 231
Ansible 1.2 Documentation, Release 0.01
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# Create a domainlocal_action:module: cs_domainpath: ROOT/customersnetwork_domain: customers.example.com
# Create another subdomainlocal_action:module: cs_domainpath: ROOT/customers/xynetwork_domain: xy.customers.example.com
# Remove a domainlocal_action:module: cs_domainpath: ROOT/customers/xystate: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections incloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
232 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_facts - Gather facts on instances of Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• This is an Extras Module
Synopsis
This module fetches data from the metadata API in CloudStack. The module must be called from within the instanceitself.
Requirements
• yaml
Options
Examples
# Gather all facts on instances- name: Gather cloudstack factscs_facts:
# Gather specific fact on instances- name: Gather cloudstack factscs_facts: filter=cloudstack_instance_id
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
1.6. Module Index 233
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_firewall - Manages firewall rules on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Creates and removes firewall rules.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# Allow inbound port 80/tcp from 1.2.3.4 to 4.3.2.1- local_action:
module: cs_firewallip_address: 4.3.2.1port: 80cidr: 1.2.3.4/32
# Allow inbound tcp/udp port 53 to 4.3.2.1- local_action:
module: cs_firewallip_address: 4.3.2.1port: 53protocol: '{{ item }}'
234 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
with_items:- tcp- udp
# Ensure firewall rule is removed- local_action:
module: cs_firewallip_address: 4.3.2.1start_port: 8000end_port: 8888cidr: 17.0.0.0/8state: absent
# Allow all outbound traffic- local_action:
module: cs_firewallnetwork: my_networktype: egressprotocol: all
# Allow only HTTP outbound traffic for an IP- local_action:
module: cs_firewallnetwork: my_networktype: egressport: 80cidr: 10.101.1.20
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections incloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
1.6. Module Index 235
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_instance - Manages instances and virtual machines on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Deploy, start, update, scale, restart, restore, stop and destroy instances.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# Create a instance from an ISO# NOTE: Names of offerings and ISOs depending on the CloudStack→˓configuration.- local_action:
module: cs_instancename: web-vm-1iso: Linux Debian 7 64-bithypervisor: VMwareproject: Integrationzone: ch-zrh-ix-01service_offering: 1cpu_1gbdisk_offering: PerfPlus Storagedisk_size: 20networks:
- Server Integration- Sync Integration- Storage Integration
236 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# For changing a running instance, use the 'force' parameter- local_action:
module: cs_instancename: web-vm-1display_name: web-vm-01.example.comiso: Linux Debian 7 64-bitservice_offering: 2cpu_2gbforce: yes
# Create or update a instance on Exoscale's public cloud using display_name.# Note: user_data can be used to kickstart the instance using cloud-init→˓yaml config.- local_action:
module: cs_instancedisplay_name: web-vm-1template: Linux Debian 7 64-bitservice_offering: Tinyssh_key: [email protected]:
- { key: admin, value: john }- { key: foo, value: bar }
user_data: |#cloud-configpackages:- nginx
# Create an instance with multiple interfaces specifying the IP addresses- local_action:
module: cs_instancename: web-vm-1template: Linux Debian 7 64-bitservice_offering: Tinyip_to_networks:- {'network': NetworkA, 'ip': '10.1.1.1'}- {'network': NetworkB, 'ip': '192.168.1.1'}
# Ensure an instance is stopped- local_action: cs_instance name=web-vm-1 state=stopped
# Ensure an instance is running- local_action: cs_instance name=web-vm-1 state=started
# Remove an instance- local_action: cs_instance name=web-vm-1 state=absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.
1.6. Module Index 237
Ansible 1.2 Documentation, Release 0.01
CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections incloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_instancegroup - Manages instance groups on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Create and remove instance groups.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
238 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
# Create an instance group- local_action:
module: cs_instancegroupname: loadbalancers
# Remove an instance group- local_action:
module: cs_instancegroupname: loadbalancersstate: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections incloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_ip_address - Manages public IP address associations on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
1.6. Module Index 239
Ansible 1.2 Documentation, Release 0.01
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Acquires and associates a public IP to an account or project. Due to API limitations this is not an idempotent call, sobe sure to only conditionally call this when state=present
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# Associate an IP address conditonally- local_action:
module: cs_ip_addressnetwork: My Network
register: ip_addresswhen: instance.public_ip is undefined
# Disassociate an IP address- local_action:
module: cs_ip_addressip_address: 1.2.3.4state: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections in
240 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
cloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_iso - Manages ISO images on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Register and remove ISO images.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# Register an ISO if ISO name does not already exist.- local_action:
module: cs_isoname: Debian 7 64-bit
1.6. Module Index 241
Ansible 1.2 Documentation, Release 0.01
url: http://mirror.switch.ch/ftp/mirror/debian-cd/current/amd64/iso-cd/→˓debian-7.7.0-amd64-netinst.iso
os_type: Debian GNU/Linux 7(64-bit)
# Register an ISO with given name if ISO md5 checksum does not already exist.- local_action:
module: cs_isoname: Debian 7 64-biturl: http://mirror.switch.ch/ftp/mirror/debian-cd/current/amd64/iso-cd/
→˓debian-7.7.0-amd64-netinst.isoos_type: Debian GNU/Linux 7(64-bit)checksum: 0b31bccccb048d20b551f70830bb7ad0
# Remove an ISO by name- local_action:
module: cs_isoname: Debian 7 64-bitstate: absent
# Remove an ISO by checksum- local_action:
module: cs_isoname: Debian 7 64-bitchecksum: 0b31bccccb048d20b551f70830bb7ad0state: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections incloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
242 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
cs_loadbalancer_rule - Manages load balancer rules on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Add, update and remove load balancer rules.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# Create a load balancer rule- local_action:
module: cs_loadbalancer_rulename: balance_httppublic_ip: 1.2.3.4algorithm: leastconnpublic_port: 80private_port: 8080
# update algorithm of an existing load balancer rule- local_action:
module: cs_loadbalancer_rulename: balance_httppublic_ip: 1.2.3.4algorithm: roundrobinpublic_port: 80private_port: 8080
# Delete a load balancer rule- local_action:
module: cs_loadbalancer_rulename: balance_http
1.6. Module Index 243
Ansible 1.2 Documentation, Release 0.01
public_ip: 1.2.3.4state: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections incloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_loadbalancer_rule_member - Manages load balancer rule members on Apache CloudStackbased clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
244 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
Add and remove load balancer rule members.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# Add VMs to an exising load balancer- local_action:
module: cs_loadbalancer_rule_membername: balance_httpvms:- web01- web02
# Remove a VM from an existing load balancer- local_action:
module: cs_loadbalancer_rule_membername: balance_httpvms:
- web01- web02
state: absent
# Rolling upgrade of hosts- hosts: webserversserial: 1pre_tasks:
- name: Remove from load balancerlocal_action:module: cs_loadbalancer_rule_membername: balance_httpvm: "{{ ansible_hostname }}"state: absent
tasks:# Perform update
post_tasks:- name: Add to load balancer
local_action:module: cs_loadbalancer_rule_membername: balance_httpvm: "{{ ansible_hostname }}"state: present
1.6. Module Index 245
Ansible 1.2 Documentation, Release 0.01
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections incloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_network - Manages networks on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Create, update, restart and delete networks.
246 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# create a network- local_action:
module: cs_networkname: my networkzone: gva-01network_offering: DefaultIsolatedNetworkOfferingWithSourceNatServicenetwork_domain: example.com
# update a network- local_action:
module: cs_networkname: my networkdisplay_text: network of domain example.localnetwork_domain: example.local
# restart a network with clean up- local_action:
module: cs_networkname: my networkclean_up: yesstate: restared
# remove a network- local_action:
module: cs_networkname: my networkstate: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections in
1.6. Module Index 247
Ansible 1.2 Documentation, Release 0.01
cloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_portforward - Manages port forwarding rules on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Create, update and remove port forwarding rules.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# 1.2.3.4:80 -> web01:8080- local_action:
module: cs_portforwardip_address: 1.2.3.4
248 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
vm: web01public_port: 80private_port: 8080
# forward SSH and open firewall- local_action:
module: cs_portforwardip_address: '{{ public_ip }}'vm: '{{ inventory_hostname }}'public_port: '{{ ansible_ssh_port }}'private_port: 22open_firewall: true
# forward DNS traffic, but do not open firewall- local_action:
module: cs_portforwardip_address: 1.2.3.4vm: '{{ inventory_hostname }}'public_port: 53private_port: 53protocol: udp
# remove ssh port forwarding- local_action:
module: cs_portforwardip_address: 1.2.3.4public_port: 22private_port: 22state: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections incloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
1.6. Module Index 249
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_project - Manages projects on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Create, update, suspend, activate and remove projects.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# Create a project- local_action:
module: cs_projectname: web
# Rename a project- local_action:
module: cs_projectname: webdisplay_text: my web project
# Suspend an existing project- local_action:
250 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
module: cs_projectname: webstate: suspended
# Activate an existing project- local_action:
module: cs_projectname: webstate: active
# Remove a project- local_action:
module: cs_projectname: webstate: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections incloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_securitygroup - Manages security groups on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
1.6. Module Index 251
Ansible 1.2 Documentation, Release 0.01
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Create and remove security groups.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# Create a security group- local_action:
module: cs_securitygroupname: defaultdescription: default security group
# Remove a security group- local_action:
module: cs_securitygroupname: defaultstate: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections in
252 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
cloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_securitygroup_rule - Manages security group rules on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Add and remove security group rules.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
---# Allow inbound port 80/tcp from 1.2.3.4 added to security group 'default'- local_action:
module: cs_securitygroup_rule
1.6. Module Index 253
Ansible 1.2 Documentation, Release 0.01
security_group: defaultport: 80cidr: 1.2.3.4/32
# Allow tcp/udp outbound added to security group 'default'- local_action:
module: cs_securitygroup_rulesecurity_group: defaulttype: egressstart_port: 1end_port: 65535protocol: '{{ item }}'
with_items:- tcp- udp
# Allow inbound icmp from 0.0.0.0/0 added to security group 'default'- local_action:
module: cs_securitygroup_rulesecurity_group: defaultprotocol: icmpicmp_code: -1icmp_type: -1
# Remove rule inbound port 80/tcp from 0.0.0.0/0 from security group 'default→˓'- local_action:
module: cs_securitygroup_rulesecurity_group: defaultport: 80state: absent
# Allow inbound port 80/tcp from security group web added to security group→˓'default'- local_action:
module: cs_securitygroup_rulesecurity_group: defaultport: 80user_security_group: web
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections in
254 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
cloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_sshkeypair - Manages SSH keys on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Create, register and remove SSH keys. If no key was found and no public key was provided and a new SSH pri-vate/public key pair will be created and the private key will be returned.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# create a new private / public key pair:- local_action: cs_sshkeypair [email protected]: key
1.6. Module Index 255
Ansible 1.2 Documentation, Release 0.01
- debug: msg='private key is {{ key.private_key }}'
# remove a public key by its name:- local_action: cs_sshkeypair [email protected] state=absent
# register your existing local public key:- local_action: cs_sshkeypair [email protected] public_key='{{ lookup(→˓'file', '~/.ssh/id_rsa.pub') }}'
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections incloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_staticnat - Manages static NATs on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
256 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• This is an Extras Module
Synopsis
Create, update and remove static NATs.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# create a static NAT: 1.2.3.4 -> web01- local_action:
module: cs_staticnatip_address: 1.2.3.4vm: web01
# remove a static NAT- local_action:
module: cs_staticnatip_address: 1.2.3.4state: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections incloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
1.6. Module Index 257
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_template - Manages templates on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Register a template from URL, create a template from a ROOT volume of a stopped VM or its snapshot, extract anddelete templates.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# Register a systemvm template- local_action:
module: cs_templatename: systemvm-vmware-4.5url: "http://packages.shapeblue.com/systemvmtemplate/4.5/
→˓systemvm64template-4.5-vmware.ova"hypervisor: VMwareformat: OVAcross_zones: yesos_type: Debian GNU/Linux 7(64-bit)
# Create a template from a stopped virtual machine's volume
258 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- local_action:module: cs_templatename: debian-base-templatevm: debian-base-vmos_type: Debian GNU/Linux 7(64-bit)zone: tokio-ixpassword_enabled: yesis_public: yes
# Create a template from a virtual machine's root volume snapshot- local_action:
module: cs_templatename: debian-base-templatevm: debian-base-vmsnapshot: ROOT-233_2015061509114os_type: Debian GNU/Linux 7(64-bit)zone: tokio-ixpassword_enabled: yesis_public: yes
# Remove a template- local_action:
module: cs_templatename: systemvm-4.2state: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections incloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 259
Ansible 1.2 Documentation, Release 0.01
cs_user - Manages users on Apache CloudStack based clouds.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Create, update, disable, lock, enable and remove users.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# create an user in domain 'CUSTOMERS'local_action:module: cs_useraccount: developersusername: johndoepassword: S3Cur3last_name: Doefirst_name: Johnemail: [email protected]: CUSTOMERS
# Lock an existing user in domain 'CUSTOMERS'local_action:module: cs_userusername: johndoedomain: CUSTOMERSstate: locked
# Disable an existing user in domain 'CUSTOMERS'local_action:module: cs_userusername: johndoe
260 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
domain: CUSTOMERSstate: disabled
# Enable/unlock an existing user in domain 'CUSTOMERS'local_action:module: cs_userusername: johndoedomain: CUSTOMERSstate: enabled
# Remove an user in domain 'CUSTOMERS'local_action:module: cs_username: customer_xydomain: CUSTOMERSstate: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections incloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
cs_vmsnapshot - Manages VM snapshots on Apache CloudStack based clouds.
New in version 2.0.
1.6. Module Index 261
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Create, remove and revert VM from snapshots.
Requirements
• python >= 2.6
• cs >= 0.6.10
Options
Examples
# Create a VM snapshot of disk and memory before an upgrade- local_action:
module: cs_vmsnapshotname: Snapshot before upgradevm: web-01snapshot_memory: yes
# Revert a VM to a snapshot after a failed upgrade- local_action:
module: cs_vmsnapshotname: Snapshot before upgradevm: web-01state: revert
# Remove a VM snapshot after successful upgrade- local_action:
module: cs_vmsnapshotname: Snapshot before upgradevm: web-01state: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
262 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Notes
Note: Ansible uses the cs library’s configuration method if credentials are not provided by the argumentsapi_url, api_key, api_secret. Configuration is read from several locations, in the following order.- The CLOUDSTACK_ENDPOINT, CLOUDSTACK_KEY, CLOUDSTACK_SECRET and CLOUDSTACK_METHOD.CLOUDSTACK_TIMEOUT environment variables. - A CLOUDSTACK_CONFIG environment variable pointing toan .ini file, - A cloudstack.ini file in the current working directory. - A .cloudstack.ini file inthe users home directory. Optionally multiple credentials and endpoints can be specified using ini sections incloudstack.ini. Use the argument api_region to select the section name, default section is cloudstack.See https://github.com/exoscale/cs for more information.
Note: This module supports check mode.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
datadog_event - Posts events to DataDog service
New in version 1.3.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Allows to post events to DataDog (www.datadoghq.com) service. Uses http://docs.datadoghq.com/api/#events API.
Options
Examples
# Post an event with low prioritydatadog_event: title="Testing from ansible" text="Test!" priority="low"
api_key="6873258723457823548234234234"# Post an event with several tagsdatadog_event: title="Testing from ansible" text="Test!"
1.6. Module Index 263
Ansible 1.2 Documentation, Release 0.01
api_key="6873258723457823548234234234"tags=aa,bb,#host:{{ inventory_hostname }}
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
datadog_monitor - Manages Datadog monitors
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Manages monitors within Datadog Options like described on http://docs.datadoghq.com/api/
Requirements
• datadog
Options
Examples
# Create a metric monitordatadog_monitor:type: "metric alert"name: "Test monitor"state: "present"query: "datadog.agent.up".over("host:host1").last(2).count_by_status()"message: "Some message."api_key: "9775a026f1ca7d1c6c5af9d94d9595a4"app_key: "87ce4a24b5553d2e482ea8a8500e71b8ad4554ff"
# Deletes a monitordatadog_monitor:name: "Test monitor"
264 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
state: "absent"api_key: "9775a026f1ca7d1c6c5af9d94d9595a4"app_key: "87ce4a24b5553d2e482ea8a8500e71b8ad4554ff"
# Mutes a monitordatadog_monitor:name: "Test monitor"state: "mute"silenced: '{"*":None}'api_key: "9775a026f1ca7d1c6c5af9d94d9595a4"app_key: "87ce4a24b5553d2e482ea8a8500e71b8ad4554ff"
# Unmutes a monitordatadog_monitor:name: "Test monitor"state: "unmute"api_key: "9775a026f1ca7d1c6c5af9d94d9595a4"app_key: "87ce4a24b5553d2e482ea8a8500e71b8ad4554ff"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
debconf - Configure a .deb package
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Configure a .deb package using debconf-set-selections. Or just query existing selections.
Requirements
• debconf
• debconf-utils
1.6. Module Index 265
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Set default locale to fr_FR.UTF-8debconf: name=locales question='locales/default_environment_locale' value=fr_→˓FR.UTF-8 vtype='select'
# set to generate locales:debconf: name=locales question='locales/locales_to_be_generated' value='en_→˓US.UTF-8 UTF-8, fr_FR.UTF-8 UTF-8' vtype='multiselect'
# Accept oracle licensedebconf: name='oracle-java7-installer' question='shared/accepted-oracle-→˓license-v1-1' value='true' vtype='select'
# Specifying package you can register/return the list of questions and→˓current valuesdebconf: name='tzdata'
Notes
Note: This module requires the command line debconf tools.
Note: A number of questions have to be answered (depending on the package). Use ‘debconf-show <package>’ onany Debian or derivative with the package installed to see questions/settings available.
Note: Some distros will always record tasks involving the setting of passwords as changed. This is due to debconf-get-selections masking passwords.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
debug - Print statements during execution
• Synopsis
• Options
• Examples
• This is a Core Module
266 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
This module prints statements during execution and can be useful for debugging variables or expressions withoutnecessarily halting the playbook. Useful for debugging together with the ‘when:’ directive.
Options
Examples
# Example that prints the loopback address and gateway for each host- debug: msg="System {{ inventory_hostname }} has uuid {{ ansible_product_→˓uuid }}"
- debug: msg="System {{ inventory_hostname }} has gateway {{ ansible_default_→˓ipv4.gateway }}"when: ansible_default_ipv4.gateway is defined
- shell: /usr/bin/uptimeregister: result
- debug: var=result
- name: Display all variables/facts known for a hostdebug: var=hostvars[inventory_hostname]
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
deploy_helper - Manages some of the steps common in deploying projects.
New in version 2.0.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
The Deploy Helper manages some of the steps common in deploying software. It creates a folder structure, manages asymlink for the current release and cleans up old releases. Running it with the state=query or state=presentwill return the deploy_helper fact. project_path, whatever you set in the path parameter, current_path,
1.6. Module Index 267
Ansible 1.2 Documentation, Release 0.01
the path to the symlink that points to the active release, releases_path, the path to the folder to keep releasesin, shared_path, the path to the folder to keep shared resources in, unfinished_filename, the file tocheck for to recognize unfinished builds, previous_release, the release the ‘current’ symlink is pointing to,previous_release_path, the full path to the ‘current’ symlink target, new_release, either the ‘release’ pa-rameter or a generated timestamp, new_release_path, the path to the new release folder (not created by themodule).
Options
Examples
# General explanation, starting with an example folder structure for a→˓project:
root:releases:
- 20140415234508- 20140415235146- 20140416082818
shared:- sessions- uploads
current: -> releases/20140416082818
The 'releases' folder holds all the available releases. A release is a→˓complete build of the application beingdeployed. This can be a clone of a repository for example, or a sync of a→˓local folder on your filesystem.Having timestamped folders is one way of having distinct releases, but you→˓could choose your own strategy likegit tags or commit hashes.
During a deploy, a new folder should be created in the releases folder and→˓any build steps required should beperformed. Once the new build is ready, the deploy procedure is 'finalized'→˓by replacing the 'current' symlinkwith a link to this build.
The 'shared' folder holds any resource that is shared between releases.→˓Examples of this are web-serversession files, or files uploaded by users of your application. It's quite→˓common to have symlinks from a releasefolder pointing to a shared/subfolder, and creating these links would be→˓automated as part of the build steps.
The 'current' symlink points to one of the releases. Probably the latest one,→˓ unless a deploy is in progress.The web-server's root for the project will go through this symlink, so the→˓'downtime' when switching to a newrelease is reduced to the time it takes to switch the link.
To distinguish between successful builds and unfinished ones, a file can be→˓placed in the folder of the release
268 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
that is currently in progress. The existence of this file will mark it as→˓unfinished, and allow an automatedprocedure to remove it during cleanup.
# Typical usage:- name: Initialize the deploy root and gather factsdeploy_helper: path=/path/to/root
- name: Clone the project to the new release foldergit: repo=git://foosball.example.org/path/to/repo.git dest={{ deploy_
→˓helper.new_release_path }} version=v1.1.1- name: Add an unfinished file, to allow cleanup on successful finalizefile: path={{ deploy_helper.new_release_path }}/{{ deploy_helper.
→˓unfinished_filename }} state=touch- name: Perform some build steps, like running your dependency manager for→˓examplecomposer: command=install working_dir={{ deploy_helper.new_release_path }}
- name: Create some folders in the shared folderfile: path='{{ deploy_helper.shared_path }}/{{ item }}' state=directorywith_items: ['sessions', 'uploads']
- name: Add symlinks from the new release to the shared folderfile: path='{{ deploy_helper.new_release_path }}/{{ item.path }}'
src='{{ deploy_helper.shared_path }}/{{ item.src }}'state=link
with_items:- { path: "app/sessions", src: "sessions" }- { path: "web/uploads", src: "uploads" }
- name: Finalize the deploy, removing the unfinished file and switching the→˓symlinkdeploy_helper: path=/path/to/root release={{ deploy_helper.new_release }}
→˓state=finalize
# Retrieving facts before running a deploy- name: Run 'state=query' to gather facts without changing anythingdeploy_helper: path=/path/to/root state=query
# Remember to set the 'release' parameter when you actually call→˓'state=present' later- name: Initialize the deploy rootdeploy_helper: path=/path/to/root release={{ deploy_helper.new_release }}
→˓state=present
# all paths can be absolute or relative (to the 'path' parameter)- deploy_helper: path=/path/to/root
releases_path=/var/www/project/releasesshared_path=/var/www/sharedcurrent_path=/var/www/active
# Using your own naming strategy for releases (a version tag in this case):- deploy_helper: path=/path/to/root release=v1.1.1 state=present- deploy_helper: path=/path/to/root release={{ deploy_helper.new_release }}→˓state=finalize
# Using a different unfinished_filename:- deploy_helper: path=/path/to/root
unfinished_filename=README.mdrelease={{ deploy_helper.new_release }}state=finalize
1.6. Module Index 269
Ansible 1.2 Documentation, Release 0.01
# Postponing the cleanup of older builds:- deploy_helper: path=/path/to/root release={{ deploy_helper.new_release }}→˓state=finalize clean=False- deploy_helper: path=/path/to/root state=clean# Or running the cleanup ahead of the new deploy- deploy_helper: path=/path/to/root state=clean- deploy_helper: path=/path/to/root state=present
# Keeping more old releases:- deploy_helper: path=/path/to/root release={{ deploy_helper.new_release }}→˓state=finalize keep_releases=10# Or, if you use 'clean=false' on finalize:- deploy_helper: path=/path/to/root state=clean keep_releases=10
# Removing the entire project root folder- deploy_helper: path=/path/to/root state=absent
# Debugging the facts returned by the module- deploy_helper: path=/path/to/root- debug: var=deploy_helper
Notes
Note: Facts are only returned for state=query and state=present. If you use both, you should pass anyoverridden parameters to both calls, otherwise the second call will overwrite the facts of the first one.
Note: When using state=clean, the releases are ordered by creation date. You should be able to switch to a newnaming strategy without problems.
Note: Because of the default behaviour of generating the new_release fact, this module will not be idempotent unlessyou pass your own release name with release. Due to the nature of deploying software, this should not be much ofa problem.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
digital_ocean - Create/delete a droplet/SSH_key in DigitalOcean
New in version 1.3.
• Synopsis
270 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Create/delete a droplet in DigitalOcean and optionally wait for it to be ‘running’, or deploy an SSH key.
Requirements
• python >= 2.6
• dopy
Options
Examples
# Ensure a SSH key is present# If a key matches this name, will return the ssh key id and changed = False# If no existing key matches this name, a new key is created, the ssh key id→˓is returned and changed = False
- digital_ocean: >state=presentcommand=sshname=my_ssh_keyssh_pub_key='ssh-rsa AAAA...'api_token=XXX
# Create a new Droplet# Will return the droplet details including the droplet id (used for→˓idempotence)
- digital_ocean: >state=presentcommand=dropletname=mydropletapi_token=XXXsize_id=2gbregion_id=ams2image_id=fedora-19-x64wait_timeout=500
register: my_droplet- debug: msg="ID is {{ my_droplet.droplet.id }}"- debug: msg="IP is {{ my_droplet.droplet.ip_address }}"
# Ensure a droplet is present
1.6. Module Index 271
Ansible 1.2 Documentation, Release 0.01
# If droplet id already exist, will return the droplet details and changed =→˓False# If no droplet matches the id, a new droplet will be created and the→˓droplet details (including the new id) are returned, changed = True.
- digital_ocean: >state=presentcommand=dropletid=123name=mydropletapi_token=XXXsize_id=2gbregion_id=ams2image_id=fedora-19-x64wait_timeout=500
# Create a droplet with ssh key# The ssh key id can be passed as argument at the creation of a droplet (see→˓ssh_key_ids).# Several keys can be added to ssh_key_ids as id1,id2,id3# The keys are used to connect as root to the droplet.
- digital_ocean: >state=presentssh_key_ids=123,456name=mydropletapi_token=XXXsize_id=2gbregion_id=ams2image_id=fedora-19-x64
Notes
Note: Two environment variables can be used, DO_API_KEY and DO_API_TOKEN. They both refer to the v2token.
Note: As of Ansible 1.9.5 and 2.0, Version 2 of the DigitalOcean API is used, this removes client_id andapi_key options in favor of api_token.
Note: If you are running Ansible 1.9.4 or earlier you might not be able to use the included version of this moduleas the API version used has been retired. Upgrade Ansible or, if unable to, try downloading the latest version of thismodule from github and putting it into a ‘library’ directory.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
272 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
digital_ocean_domain - Create/delete a DNS record in DigitalOcean
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Create/delete a DNS record in DigitalOcean.
Requirements
• python >= 2.6
• dopy
Options
Examples
# Create a domain record
- digital_ocean_domain: >state=presentname=my.digitalocean.domainip=127.0.0.1
# Create a droplet and a corresponding domain record
- digital_ocean: >state=presentname=test_dropletsize_id=1gbregion_id=sgp1image_id=ubuntu-14-04-x64
register: test_droplet
- digital_ocean_domain: >state=presentname={{ test_droplet.droplet.name }}.my.domainip={{ test_droplet.droplet.ip_address }}
1.6. Module Index 273
Ansible 1.2 Documentation, Release 0.01
Notes
Note: Two environment variables can be used, DO_API_KEY and DO_API_TOKEN. They both refer to the v2token.
Note: As of Ansible 1.9.5 and 2.0, Version 2 of the DigitalOcean API is used, this removes client_id andapi_key options in favor of api_token.
Note: If you are running Ansible 1.9.4 or earlier you might not be able to use the included version of this module asthe API version used has been retired.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
digital_ocean_sshkey - Create/delete an SSH key in DigitalOcean
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Create/delete an SSH key.
Requirements
• python >= 2.6
• dopy
274 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Ensure a SSH key is present# If a key matches this name, will return the ssh key id and changed = False# If no existing key matches this name, a new key is created, the ssh key id→˓is returned and changed = False
- digital_ocean_sshkey: >state=presentname=my_ssh_keyssh_pub_key='ssh-rsa AAAA...'client_id=XXXapi_key=XXX
Notes
Note: Two environment variables can be used, DO_CLIENT_ID and DO_API_KEY.
Note: Version 1 of DigitalOcean API is used.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
django_manage - Manages a Django application.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Manages a Django application using the manage.py application frontend to django-admin. With the virtualenv param-eter, all management commands will be executed by the given virtualenv installation.
1.6. Module Index 275
Ansible 1.2 Documentation, Release 0.01
Requirements
• virtualenv
• django
Options
Examples
# Run cleanup on the application installed in 'django_dir'.- django_manage: command=cleanup app_path={{ django_dir }}
# Load the initial_data fixture into the application- django_manage: command=loaddata app_path={{ django_dir }} fixtures={{→˓initial_data }}
# Run syncdb on the application- django_manage: >
command=syncdbapp_path={{ django_dir }}settings={{ settings_app_name }}pythonpath={{ settings_dir }}virtualenv={{ virtualenv_dir }}
# Run the SmokeTest test case from the main app. Useful for testing deploys.- django_manage: command=test app_path={{ django_dir }} apps=main.SmokeTest
# Create an initial superuser.- django_manage: command="createsuperuser --noinput --username=admin --→˓[email protected]" app_path={{ django_dir }}
Notes
Note: virtualenv (http://www.virtualenv.org) must be installed on the remote host if the virtualenv parameter isspecified.
Note: This module will create a virtualenv if the virtualenv parameter is specified and a virtualenv does not alreadyexist at the given location.
Note: This module assumes English error messages for the ‘createcachetable’ command to detect table existence,unfortunately.
Note: To be able to use the migrate command with django versions < 1.7, you must have south installed and addedas an app in your settings.
276 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: To be able to use the collectstatic command, you must have enabled staticfiles in your settings.
Note: As of ansible 2.x, your manage.py application must be executable (rwxr-xr-x), and must have a valid shebang,i.e. “#!/usr/bin/env python”, for invoking the appropriate Python interpreter.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
dnf - Manages packages with the dnf package manager
New in version 1.9.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Installs, upgrade, removes, and lists packages and groups with the dnf package manager.
Requirements
• python >= 2.6
• python-dnf
Options
Examples
- name: install the latest version of Apachednf: name=httpd state=latest
- name: remove the Apache packagednf: name=httpd state=absent
- name: install the latest version of Apache from the testing repo
1.6. Module Index 277
Ansible 1.2 Documentation, Release 0.01
dnf: name=httpd enablerepo=testing state=present
- name: upgrade all packagesdnf: name=* state=latest
- name: install the nginx rpm from a remote repodnf: name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-
→˓centos-6-0.el6.ngx.noarch.rpm state=present
- name: install nginx rpm from a local filednf: name=/usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm
→˓state=present
- name: install the 'Development tools' package groupdnf: name="@Development tools" state=present
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
dnsimple - Interface with dnsimple.com (a DNS hosting service).
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Manages domains and records via the DNSimple API, see the docs: http://developer.dnsimple.com/
Requirements
• dnsimple
Options
278 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
# authenticate using email and API token- local_action: dnsimple [email protected] account_api_→˓token=dummyapitoken
# fetch all domains- local_action dnsimpleregister: domains
# fetch my.com domain records- local_action: dnsimple domain=my.com state=presentregister: records
# delete a domain- local_action: dnsimple domain=my.com state=absent
# create a test.my.com A record to point to 127.0.0.01- local_action: dnsimple domain=my.com record=test type=A value=127.0.0.1register: record
# and then delete it- local_action: dnsimple domain=my.com record_ids={{ record['id'] }}
# create a my.com CNAME record to example.com- local_action: dnsimple domain=my.com record= type=CNAME value=example.com→˓state=present
# change it's ttl- local_action: dnsimple domain=my.com record= type=CNAME value=example.com→˓ttl=600 state=present
# and delete the record- local_action: dnsimpledomain=my.com record= type=CNAME value=example.com→˓state=absent
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
dnsmadeeasy - Interface with dnsmadeeasy.com (a DNS hosting service).
New in version 1.3.
• Synopsis
• Requirements
• Options
• Examples
1.6. Module Index 279
Ansible 1.2 Documentation, Release 0.01
• Notes
• This is an Extras Module
Synopsis
Manages DNS records via the v2 REST API of the DNS Made Easy service. It handles records only; there is nomanipulation of domains or monitor/account support yet. See: http://www.dnsmadeeasy.com/services/rest-api/
Requirements
• hashlib
• hmac
Options
Examples
# fetch my.com domain records- dnsmadeeasy: account_key=key account_secret=secret domain=my.com→˓state=presentregister: response
# create / ensure the presence of a record- dnsmadeeasy: account_key=key account_secret=secret domain=my.com→˓state=present record_name="test" record_type="A" record_value="127.0.0.1"
# update the previously created record- dnsmadeeasy: account_key=key account_secret=secret domain=my.com→˓state=present record_name="test" record_value="192.168.0.1"
# fetch a specific record- dnsmadeeasy: account_key=key account_secret=secret domain=my.com→˓state=present record_name="test"register: response
# delete a record / ensure it is absent- dnsmadeeasy: account_key=key account_secret=secret domain=my.com→˓state=absent record_name="test"
Notes
Note: The DNS Made Easy service requires that machines interacting with the API have the proper time and timezoneset. Be sure you are within a few seconds of actual time by using NTP.
280 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: This module returns record(s) in the “result” element when ‘state’ is set to ‘present’. This value can be beregistered and used in your playbooks.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
docker - manage docker containers
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• This is a Core Module
Synopsis
Manage the life cycle of docker containers.
Requirements
• python >= 2.6
• docker-py >= 0.3.0
• The docker server >= 0.10.0
Options
Examples
# Containers are matched either by name (if provided) or by an exact match of# the image they were launched with and the command they're running. The→˓module# can accept either a name to target a container uniquely, or a count to→˓operate# on multiple containers at once when it makes sense to do so.
# Ensure that a data container with the name "mydata" exists. If no container# by this name exists, it will be created, but not started.
1.6. Module Index 281
Ansible 1.2 Documentation, Release 0.01
- name: data containerdocker:
name: mydataimage: busyboxstate: presentvolumes:- /data
# Ensure that a Redis server is running, using the volume from the data# container. Expose the default Redis port.
- name: redis containerdocker:
name: myredisimage: rediscommand: redis-server --appendonly yesstate: startedexpose:- 6379volumes_from:- mydata
# Ensure that a container of your application server is running. This will:# - pull the latest version of your application image from DockerHub.# - ensure that a container is running with the specified name and exact→˓image.# If any configuration options have changed, the existing container will be# stopped and removed, and a new one will be launched in its place.# - link this container to the existing redis container launched above with# an alias.# - bind TCP port 9000 within the container to port 8080 on all interfaces# on the host.# - bind UDP port 9001 within the container to port 8081 on the host, only# listening on localhost.# - set the environment variable SECRET_KEY to "ssssh".
- name: application containerdocker:
name: myapplicationimage: someuser/appimagestate: reloadedpull: alwayslinks:- "myredis:aliasedredis"ports:- "8080:9000"- "127.0.0.1:8081:9001/udp"env:
SECRET_KEY: ssssh
# Ensure that exactly five containers of another server are running with this# exact image and command. If fewer than five are running, more will be→˓launched;# if more are running, the excess will be stopped.
- name: load-balanced containersdocker:
282 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
state: reloadedcount: 5image: someuser/anotherappimagecommand: sleep 1d
# Unconditionally restart a service container. This may be useful within a# handler, for example.
- name: application servicedocker:
name: myserviceimage: someuser/serviceimagestate: restarted
# Stop all containers running the specified image.
- name: obsolete containerdocker:
image: someuser/oldandbustedstate: stopped
# Stop and remove a container with the specified name.
- name: obsolete containerdocker:
name: ohnoimage: someuser/oldandbustedstate: absent
# Example Syslogging Output
- name: myservice containerdocker:
name: myserviceimage: someservice/someimagestate: reloadedlog_driver: sysloglog_opt:
syslog-address: tcp://my-syslog-server:514syslog-facility: daemonsyslog-tag: myservice
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
docker_image - manage docker images
New in version 1.5.
1.6. Module Index 283
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• This is a Core Module
Synopsis
Create, check and remove docker images
Requirements
• python >= 2.6
• docker-py
• requests
Options
Examples
Build docker image if required. Path should contains Dockerfile to build→˓image:
- hosts: websudo: yestasks:- name: check or build image
docker_image: path="/path/to/build/dir" name="my/app" state=present
Build new version of image:
- hosts: websudo: yestasks:- name: check or build image
docker_image: path="/path/to/build/dir" name="my/app" state=build
Remove image from local docker storage:
- hosts: websudo: yestasks:- name: remove image
docker_image: name="my/app" state=absent
284 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
docker_login - Manage Docker registry logins
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Ansible version of the “docker login” CLI command. This module allows you to login to a Docker registry withoutdirectly pulling an image or performing any other actions. It will write your login credentials to your local .dockercfgfile that is compatible to the Docker CLI client as well as docker-py and all other Docker related modules that arebased on docker-py.
Requirements
• python >= 2.6
• docker-py >= 1.1.0
Options
Examples
Login to a Docker registry without performing any other action. Make sure→˓that the user you are using is either in the docker group which owns the→˓Docker socket or use sudo to perform login actions:
- name: login to DockerHub remote registry using your accountdocker_login:
username: dockerpassword: rekcodemail: [email protected]
- name: login to private Docker remote registry and force reauthentificationdocker_login:
registry: your.private.registry.io
1.6. Module Index 285
Ansible 1.2 Documentation, Release 0.01
username: yourselfpassword: secrets3reauth: yes
- name: login to DockerHub remote registry using a custom dockercfg file→˓locationdocker_login:
username: dockerpassword: rekcodemail: [email protected]_path: /tmp/.mydockercfg
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
dpkg_selections - Dpkg package selection selections
New in version 2.0.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Change dpkg package selection state via –get-selections and –set-selections.
Options
Examples
# Prevent python from being upgraded.- dpkg_selections: name=python selection=hold
Notes
Note: This module won’t cause any packages to be installed/removed/purged, use the apt module for that.
286 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
dynamodb_table - Create, update or delete AWS Dynamo DB tables.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Create or delete AWS Dynamo DB tables. Can update the provisioned throughput on existing tables. Returns thestatus of the specified table.
Requirements
• boto
• boto >= 2.13.2
• python >= 2.6
Options
Examples
# Create dynamo table with hash and range primary key- dynamodb_table:
name: my-tableregion: us-east-1hash_key_name: idhash_key_type: STRINGrange_key_name: create_timerange_key_type: NUMBERread_capacity: 2write_capacity: 2
1.6. Module Index 287
Ansible 1.2 Documentation, Release 0.01
# Update capacity on existing dynamo table- dynamodb_table:
name: my-tableregion: us-east-1read_capacity: 10write_capacity: 10
# Delete dynamo table- dynamodb_table:
name: my-tableregion: us-east-1state: absent
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
easy_install - Installs Python libraries
• Synopsis
• Requirements
• Options
288 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Examples
• Notes
• This is a Core Module
Synopsis
Installs Python libraries, optionally in a virtualenv
Requirements
• virtualenv
Options
Examples
# Examples from Ansible Playbooks- easy_install: name=pip state=latest
# Install Bottle into the specified virtualenv.- easy_install: name=bottle virtualenv=/webapps/myapp/venv
Notes
Note: Please note that the easy_install module can only install Python libraries. Thus this module is not able toremove libraries. It is generally recommended to use the pip module which you can first install using easy_install.
Note: Also note that virtualenv must be installed on the remote host if the virtualenv parameter is specified.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2 - create, terminate, start or stop an instance in ec2
• Synopsis
• Requirements
1.6. Module Index 289
Ansible 1.2 Documentation, Release 0.01
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Creates or terminates ec2 instances.
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
# Basic provisioning example- ec2:
key_name: mykeyinstance_type: t2.microimage: ami-123456wait: yesgroup: webservercount: 3vpc_subnet_id: subnet-29e63245assign_public_ip: yes
# Advanced example with tagging and CloudWatch- ec2:
key_name: mykeygroup: databasesinstance_type: t2.microimage: ami-123456wait: yeswait_timeout: 500count: 5instance_tags:
db: postgresmonitoring: yesvpc_subnet_id: subnet-29e63245assign_public_ip: yes
# Single instance with additional IOPS volume from snapshot and volume→˓delete on termination- ec2:
290 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
key_name: mykeygroup: webserverinstance_type: c3.mediumimage: ami-123456wait: yeswait_timeout: 500volumes:
- device_name: /dev/sdbsnapshot: snap-abcdef12volume_type: io1iops: 1000volume_size: 100delete_on_termination: true
monitoring: yesvpc_subnet_id: subnet-29e63245assign_public_ip: yes
# Single instance with ssd gp2 root volume- ec2:
key_name: mykeygroup: webserverinstance_type: c3.mediumimage: ami-123456wait: yeswait_timeout: 500volumes:- device_name: /dev/xvdavolume_type: gp2volume_size: 8
vpc_subnet_id: subnet-29e63245assign_public_ip: yesexact_count: 1
# Multiple groups example- ec2:
key_name: mykeygroup: ['databases', 'internal-services', 'sshable', 'and-so-forth']instance_type: m1.largeimage: ami-6e649707wait: yeswait_timeout: 500count: 5instance_tags:
db: postgresmonitoring: yesvpc_subnet_id: subnet-29e63245assign_public_ip: yes
# Multiple instances with additional volume from snapshot- ec2:
key_name: mykeygroup: webserverinstance_type: m1.largeimage: ami-6e649707wait: yeswait_timeout: 500count: 5volumes:
1.6. Module Index 291
Ansible 1.2 Documentation, Release 0.01
- device_name: /dev/sdbsnapshot: snap-abcdef12volume_size: 10
monitoring: yesvpc_subnet_id: subnet-29e63245assign_public_ip: yes
# Dedicated tenancy example- local_action:
module: ec2assign_public_ip: yesgroup_id: sg-1dc53f72key_name: mykeyimage: ami-6e649707instance_type: m1.smalltenancy: dedicatedvpc_subnet_id: subnet-29e63245wait: yes
# Spot instance example- ec2:
spot_price: 0.24spot_wait_timeout: 600keypair: mykeygroup_id: sg-1dc53f72instance_type: m1.smallimage: ami-6e649707wait: yesvpc_subnet_id: subnet-29e63245assign_public_ip: yes
# Examples using pre-existing network interfaces- ec2:
key_name: mykeyinstance_type: t2.smallimage: ami-f005ba11network_interface: eni-deadbeef
- ec2:key_name: mykeyinstance_type: t2.smallimage: ami-f005ba11network_interfaces: ['eni-deadbeef', 'eni-5ca1ab1e']
# Launch instances, runs some tasks# and then terminate them
- name: Create a sandbox instancehosts: localhostgather_facts: Falsevars:
key_name: my_keypairinstance_type: m1.smallsecurity_group: my_securitygroupimage: my_ami_idregion: us-east-1
tasks:- name: Launch instance
292 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
ec2:key_name: "{{ keypair }}"group: "{{ security_group }}"instance_type: "{{ instance_type }}"image: "{{ image }}"wait: trueregion: "{{ region }}"vpc_subnet_id: subnet-29e63245assign_public_ip: yes
register: ec2- name: Add new instance to host group
add_host: hostname={{ item.public_ip }} groupname=launchedwith_items: ec2.instances
- name: Wait for SSH to come upwait_for: host={{ item.public_dns_name }} port=22 delay=60 timeout=320
→˓state=startedwith_items: ec2.instances
- name: Configure instance(s)hosts: launchedsudo: Truegather_facts: Trueroles:
- my_awesome_role- my_awesome_test
- name: Terminate instanceshosts: localhostconnection: localtasks:
- name: Terminate instances that were previously launchedec2:state: 'absent'instance_ids: '{{ ec2.instance_ids }}'
# Start a few existing instances, run some tasks# and stop the instances
- name: Start sandbox instanceshosts: localhostgather_facts: falseconnection: localvars:
instance_ids:- 'i-xxxxxx'- 'i-xxxxxx'- 'i-xxxxxx'
region: us-east-1tasks:
- name: Start the sandbox instancesec2:instance_ids: '{{ instance_ids }}'region: '{{ region }}'state: runningwait: Truevpc_subnet_id: subnet-29e63245assign_public_ip: yes
role:
1.6. Module Index 293
Ansible 1.2 Documentation, Release 0.01
- do_neat_stuff- do_more_neat_stuff
- name: Stop sandbox instanceshosts: localhostgather_facts: falseconnection: localvars:
instance_ids:- 'i-xxxxxx'- 'i-xxxxxx'- 'i-xxxxxx'
region: us-east-1tasks:
- name: Stop the sandbox instancesec2:instance_ids: '{{ instance_ids }}'region: '{{ region }}'state: stoppedwait: Truevpc_subnet_id: subnet-29e63245assign_public_ip: yes
## Start stopped instances specified by tag#- local_action:
module: ec2instance_tags:
Name: ExtraPowerstate: running
## Enforce that 5 instances with a tag "foo" are running# (Highly recommended!)#
- ec2:key_name: mykeyinstance_type: c1.mediumimage: ami-40603AD1wait: yesgroup: webserverinstance_tags:
foo: barexact_count: 5count_tag: foovpc_subnet_id: subnet-29e63245assign_public_ip: yes
## Enforce that 5 running instances named "database" with a "dbtype" of→˓"postgres"#
- ec2:key_name: mykeyinstance_type: c1.medium
294 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
image: ami-40603AD1wait: yesgroup: webserverinstance_tags:
Name: databasedbtype: postgres
exact_count: 5count_tag:
Name: databasedbtype: postgres
vpc_subnet_id: subnet-29e63245assign_public_ip: yes
## count_tag complex argument examples#
# instances with tag foocount_tag:
foo:
# instances with tag foo=barcount_tag:
foo: bar
# instances with tags foo=bar & bazcount_tag:
foo: barbaz:
# instances with tags foo & bar & baz=bangcount_tag:
- foo- bar- baz: bang
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
1.6. Module Index 295
Ansible 1.2 Documentation, Release 0.01
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_ami - create or destroy an image in ec2
New in version 1.3.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Creates or deletes ec2 images.
Requirements
• python >= 2.6
• boto
Options
Examples
# Basic AMI Creation- ec2_ami:
aws_access_key: xxxxxxxxxxxxxxxxxxxxxxxaws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxinstance_id: i-xxxxxxwait: yesname: newtesttags:Name: newtestService: TestService
register: instance
# Basic AMI Creation, without waiting- ec2_ami:
aws_access_key: xxxxxxxxxxxxxxxxxxxxxxx
296 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
aws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxregion: xxxxxxinstance_id: i-xxxxxxwait: noname: newtest
register: instance
# AMI Creation, with a custom root-device size and another EBS attached- ec2_ami
aws_access_key: xxxxxxxxxxxxxxxxxxxxxxxaws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxinstance_id: i-xxxxxxname: newtestdevice_mapping:
- device_name: /dev/sda1size: XXXdelete_on_termination: truevolume_type: gp2
- device_name: /dev/sdbsize: YYYdelete_on_termination: falsevolume_type: gp2
register: instance
# AMI Creation, excluding a volume attached at /dev/sdb- ec2_ami
aws_access_key: xxxxxxxxxxxxxxxxxxxxxxxaws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxinstance_id: i-xxxxxxname: newtestdevice_mapping:
- device_name: /dev/sda1size: XXXdelete_on_termination: truevolume_type: gp2
- device_name: /dev/sdbno_device: yes
register: instance
# Deregister/Delete AMI- ec2_ami:
aws_access_key: xxxxxxxxxxxxxxxxxxxxxxxaws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxregion: xxxxxximage_id: "{{ instance.image_id }}"delete_snapshot: Truestate: absent
# Deregister AMI- ec2_ami:
aws_access_key: xxxxxxxxxxxxxxxxxxxxxxxaws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxregion: xxxxxximage_id: "{{ instance.image_id }}"delete_snapshot: Falsestate: absent
# Update AMI Launch Permissions, making it public
1.6. Module Index 297
Ansible 1.2 Documentation, Release 0.01
- ec2_ami:aws_access_key: xxxxxxxxxxxxxxxxxxxxxxxaws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxregion: xxxxxximage_id: "{{ instance.image_id }}"state: presentlaunch_permissions:group_names: ['all']
# Allow AMI to be launched by another account- ec2_ami:
aws_access_key: xxxxxxxxxxxxxxxxxxxxxxxaws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxregion: xxxxxximage_id: "{{ instance.image_id }}"state: presentlaunch_permissions:
user_ids: ['123456789012']
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_ami_copy - copies AMI between AWS regions, return new image id
New in version 2.0.
• Synopsis
• Requirements
298 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Copies AMI from a source region to a destination region. This module has a dependency on python-boto >= 2.5
Requirements
• python >= 2.6
• boto
Options
Examples
# Basic AMI Copy- local_action:
module: ec2_ami_copysource_region: eu-west-1dest_region: us-east-1source_image_id: ami-xxxxxxxname: SuperService-new-AMIdescription: latest patchtags: '{"Name":"SuperService-new-AMI", "type":"SuperService"}'wait: yes
register: image_id
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
1.6. Module Index 299
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_ami_find - Searches for AMIs to obtain the AMI ID and other information
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is a Core Module
Synopsis
Returns list of matching AMIs with AMI ID, along with other useful information Can search AMIs with differentowners Can search by matching tag(s), by AMI name and/or other criteria Results can be sorted and sliced
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
# Search for the AMI tagged "project:website"- ec2_ami_find:
owner: selfami_tags:
project: websiteno_result_action: fail
register: ami_find
# Search for the latest Ubuntu 14.04 AMI
300 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- ec2_ami_find:name: "ubuntu/images/ebs/ubuntu-trusty-14.04-amd64-server-*"owner: 099720109477sort: namesort_order: descendingsort_end: 1
register: ami_find
# Launch an EC2 instance- ec2:
image: "{{ ami_find.results[0].ami_id }}"instance_type: m3.mediumkey_name: mykeywait: yes
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: This module is not backwards compatible with the previous version of the ec2_search_ami module whichworked only for Ubuntu AMIs listed on cloud-images.ubuntu.com.
Note: See the example below for a suggestion of how to search by distro/release.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_ami_search - Retrieve AWS AMI information for a given operating system.
New in version 1.6.
• DEPRECATED
• Synopsis
• Options
• Examples
1.6. Module Index 301
Ansible 1.2 Documentation, Release 0.01
DEPRECATED
in favor of the ec2_ami_find module
Synopsis
Look up the most recent AMI on AWS for a given operating system. Returns ami, aki, ari, serial, tagIf there is no AKI or ARI associated with an image, these will be null. Only supports images from cloud-images.ubuntu.com Example output: {"ami": "ami-69f5a900", "changed": false, "aki":"aki-88aa75e1", "tag": "release", "ari": null, "serial": "20131024"}
Options
Examples
- name: Launch an Ubuntu 12.04 (Precise Pangolin) EC2 instancehosts: 127.0.0.1connection: localtasks:- name: Get the Ubuntu precise AMI
ec2_ami_search: distro=ubuntu release=precise region=us-west-1→˓store=instance-store
register: ubuntu_image- name: Start the EC2 instance
ec2: image={{ ubuntu_image.ami }} instance_type=m1.small key_name=mykey
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_asg - Create or delete AWS Autoscaling Groups
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Can create or delete AWS Autoscaling Groups Works with the ec2_lc module to manage Launch Configurations
302 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Requirements
• python >= 2.6
• boto
Options
Examples
# Basic configuration
- ec2_asg:name: specialload_balancers: [ 'lb1', 'lb2' ]availability_zones: [ 'eu-west-1a', 'eu-west-1b' ]launch_config_name: 'lc-1'min_size: 1max_size: 10desired_capacity: 5vpc_zone_identifier: [ 'subnet-abcd1234', 'subnet-1a2b3c4d' ]tags:- environment: productionpropagate_at_launch: no
# Rolling ASG Updates
Below is an example of how to assign a new launch config to an ASG and→˓terminate old instances.
All instances in "myasg" that do not have the launch configuration named "my_→˓new_lc" will be terminated ina rolling fashion with instances using the current launch configuration, "my_→˓new_lc".
This could also be considered a rolling deploy of a pre-baked AMI.
If this is a newly created group, the instances will not be replaced since→˓all instanceswill have the current launch configuration.
- name: create launch configec2_lc:
name: my_new_lcimage_id: ami-lkajsfkey_name: mykeyregion: us-east-1security_groups: sg-23423instance_type: m1.smallassign_public_ip: yes
- ec2_asg:name: myasglaunch_config_name: my_new_lchealth_check_period: 60health_check_type: ELB
1.6. Module Index 303
Ansible 1.2 Documentation, Release 0.01
replace_all_instances: yesmin_size: 5max_size: 5desired_capacity: 5region: us-east-1
To only replace a couple of instances instead of all of them, supply a listto "replace_instances":
- ec2_asg:name: myasglaunch_config_name: my_new_lchealth_check_period: 60health_check_type: ELBreplace_instances:- i-b345231- i-24c2931min_size: 5max_size: 5desired_capacity: 5region: us-east-1
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_eip - associate an EC2 elastic IP with an instance.
New in version 1.4.
304 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
This module associates AWS EC2 elastic IP addresses with instances
Requirements
• python >= 2.6
• boto
Options
Examples
- name: associate an elastic IP with an instanceec2_eip: device_id=i-1212f003 ip=93.184.216.119
- name: associate an elastic IP with a deviceec2_eip: device_id=eni-c8ad70f3 ip=93.184.216.119
- name: disassociate an elastic IP from an instanceec2_eip: device_id=i-1212f003 ip=93.184.216.119 state=absent
- name: disassociate an elastic IP with a deviceec2_eip: device_id=eni-c8ad70f3 ip=93.184.216.119 state=absent
- name: allocate a new elastic IP and associate it with an instanceec2_eip: device_id=i-1212f003
- name: allocate a new elastic IP without associating it to anythingaction: ec2_eipregister: eip
- name: output the IPdebug: msg="Allocated IP is {{ eip.public_ip }}"
- name: another way of allocating an elastic IP without associating it to→˓anythingec2_eip: state='present'
- name: provision new instances with ec2ec2: keypair=mykey instance_type=c1.medium image=emi-40603AD1 wait=yes
Notes
1.6. Module Index 305
Ansible 1.2 Documentation, Release 0.01
Note: This module will return public_ip on success, which will contain the public IP address associated with theinstance.
Note: There may be a delay between the time the Elastic IP is assigned and when the cloud instance is reachablevia the new address. Use wait_for and pause to delay further playbook execution until the instance is reachable, ifnecessary.
Note: This module returns multiple changed statuses on disassociation or release. It returns an overall status basedon any changes occuring. It also returns individual changed statuses for disassociation and release.
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_elb - De-registers or registers instances from EC2 ELBs
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
306 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
This module de-registers or registers an AWS EC2 instance from the ELBs that it belongs to. Returns fact “ec2_elbs”which is a list of elbs attached to the instance if state=absent is passed as an argument. Will be marked changed whencalled only if there are ELBs found to operate on.
Requirements
• python >= 2.6
• boto
Options
Examples
# basic pre_task and post_task examplepre_tasks:- name: Gathering ec2 facts
action: ec2_facts- name: Instance De-register
local_action:module: ec2_elbinstance_id: "{{ ansible_ec2_instance_id }}"state: absent
roles:- myrole
post_tasks:- name: Instance Register
local_action:module: ec2_elbinstance_id: "{{ ansible_ec2_instance_id }}"ec2_elbs: "{{ item }}"state: present
with_items: ec2_elbs
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
1.6. Module Index 307
Ansible 1.2 Documentation, Release 0.01
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_elb_facts - Gather facts about EC2 Elastic Load Balancers in AWS
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Gather facts about EC2 Elastic Load Balancers in AWS
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.# Output format tries to match ec2_elb_lb module input parameters
# Gather facts about all ELBs- action:
module: ec2_elb_factsregister: elb_facts
308 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- action:module: debugmsg: "{{ item.dns_name }}"
with_items: elb_facts.elbs
# Gather facts about a particular ELB- action:
module: ec2_elb_factsnames: frontend-prod-elb
register: elb_facts
- action:module: debugmsg: "{{ elb_facts.elbs.0.dns_name }}"
# Gather facts about a set of ELBs- action:
module: ec2_elb_factsnames:- frontend-prod-elb- backend-prod-elb
register: elb_facts
- action:module: debugmsg: "{{ item.dns_name }}"
with_items: elb_facts.elbs
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 309
Ansible 1.2 Documentation, Release 0.01
ec2_elb_lb - Creates or destroys Amazon ELB.
New in version 1.5.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Returns information about the load balancer. Will be marked changed when called only if state is changed.
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: None of these examples set aws_access_key, aws_secret_key, or region.# It is assumed that their matching environment variables are set.
# Basic provisioning example (non-VPC)
- local_action:module: ec2_elb_lbname: "test-please-delete"state: presentzones:- us-east-1a- us-east-1d
listeners:- protocol: http # options are http, https, ssl, tcpload_balancer_port: 80instance_port: 80
- protocol: httpsload_balancer_port: 443instance_protocol: http # optional, defaults to value of protocol
→˓settinginstance_port: 80# ssl certificate required for https or sslssl_certificate_id: "arn:aws:iam::123456789012:server-certificate/
→˓company/servercerts/ProdServerCert"
310 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# Internal ELB example
- local_action:module: ec2_elb_lbname: "test-vpc"scheme: internalstate: presentsubnets:- subnet-abcd1234- subnet-1a2b3c4d
listeners:- protocol: http # options are http, https, ssl, tcpload_balancer_port: 80instance_port: 80
# Configure a health check and the access logs- local_action:
module: ec2_elb_lbname: "test-please-delete"state: presentzones:- us-east-1d
listeners:- protocol: httpload_balancer_port: 80instance_port: 80
health_check:ping_protocol: http # options are http, https, ssl, tcpping_port: 80ping_path: "/index.html" # not required for tcp or sslresponse_timeout: 5 # secondsinterval: 30 # secondsunhealthy_threshold: 2healthy_threshold: 10
access_logs:interval: 5 # minutes (defaults to 60)s3_location: "my-bucket" # This value is required if access_logs is
→˓sets3_prefix: "logs"
# Ensure ELB is gone- local_action:
module: ec2_elb_lbname: "test-please-delete"state: absent
# Normally, this module will purge any listeners that exist on the ELB# but aren't specified in the listeners parameter. If purge_listeners is# false it leaves them alone- local_action:
module: ec2_elb_lbname: "test-please-delete"state: presentzones:- us-east-1a- us-east-1d
listeners:
1.6. Module Index 311
Ansible 1.2 Documentation, Release 0.01
- protocol: httpload_balancer_port: 80instance_port: 80
purge_listeners: no
# Normally, this module will leave availability zones that are enabled# on the ELB alone. If purge_zones is true, then any extraneous zones# will be removed- local_action:
module: ec2_elb_lbname: "test-please-delete"state: presentzones:- us-east-1a- us-east-1d
listeners:- protocol: httpload_balancer_port: 80instance_port: 80
purge_zones: yes
# Creates a ELB and assigns a list of subnets to it.- local_action:
module: ec2_elb_lbstate: presentname: 'New ELB'security_group_ids: 'sg-123456, sg-67890'region: us-west-2subnets: 'subnet-123456,subnet-67890'purge_subnets: yeslisteners:- protocol: httpload_balancer_port: 80instance_port: 80
# Create an ELB with connection draining, increased idle timeout and cross→˓availability# zone load balancing- local_action:
module: ec2_elb_lbname: "New ELB"state: presentconnection_draining_timeout: 60idle_timeout: 300cross_az_load_balancing: "yes"region: us-east-1zones:
- us-east-1a- us-east-1d
listeners:- protocols: http- load_balancer_port: 80- instance_port: 80
# Create an ELB with load balanacer stickiness enabled- local_action:
module: ec2_elb_lbname: "New ELB"
312 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
state: presentregion: us-east-1zones:
- us-east-1a- us-east-1d
listeners:- protocols: http- load_balancer_port: 80- instance_port: 80
stickiness:type: loadbalancerenabled: yesexpiration: 300
# Create an ELB with application stickiness enabled- local_action:
module: ec2_elb_lbname: "New ELB"state: presentregion: us-east-1zones:
- us-east-1a- us-east-1d
listeners:- protocols: http- load_balancer_port: 80- instance_port: 80
stickiness:type: applicationenabled: yescookie: SESSIONID
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
1.6. Module Index 313
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_eni - Create and optionally attach an Elastic Network Interface (ENI) to an instance
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Create and optionally attach an Elastic Network Interface (ENI) to an instance. If an ENI ID is provided, an attempt ismade to update the existing ENI. By passing ‘None’ as the instance_id, an ENI can be detached from an instance.
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
# Create an ENI. As no security group is defined, ENI will be created in→˓default security group- ec2_eni:
private_ip_address: 172.31.0.20subnet_id: subnet-xxxxxxxxstate: present
# Create an ENI and attach it to an instance- ec2_eni:
instance_id: i-xxxxxxxdevice_index: 1private_ip_address: 172.31.0.20subnet_id: subnet-xxxxxxxxstate: present
314 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# Destroy an ENI, detaching it from any instance if necessary- ec2_eni:
eni_id: eni-xxxxxxxforce_detach: yesstate: absent
# Update an ENI- ec2_eni:
eni_id: eni-xxxxxxxdescription: "My new description"state: present
# Detach an ENI from an instance- ec2_eni:
eni_id: eni-xxxxxxxinstance_id: Nonestate: present
### Delete an interface on termination# First create the interface- ec2_eni:
instance_id: i-xxxxxxxdevice_index: 1private_ip_address: 172.31.0.20subnet_id: subnet-xxxxxxxxstate: present
register: eni
# Modify the interface to enable the delete_on_terminaton flag- ec2_eni:
eni_id: {{ "eni.interface.id" }}delete_on_termination: true
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
1.6. Module Index 315
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_eni_facts - Gather facts about ec2 ENI interfaces in AWS
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Gather facts about ec2 ENI interfaces in AWS
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
# Gather facts about all ENIs- ec2_eni_facts:
# Gather facts about a particular ENI- ec2_eni_facts:
filters:network-interface-id: eni-xxxxxxx
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,
316 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_facts - Gathers facts about remote hosts within ec2 (aws)
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
This module fetches data from the metadata servers in ec2 (aws) as per http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html. The module must be called from within the EC2 instance itself.
Options
Examples
# Conditional example- name: Gather factsaction: ec2_facts
- name: Conditionalaction: debug msg="This instance is a t1.micro"when: ansible_ec2_instance_type == "t1.micro"
1.6. Module Index 317
Ansible 1.2 Documentation, Release 0.01
Notes
Note: Parameters to filter on ec2_facts may be added later.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_group - maintain an ec2 VPC security group.
New in version 1.3.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
maintains ec2 security groups. This module has a dependency on python-boto >= 2.5
Requirements
• python >= 2.6
• boto
Options
Examples
- name: example ec2 groupec2_group:
name: exampledescription: an example EC2 groupvpc_id: 12345region: eu-west-1aaws_secret_key: SECRET
318 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
aws_access_key: ACCESSrules:
- proto: tcpfrom_port: 80to_port: 80cidr_ip: 0.0.0.0/0
- proto: tcpfrom_port: 22to_port: 22cidr_ip: 10.0.0.0/8
- proto: tcpfrom_port: 443to_port: 443group_id: amazon-elb/sg-87654321/amazon-elb-sg
- proto: tcpfrom_port: 3306to_port: 3306group_id: 123412341234/sg-87654321/exact-name-of-sg
- proto: udpfrom_port: 10050to_port: 10050cidr_ip: 10.0.0.0/8
- proto: udpfrom_port: 10051to_port: 10051group_id: sg-12345678
- proto: icmpfrom_port: 8 # icmp type, -1 = any typeto_port: -1 # icmp subtype, -1 = any subtypecidr_ip: 10.0.0.0/8
- proto: all# the containing group name may be specified heregroup_name: example
rules_egress:- proto: tcpfrom_port: 80to_port: 80cidr_ip: 0.0.0.0/0group_name: example-other# description to use if example-other needs to be createdgroup_desc: other example EC2 group
Notes
Note: If a rule declares a group_name and that group doesn’t exist, it will be automatically created. In that case,group_desc should be provided as well. The module will refuse to create a depended-on group without a description.
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
1.6. Module Index 319
Ansible 1.2 Documentation, Release 0.01
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_key - maintain an ec2 key pair.
New in version 1.5.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
maintains ec2 key pairs. This module has a dependency on python-boto >= 2.5
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: None of these examples set aws_access_key, aws_secret_key, or region.# It is assumed that their matching environment variables are set.
# Creates a new ec2 key pair named `example` if not present, returns→˓generated
320 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# private key- name: example ec2 keyec2_key:
name: example
# Creates a new ec2 key pair named `example` if not present using provided→˓key# material. This could use the 'file' lookup plugin to pull this off disk.- name: example2 ec2 keyec2_key:
name: example2key_material: 'ssh-rsa AAAAxyz...== [email protected]'state: present
# Creates a new ec2 key pair named `example` if not present using provided→˓key# material- name: example3 ec2 keyec2_key:
name: example3key_material: "{{ item }}"
with_file: /path/to/public_key.id_rsa.pub
# Removes ec2 key pair by name- name: remove example keyec2_key:
name: examplestate: absent
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 321
Ansible 1.2 Documentation, Release 0.01
ec2_lc - Create or delete AWS Autoscaling Launch Configurations
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Can create or delete AwS Autoscaling Configurations Works with the ec2_asg module to manage Autoscaling Groups
Requirements
• python >= 2.6
• boto
Options
Examples
- ec2_lc:name: specialimage_id: ami-XXXkey_name: defaultsecurity_groups: ['group', 'group2' ]instance_type: t1.microvolumes:- device_name: /dev/sda1volume_size: 100device_type: io1iops: 3000delete_on_termination: true
Notes
Note: Amazon ASG Autoscaling Launch Configurations are immutable once created, so modifying the configurationafter it is changed will not modify the launch configuration on AWS. You must create a new config and assign it to theASG instead.
322 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_metric_alarm - Create/update or delete AWS Cloudwatch ‘metric alarms’
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Can create or delete AWS metric alarms Metrics you wish to alarm on must already exist
Requirements
• python >= 2.6
• boto
1.6. Module Index 323
Ansible 1.2 Documentation, Release 0.01
Options
Examples
- name: create alarmec2_metric_alarm:
state: presentregion: ap-southeast-2name: "cpu-low"metric: "CPUUtilization"namespace: "AWS/EC2"statistic: Averagecomparison: "<="threshold: 5.0period: 300evaluation_periods: 3unit: "Percent"description: "This will alarm when a bamboo slave's cpu usage average is
→˓lower than 5% for 15 minutes "dimensions: {'InstanceId':'i-XXX'}alarm_actions: ["action1","action2"]
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_remote_facts - Gather facts about ec2 instances in AWS
New in version 2.0.
324 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Gather facts about ec2 instances in AWS
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
# Gather facts about all ec2 instances- ec2_remote_facts:
# Gather facts about all running ec2 instances with a tag of Name:Example- ec2_remote_facts:
filters:instance-state-name: running"tag:Name": Example
# Gather facts about instance i-123456- ec2_remote_facts:
filters:instance-id: i-123456
# Gather facts about all instances in vpc-123456 that are t2.small type- ec2_remote_facts:
filters:vpc-id: vpc-123456instance-type: t2.small
Notes
1.6. Module Index 325
Ansible 1.2 Documentation, Release 0.01
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_scaling_policy - Create or delete AWS scaling policies for Autoscaling groups
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Can create or delete scaling policies for autoscaling groups Referenced autoscaling groups must already exist
Requirements
• python >= 2.6
• boto
326 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
- ec2_scaling_policy:state: presentregion: US-XXXname: "scaledown-policy"adjustment_type: "ChangeInCapacity"asg_name: "slave-pool"scaling_adjustment: -1min_adjustment_step: 1cooldown: 300
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_snapshot - creates a snapshot from an existing volume
New in version 1.5.
• Synopsis
• Requirements
• Options
• Examples
1.6. Module Index 327
Ansible 1.2 Documentation, Release 0.01
• Notes
• This is a Core Module
Synopsis
creates an EC2 snapshot from an existing EBS volume
Requirements
• python >= 2.6
• boto
Options
Examples
# Simple snapshot of volume using volume_id- ec2_snapshot:
volume_id: vol-abcdef12description: snapshot of /data from DB123 taken 2013/11/28 12:18:32
# Snapshot of volume mounted on device_name attached to instance_id- ec2_snapshot:
instance_id: i-12345678device_name: /dev/sdb1description: snapshot of /data from DB123 taken 2013/11/28 12:18:32
# Snapshot of volume with tagging- ec2_snapshot:
instance_id: i-12345678device_name: /dev/sdb1snapshot_tags:
frequency: hourlysource: /data
# Remove a snapshot- local_action:
module: ec2_snapshotsnapshot_id: snap-abcd1234state: absent
# Create a snapshot only if the most recent one is older than 1 hour- local_action:
module: ec2_snapshotvolume_id: vol-abcdef12last_snapshot_min_age: 60
Notes
328 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_tag - create and remove tag(s) to ec2 resources.
New in version 1.3.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Creates, removes and lists tags from any EC2 resource. The resource is referenced by its resource id (e.g. an in-stance being i-XXXXXXX). It is designed to be used with complex args (tags), see the examples. This module has adependency on python-boto.
Requirements
• python >= 2.6
• boto
1.6. Module Index 329
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Basic example of adding tag(s)tasks:- name: tag a resourceec2_tag:
region: eu-west-1resource: vol-XXXXXXstate: presenttags:
Name: ubervolenv: prod
# Playbook example of adding tags to volumes on an instancetasks:- name: launch an instanceec2:
count_tags:Name: dbserverEnv: production
exact_count: 1group: "{{ security_group }}"keypair: "{{ keypair }}"image: "{{ image_id }}"instance_tags:
Name: dbserverEnv: production
instance_type: "{{ instance_type }}"region: eu-west-1volumes:
- device_name: /dev/xvdbdevice_type: standardvolume_size: 10delete_on_termination: true
wait: trueregister: ec2
- name: list the volumes for the instanceec2_vol:
instance: "{{ item.id }}"region: eu-west-1state: list
with_items: ec2.tagged_instancesregister: ec2_vol
- name: tag the volumesec2_tag:
region: eu-west-1resource: "{{ item.id }}"state: presenttags:Name: dbserverEnv: production
with_subelements:- ec2_vol.results
330 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- volumes
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_vol - create and attach a volume, return volume id and device map
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
creates an EBS volume and optionally attaches it to an instance. If both an instance ID and a device name is given andthe instance has a device at the device name, then no volume is created and no attachment is made. This module has adependency on python-boto.
1.6. Module Index 331
Ansible 1.2 Documentation, Release 0.01
Requirements
• python >= 2.6
• boto
Options
Examples
# Simple attachment action- ec2_vol:
instance: XXXXXXvolume_size: 5device_name: sdd
# Example using custom iops params- ec2_vol:
instance: XXXXXXvolume_size: 5iops: 100device_name: sdd
# Example using snapshot id- ec2_vol:
instance: XXXXXXsnapshot: "{{ snapshot }}"
# Playbook example combined with instance launch- ec2:
keypair: "{{ keypair }}"image: "{{ image }}"wait: yescount: 3
register: ec2- ec2_vol:
instance: "{{ item.id }} "volume_size: 5
with_items: ec2.instancesregister: ec2_vol
# Example: Launch an instance and then add a volume if not already attached# * Volume will be created with the given name if not already created.# * Nothing will happen if the volume is already attached.# * Requires Ansible 2.0
- ec2:keypair: "{{ keypair }}"image: "{{ image }}"zone: YYYYYYid: my_instancewait: yescount: 1
register: ec2
- ec2_vol:
332 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
instance: "{{ item.id }}"name: my_existing_volume_Name_tagdevice_name: /dev/xvdf
with_items: ec2.instancesregister: ec2_vol
# Remove a volume- ec2_vol:
id: vol-XXXXXXXXstate: absent
# Detach a volume (since 1.9)- ec2_vol:
id: vol-XXXXXXXXinstance: None
# List volumes for an instance- ec2_vol:
instance: i-XXXXXXstate: list
# Create new volume using SSD storage- ec2_vol:
instance: XXXXXXvolume_size: 50volume_type: gp2device_name: /dev/xvdf
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 333
Ansible 1.2 Documentation, Release 0.01
ec2_vpc - configure AWS virtual private clouds
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Create or terminates AWS virtual private clouds. This module has a dependency on python-boto.
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: None of these examples set aws_access_key, aws_secret_key, or region.# It is assumed that their matching environment variables are set.
# Basic creation example:ec2_vpc:state: presentcidr_block: 172.23.0.0/16resource_tags: { "Environment":"Development" }region: us-west-2
# Full creation example with subnets and optional availability zones.# The absence or presence of subnets deletes or creates them respectively.
ec2_vpc:state: presentcidr_block: 172.22.0.0/16resource_tags: { "Environment":"Development" }subnets:- cidr: 172.22.1.0/24az: us-west-2cresource_tags: { "Environment":"Dev", "Tier" : "Web" }
- cidr: 172.22.2.0/24az: us-west-2bresource_tags: { "Environment":"Dev", "Tier" : "App" }
- cidr: 172.22.3.0/24
334 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
az: us-west-2aresource_tags: { "Environment":"Dev", "Tier" : "DB" }
internet_gateway: Trueroute_tables:- subnets:
- 172.22.2.0/24- 172.22.3.0/24
routes:- dest: 0.0.0.0/0gw: igw
- subnets:- 172.22.1.0/24
routes:- dest: 0.0.0.0/0gw: igw
region: us-west-2register: vpc
# Removal of a VPC by idec2_vpc:state: absentvpc_id: vpc-aaaaaaaregion: us-west-2
If you have added elements not managed by this module, e.g. instances, NATs,→˓etc thenthe delete will fail until those dependencies are removed.
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 335
Ansible 1.2 Documentation, Release 0.01
ec2_vpc_igw - Manage an AWS VPC Internet gateway
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manage an AWS VPC Internet gateway
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
# Ensure that the VPC has an Internet Gateway.# The Internet Gateway ID is can be accessed via {{igw.gateway_id}} for use→˓in setting up NATs etc.ec2_vpc_igw:vpc_id: vpc-abcdefghstate: present
register: igw
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
336 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_vpc_net - Configure AWS virtual private clouds
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Create or terminate AWS virtual private clouds. This module has a dependency on python-boto.
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
# Create a VPC with dedicate tenancy and a couple of tags
1.6. Module Index 337
Ansible 1.2 Documentation, Release 0.01
- ec2_vpc_net:name: Module_dev2cidr_block: 10.10.0.0/16region: us-east-1tags:module: ec2_vpc_netthis: works
tenancy: dedicated
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_vpc_net_facts - Gather facts about ec2 VPCs in AWS
New in version 2.1.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
338 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
Gather facts about ec2 VPCs in AWS
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
# Gather facts about all VPCs- ec2_vpc_net_facts:
# Gather facts about a particular VPC using VPC ID- ec2_vpc_net_facts:
filters:vpc-id: vpc-00112233
# Gather facts about any VPC with a tag key Name and value Example- ec2_vpc_net_facts:
filters:"tag:Name": Example
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
1.6. Module Index 339
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_vpc_route_table - Manage route tables for AWS virtual private clouds
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manage route tables for AWS virtual private clouds
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
# Basic creation example:- name: Set up public subnet route tableec2_vpc_route_table:
vpc_id: vpc-1245678region: us-west-1tags:Name: Public
subnets:- "{{ jumpbox_subnet.subnet.id }}"- "{{ frontend_subnet.subnet.id }}"- "{{ vpn_subnet.subnet_id }}"
routes:- dest: 0.0.0.0/0gateway_id: "{{ igw.gateway_id }}"
register: public_route_table
340 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- name: Set up NAT-protected route tableec2_vpc_route_table:
vpc_id: vpc-1245678region: us-west-1tags:
Name: Internalsubnets:
- "{{ application_subnet.subnet.id }}"- 'Database Subnet'- '10.0.0.0/8'
routes:- dest: 0.0.0.0/0instance_id: "{{ nat.instance_id }}"
register: nat_route_table
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_vpc_route_table_facts - Gather facts about ec2 VPC route tables in AWS
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
1.6. Module Index 341
Ansible 1.2 Documentation, Release 0.01
• Notes
• This is an Extras Module
Synopsis
Gather facts about ec2 VPC route tables in AWS
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
# Gather facts about all VPC route tables- ec2_vpc_route_table_facts:
# Gather facts about a particular VPC route table using route table ID- ec2_vpc_route_table_facts:
filters:route-table-id: rtb-00112233
# Gather facts about any VPC route table with a tag key Name and value→˓Example- ec2_vpc_route_table_facts:
filters:"tag:Name": Example
# Gather facts about any VPC route table within VPC with ID vpc-abcdef00- ec2_vpc_route_table_facts:
filters:vpc-id: vpc-abcdef00
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
342 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_vpc_subnet - Manage subnets in AWS virtual private clouds
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manage subnets in AWS virtual private clouds
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
- name: Create subnet for database servers
1.6. Module Index 343
Ansible 1.2 Documentation, Release 0.01
ec2_vpc_subnet:state: presentvpc_id: vpc-123456cidr: 10.0.1.16/28resource_tags:
Name: Database Subnetregister: database_subnet
- name: Remove subnet for database serversec2_vpc_subnet:
state: absentvpc_id: vpc-123456cidr: 10.0.1.16/28
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_vpc_subnet_facts - Gather facts about ec2 VPC subnets in AWS
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
344 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• This is an Extras Module
Synopsis
Gather facts about ec2 VPC subnets in AWS
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
# Gather facts about all VPC subnets- ec2_vpc_subnet_facts:
# Gather facts about a particular VPC subnet using ID- ec2_vpc_subnet_facts:
filters:subnet-id: subnet-00112233
# Gather facts about any VPC subnet with a tag key Name and value Example- ec2_vpc_subnet_facts:
filters:"tag:Name": Example
# Gather facts about any VPC subnet within VPC with ID vpc-abcdef00- ec2_vpc_subnet_facts:
filters:vpc-id: vpc-abcdef00
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
1.6. Module Index 345
Ansible 1.2 Documentation, Release 0.01
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ec2_win_password - gets the default administrator password for ec2 windows instances
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Gets the default administrator password from any EC2 Windows instance. The instance is referenced by its id (e.g.i-XXXXXXX). This module has a dependency on python-boto.
Requirements
• python >= 2.6
• boto
Options
Examples
# Example of getting a passwordtasks:- name: get the Administrator passwordec2_win_password:
profile: my-boto-profileinstance_id: i-XXXXXXregion: us-east-1key_file: "~/aws-creds/my_test_key.pem"
346 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# Example of getting a password with a password protected keytasks:- name: get the Administrator passwordec2_win_password:
profile: my-boto-profileinstance_id: i-XXXXXXregion: us-east-1key_file: "~/aws-creds/my_protected_test_key.pem"key_passphrase: "secret"
# Example of waiting for a passwordtasks:- name: get the Administrator passwordec2_win_password:
profile: my-boto-profileinstance_id: i-XXXXXXregion: us-east-1key_file: "~/aws-creds/my_test_key.pem"wait: yeswait_timeout: 45
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ecs_cluster - create or terminate ecs clusters
New in version 2.0.
1.6. Module Index 347
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Creates or terminates ecs clusters.
Requirements
• json
• time
• boto
• boto3
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
# Cluster creation- ecs_cluster:
name: defaultstate: present
# Cluster deletion- ecs_cluster:
name: defaultstate: absent
- name: Wait for registerecs_cluster:
name: "{{ new_cluster }}"state: has_instancesdelay: 10repeat: 10
register: task_output
348 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: When deleting a cluster, the information returned is the state of the cluster prior to deletion.
Note: It will also wait for a cluster to have instances registered to it.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ecs_task - run, start or stop a task in ecs
New in version 2.0.
• Synopsis
• Options
• Examples
• Return Values
• This is an Extras Module
Synopsis
Creates or deletes instances of task definitions.
Options
Examples
# Simple example of run task- name: Run taskecs_task:
operation: runcluster: console-sample-app-static-clustertask_definition: console-sample-app-static-taskdefcount: 1
1.6. Module Index 349
Ansible 1.2 Documentation, Release 0.01
started_by: ansible_userregister: task_output
# Simple example of start task
- name: Start a taskecs_task:
operation: startcluster: console-sample-app-static-clustertask_definition: console-sample-app-static-taskdeftask: "arn:aws:ecs:us-west-2:172139249013:task/3f8353d1-29a8-4689-bbf6-
→˓ad79937ffe8a"container_instances:- arn:aws:ecs:us-west-2:172139249013:container-instance/79c23f22-876c-
→˓438a-bddf-55c98a3538a8started_by: ansible_user
register: task_output
- name: Stop a taskecs_task:
operation: stopcluster: console-sample-app-static-clustertask_definition: console-sample-app-static-taskdeftask: "arn:aws:ecs:us-west-2:172139249013:task/3f8353d1-29a8-4689-bbf6-
→˓ad79937ffe8a"
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ecs_taskdefinition - register a task definition in ecs
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• This is an Extras Module
350 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
Creates or terminates task definitions
Requirements
• json
• boto
• botocore
• boto3
Options
Examples
- name: "Create task definition"ecs_taskdefinition:
containers:- name: simple-app
cpu: 10essential: trueimage: "httpd:2.4"memory: 300mountPoints:- containerPath: /usr/local/apache2/htdocssourceVolume: my-vol
portMappings:- containerPort: 80hostPort: 80
- name: busyboxcommand:- "/bin/sh -c "while true; do echo '<html> <head> <title>Amazon ECS
→˓Sample App</title> <style>body {margin-top: 40px; background-color: #333;}→˓</style> </head><body> <div style=color:white;text-align:center> <h1>→˓Amazon ECS Sample App</h1> <h2>Congratulations!</h2> <p>Your application→˓is now running on a container in Amazon ECS.</p>' > top; /bin/date > date ;→˓ echo '</div></body></html>' > bottom; cat top date bottom > /usr/local/→˓apache2/htdocs/index.html ; sleep 1; done""
cpu: 10entryPoint:- sh- "-c"essential: falseimage: busyboxmemory: 200volumesFrom:- sourceContainer: simple-app
volumes:- name: my-volfamily: test-cluster-taskdefstate: present
register: task_output
1.6. Module Index 351
Ansible 1.2 Documentation, Release 0.01
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ejabberd_user - Manages users for ejabberd servers
New in version 1.5.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
This module provides user management for ejabberd servers
Requirements
• ejabberd with mod_admin_extra
Options
Examples
Example playbook entries using the ejabberd_user module to manage users→˓state.
tasks:
- name: create a user if it does not existsaction: ejabberd_user username=test host=server password=password
- name: delete a user if it existsaction: ejabberd_user username=test host=server state=absent
352 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Notes
Note: Password parameter is required for state == present only
Note: Passwords must be stored in clear text for this release
Note: The ejabberd configuration file must include mod_admin_extra as a module.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
elasticache - Manage cache clusters in Amazon Elasticache.
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Manage cache clusters in Amazon Elasticache. Returns information about the specified cache cluster.
Requirements
• python >= 2.6
• boto
Options
1.6. Module Index 353
Ansible 1.2 Documentation, Release 0.01
Examples
# Note: None of these examples set aws_access_key, aws_secret_key, or region.# It is assumed that their matching environment variables are set.
# Basic example- elasticache:
name: "test-please-delete"state: presentengine: memcachedcache_engine_version: 1.4.14node_type: cache.m1.smallnum_nodes: 1cache_port: 11211cache_security_groups:- default
zone: us-east-1d
# Ensure cache cluster is gone- elasticache:
name: "test-please-delete"state: absent
# Reboot cache cluster- elasticache:
name: "test-please-delete"state: rebooted
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
354 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
elasticache_subnet_group - manage Elasticache subnet groups
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Creates, modifies, and deletes Elasticache subnet groups. This module has a dependency on python-boto >= 2.5.
Requirements
• python >= 2.6
• boto
Options
Examples
# Add or change a subnet group- elasticache_subnet_group
state: presentname: norwegian-bluedescription: My Fancy Ex Parrot Subnet Groupsubnets:- subnet-aaaaaaaa- subnet-bbbbbbbb
# Remove a subnet group- elasticache_subnet_group:
state: absentname: norwegian-blue
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,
1.6. Module Index 355
Ansible 1.2 Documentation, Release 0.01
AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
elasticsearch_plugin - Manage Elasticsearch plugins
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manages Elasticsearch plugins.
Options
Examples
# Install Elasticsearch head plugin- elasticsearch_plugin: state=present name="mobz/elasticsearch-head"
# Install specific version of a plugin- elasticsearch_plugin: state=present name="com.github.kzwang/elasticsearch-→˓image" version="1.2.0"
# Uninstall Elasticsearch head plugin- elasticsearch_plugin: state=absent name="mobz/elasticsearch-head"
356 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
expect - Executes a command and responds to prompts
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
The expect module executes a command and responds to prompts The given command will be executed on all selectednodes. It will not be processed through the shell, so variables like $HOME and operations like "<", ">", "|", and"&" will not work
Requirements
• python >= 2.6
• pexpect >= 3.3
Options
Examples
- expect:command: passwd usernameresponses:(?i)password: "MySekretPa$$word"
Notes
Note: If you want to run a command through the shell (say you are using <, >, |, etc), you must specify a shell in thecommand such as /bin/bash -c "/path/to/something | grep else"
1.6. Module Index 357
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
facter - Runs the discovery program facter on the remote system
• Synopsis
• Requirements
• Examples
• This is an Extras Module
Synopsis
Runs the facter discovery program (https://github.com/puppetlabs/facter) on the remote system, returning JSON datathat can be useful for inventory purposes.
Requirements
• facter
• ruby-json
Examples
# Example command-line invocationansible www.example.net -m facter
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
fail - Fail with custom message
• Synopsis
• Options
• Examples
358 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• This is a Core Module
Synopsis
This module fails the progress with a custom message. It can be useful for bailing out when a certain condition is metusing when.
Options
Examples
# Example playbook using fail and when together- fail: msg="The system may not be provisioned according to the CMDB status."when: cmdb_status != "to-be-staged"
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
fetch - Fetches a file from remote nodes
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
This module works like copy, but in reverse. It is used for fetching files from remote machines and storing them locallyin a file tree, organized by hostname. Note that this module is written to transfer log files that might not be present, soa missing remote file won’t be an error unless fail_on_missing is set to ‘yes’.
Options
Examples
# Store file into /tmp/fetched/host.example.com/tmp/somefile- fetch: src=/tmp/somefile dest=/tmp/fetched
# Specifying a path directly
1.6. Module Index 359
Ansible 1.2 Documentation, Release 0.01
- fetch: src=/tmp/somefile dest=/tmp/prefix-{{ ansible_hostname }} flat=yes
# Specifying a destination path- fetch: src=/tmp/uniquefile dest=/tmp/special/ flat=yes
# Storing in a path relative to the playbook- fetch: src=/tmp/uniquefile dest=special/prefix-{{ ansible_hostname }}→˓flat=yes
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
file - Sets attributes of files
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Sets attributes of files, symlinks, and directories, or removes files/symlinks/directories. Many other modules supportthe same options as the file module - including copy, template, and assemble.
Options
Examples
# change file ownership, group and mode. When specifying mode using octal→˓numbers, first digit should always be 0.- file: path=/etc/foo.conf owner=foo group=foo mode=0644- file: src=/file/to/link/to dest=/path/to/symlink owner=foo group=foo→˓state=link- file: src=/tmp/{{ item.src }} dest={{ item.dest }} state=linkwith_items:
- { src: 'x', dest: 'y' }- { src: 'z', dest: 'k' }
# touch a file, using symbolic modes to set the permissions (equivalent to→˓0644)- file: path=/etc/foo.conf state=touch mode="u=rw,g=r,o=r"
360 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# touch the same file, but add/remove some permissions- file: path=/etc/foo.conf state=touch mode="u+rw,g-wx,o-rwx"
# create a directory if it doesn't exist- file: path=/etc/some_directory state=directory mode=0755
Notes
Note: See also copy, template, assemble
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
filesystem - Makes file system on block device
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
This module creates file system.
Options
Examples
# Create a ext2 filesystem on /dev/sdb1.- filesystem: fstype=ext2 dev=/dev/sdb1
# Create a ext4 filesystem on /dev/sdb1 and check disk blocks.- filesystem: fstype=ext4 dev=/dev/sdb1 opts="-cc"
1.6. Module Index 361
Ansible 1.2 Documentation, Release 0.01
Notes
Note: uses mkfs command
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
find - return a list of files based on specific criteria
New in version 2.0.
• Synopsis
• Options
• Examples
• Return Values
• This is a Core Module
Synopsis
Return a list files based on specific criteria. Multiple criteria are AND’d together.
Options
Examples
# Recursively find /tmp files older than 2 days- find: paths="/tmp" age="2d" recurse=yes
# Recursively find /tmp files older than 4 weeks and equal or greater than 1→˓megabyte- find: paths="/tmp" age="4w" size="1m" recurse=yes
# Recursively find /var/tmp files with last access time greater than 3600→˓seconds- find: paths="/var/tmp" age="3600" age_stamp=atime recurse=yes
# find /var/log files equal or greater than 10 megabytes ending with .old or→˓.log.gz- find: paths="/var/tmp" patterns="*.old,*.log.gz" size="10m"
362 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# find /var/log files equal or greater than 10 megabytes ending with .old or→˓.log.gz via regex- find: paths="/var/tmp" patterns="^.*?\.(?:old|log\.gz)$" size="10m" use_→˓regex=True
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
fireball - Enable fireball mode on remote node
• DEPRECATED
• Synopsis
DEPRECATED
in favor of SSH with ControlPersist
Synopsis
Modern SSH clients support ControlPersist which is just as fast as fireball was. Please enable that in ansible.cfg as areplacement for fireball. Removed in ansible 2.0.
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
firewalld - Manage arbitrary ports/services with firewalld
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• Notes
1.6. Module Index 363
Ansible 1.2 Documentation, Release 0.01
• This is an Extras Module
Synopsis
This module allows for addition or deletion of services and ports either tcp or udp in either running or permanentfirewalld rules.
Requirements
• firewalld >= 0.2.11
Options
Examples
- firewalld: service=https permanent=true state=enabled- firewalld: port=8081/tcp permanent=true state=disabled- firewalld: port=161-162/udp permanent=true state=enabled- firewalld: zone=dmz service=http permanent=true state=enabled- firewalld: rich_rule='rule service name="ftp" audit limit value="1/m"→˓accept' permanent=true state=enabled- firewalld: source='192.168.1.0/24' zone=internal state=enabled
Notes
Note: Not tested on any Debian based system.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
flowdock - Send a message to a flowdock
• Synopsis
• Options
• Examples
• This is an Extras Module
364 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
Send a message to a flowdock team inbox or chat using the push API (see https://www.flowdock.com/api/team-inboxand https://www.flowdock.com/api/chat)
Options
Examples
- flowdock: [email protected]='my cool app'msg='test from ansible'subject='test subject'
- flowdock: type=chattoken=AAAAAAexternal_user_name=testusermsg='test from ansible'tags=tag1,tag2,tag3
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
gc_storage - This module manages objects/buckets in Google Cloud Storage.
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• This is a Core Module
Synopsis
This module allows users to manage their objects/buckets in Google Cloud Storage. It allows upload and downloadoperations and can set some canned permissions. It also allows retrieval of URLs for objects for use in playbooks,and retrieval of string contents of objects. This module requires setting the default project in GCS prior to playbookusage. See https://developers.google.com/storage/docs/reference/v1/apiversion1 for information about setting the de-fault project.
1.6. Module Index 365
Ansible 1.2 Documentation, Release 0.01
Requirements
• python >= 2.6
• boto >= 2.9
Options
Examples
# upload some content- gc_storage: bucket=mybucket object=key.txt src=/usr/local/myfile.txt→˓mode=put permission=public-read
# upload some headers- gc_storage: bucket=mybucket object=key.txt src=/usr/local/myfile.txt→˓headers='{"Content-Encoding": "gzip"}'
# download some content- gc_storage: bucket=mybucket object=key.txt dest=/usr/local/myfile.txt→˓mode=get
# Download an object as a string to use else where in your playbook- gc_storage: bucket=mybucket object=key.txt mode=get_str
# Create an empty bucket- gc_storage: bucket=mybucket mode=create
# Create a bucket with key as directory- gc_storage: bucket=mybucket object=/my/directory/path mode=create
# Delete a bucket and all contents- gc_storage: bucket=mybucket mode=delete
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
gce - create or terminate GCE instances
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
366 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Notes
• This is a Core Module
Synopsis
Creates or terminates Google Compute Engine (GCE) instances. See https://cloud.google.com/products/compute-engine for an overview. Full install/configuration instructions for the gce* modules can be found in thecomments of ansible/test/gce_tests.py.
Requirements
• python >= 2.6
• apache-libcloud >= 0.13.3
Options
Examples
# Basic provisioning example. Create a single Debian 7 instance in the# us-central1-a Zone of n1-standard-1 machine type.- local_action:
module: gcename: test-instancezone: us-central1-amachine_type: n1-standard-1image: debian-7
# Example using defaults and with metadata to create a single 'foo' instance- local_action:
module: gcename: foometadata: '{"db":"postgres", "group":"qa", "id":500}'
# Launch instances from a control node, runs some tasks on the new instances,# and then terminate them- name: Create a sandbox instancehosts: localhostvars:
names: foo,barmachine_type: n1-standard-1image: debian-6zone: us-central1-aservice_account_email: [email protected]_file: /path/to/pem_fileproject_id: project-id
tasks:- name: Launch instances
local_action: gce instance_names={{names}} machine_type={{machine_type}→˓}
image={{image}} zone={{zone}} service_account_email={{→˓service_account_email }}
1.6. Module Index 367
Ansible 1.2 Documentation, Release 0.01
pem_file={{ pem_file }} project_id={{ project_id }}register: gce
- name: Wait for SSH to come uplocal_action: wait_for host={{item.public_ip}} port=22 delay=10
timeout=60 state=startedwith_items: {{gce.instance_data}}
- name: Configure instance(s)hosts: launchedsudo: Trueroles:
- my_awesome_role- my_awesome_tasks
- name: Terminate instanceshosts: localhostconnection: localtasks:
- name: Terminate instances that were previously launchedlocal_action:module: gcestate: 'absent'instance_names: {{gce.instance_names}}
Notes
Note: Either name or instance_names is required.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
gce_img - utilize GCE image resources
New in version 1.9.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
368 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
This module can create and delete GCE private images from gzipped compressed tarball containing raw disk data orfrom existing detached disks in any zone. https://cloud.google.com/compute/docs/images
Requirements
• python >= 2.6
• apache-libcloud
Options
Examples
# Create an image named test-image from the disk 'test-disk' in zone us-→˓central1-a.- gce_img:
name: test-imagesource: test-diskzone: us-central1-astate: present
# Create an image named test-image from a tarball in Google Cloud Storage.- gce_img:
name: test-imagesource: https://storage.googleapis.com/bucket/path/to/image.tgz
# Alternatively use the gs scheme- gce_img:
name: test-imagesource: gs://bucket/path/to/image.tgz
# Delete an image named test-image.- gce_img:
name: test-imagestate: absent
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
gce_lb - create/destroy GCE load-balancer resources
New in version 1.5.
1.6. Module Index 369
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• This is a Core Module
Synopsis
This module can create and destroy Google Compute Engine loadbalancer and httphealthcheck resources.The primary LB resource is the load_balancer resource and the health check parameters are all prefixed withhttphealthcheck. The full documentation for Google Compute Engine load balancing is at https://developers.google.com/compute/docs/load-balancing/. However, the ansible module simplifies the configuration by following the lib-cloud model. Full install/configuration instructions for the gce* modules can be found in the comments of ansi-ble/test/gce_tests.py.
Requirements
• python >= 2.6
• apache-libcloud >= 0.13.3
Options
Examples
# Simple example of creating a new LB, adding members, and a health check- local_action:
module: gce_lbname: testlbregion: us-central1members: ["us-central1-a/www-a", "us-central1-b/www-b"]httphealthcheck_name: hchttphealthcheck_port: 80httphealthcheck_path: "/up"
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
gce_net - create/destroy GCE networks and firewall rules
New in version 1.5.
370 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• This is a Core Module
Synopsis
This module can create and destroy Google Compute Engine networks and firewall rules https://developers.google.com/compute/docs/networking. The name parameter is reserved for referencing a network while the fwname parameteris used to reference firewall rules. IPv4 Address ranges must be specified using the CIDR http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing format. Full install/configuration instructions for the gce* modules can be found inthe comments of ansible/test/gce_tests.py.
Requirements
• python >= 2.6
• apache-libcloud >= 0.13.3
Options
Examples
# Simple example of creating a new network- local_action:
module: gce_netname: privatenetipv4_range: '10.240.16.0/24'
# Simple example of creating a new firewall rule- local_action:
module: gce_netname: privatenetfwname: all-web-webproxyallowed: tcp:80,8080src_tags: ["web", "proxy"]
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 371
Ansible 1.2 Documentation, Release 0.01
gce_pd - utilize GCE persistent disk resources
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• This is a Core Module
Synopsis
This module can create and destroy unformatted GCE persistent disks https://developers.google.com/compute/docs/disks#persistentdisks. It also supports attaching and detaching disks from running instances. Full install/configurationinstructions for the gce* modules can be found in the comments of ansible/test/gce_tests.py.
Requirements
• python >= 2.6
• apache-libcloud >= 0.13.3
Options
Examples
# Simple attachment action to an existing instance- local_action:
module: gce_pdinstance_name: notlocalhostsize_gb: 5name: pd
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
gce_tag - add or remove tag(s) to/from GCE instance
New in version 2.0.
372 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
This module can add or remove tags https://cloud.google.com/compute/docs/instances/#tags to/from GCE instance.
Requirements
• python >= 2.6
• apache-libcloud
Options
Examples
# Add tags 'http-server', 'https-server', 'staging' to instance name→˓'staging-server' in zone us-central1-a.- gce_tag:
instance_name: staging-servertags: http-server,https-server,stagingzone: us-central1-astate: present
# Remove tags 'foo', 'bar' from instance 'test-server' in default zone (us-→˓central1-a)- gce_tag:
instance_name: test-servertags: foo,barstate: absent
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
gem - Manage Ruby gems
1.6. Module Index 373
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
Manage installation and uninstallation of Ruby gems.
Options
Examples
# Installs version 1.0 of vagrant.- gem: name=vagrant version=1.0 state=present
# Installs latest available version of rake.- gem: name=rake state=latest
# Installs rake version 1.0 from a local gem on disk.- gem: name=rake gem_source=/path/to/gems/rake-1.0.gem state=present
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
get_url - Downloads files from HTTP, HTTPS, or FTP to node
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
Downloads files from HTTP, HTTPS, or FTP to the remote server. The remote server must have direct access to theremote resource. By default, if an environment variable <protocol>_proxy is set on the target host, requestswill be sent through that proxy. This behaviour can be overridden by setting a variable for this task (see setting theenvironment), or by using the use_proxy option. HTTP redirects can redirect from HTTP to HTTPS so you should besure that your proxy environment for both protocols is correct.
374 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
- name: download foo.confget_url: url=http://example.com/path/file.conf dest=/etc/foo.conf mode=0440
- name: download file and force basic authget_url: url=http://example.com/path/file.conf dest=/etc/foo.conf force_
→˓basic_auth=yes
- name: download file with custom HTTP headersget_url: url=http://example.com/path/file.conf dest=/etc/foo.conf headers=
→˓'key:value,key:value'
- name: download file with checkget_url: url=http://example.com/path/file.conf dest=/etc/foo.conf
→˓checksum=sha256:b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944cget_url: url=http://example.com/path/file.conf dest=/etc/foo.conf
→˓checksum=md5:66dffb5228a211e61d6d7ef4a86f5758
- name: download file from a file pathget_url: url="file:///tmp/afile.txt" dest=/tmp/afilecopy.txt
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
getent - a wrapper to the unix getent utility
New in version 1.8.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Runs getent against one of it’s various databases and returns information into the host’s facts, in a getent_<database>prefixed variable
1.6. Module Index 375
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# get root user info- getent: database=passwd key=root- debug: var=getent_passwd
# get all groups- getent: database=group split=':'- debug: var=getent_group
# get all hosts, split by tab- getent: database=hosts- debug: var=getent_hosts
# get http service info, no error if missing- getent: database=services key=http fail_key=False- debug: var=getent_services
# get user password hash (requires sudo/root)- getent: database=shadow key=www-data split=:- debug: var=getent_shadow
Notes
Note: Not all databases support enumeration, check system documentation for details
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
git - Deploy software (or files) from git checkouts
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
376 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
Manage git checkouts of repositories to deploy files or software.
Requirements
• git (the command line tool)
Options
Examples
# Example git checkout from Ansible Playbooks- git: repo=git://foosball.example.org/path/to/repo.git
dest=/srv/checkoutversion=release-0.22
# Example read-write git checkout from github- git: repo=ssh://[email protected]/mylogin/hello.git dest=/home/mylogin/hello
# Example just ensuring the repo checkout exists- git: repo=git://foosball.example.org/path/to/repo.git dest=/srv/checkout→˓update=no
# Example just get information about the repository whether or not it has# already been cloned locally.- git: repo=git://foosball.example.org/path/to/repo.git dest=/srv/checkout→˓clone=no update=no
# Example checkout a github repo and use refspec to fetch all pull requests- git: repo=https://github.com/ansible/ansible-examples.git dest=/src/→˓ansible-examples refspec=+refs/pull/*:refs/heads/*
Notes
Note: If the task seems to be hanging, first verify remote host is in known_hosts. SSH will prompt user toauthorize the first contact with a remote host. To avoid this prompt, one solution is to add the remote host public keyin /etc/ssh/ssh_known_hosts before calling the git module, with the following command: ssh-keyscan -Hremote_host.com >> /etc/ssh/ssh_known_hosts.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 377
Ansible 1.2 Documentation, Release 0.01
github_hooks - Manages github service hooks.
New in version 1.4.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Adds service hooks and removes service hooks that have an error status.
Options
Examples
# Example creating a new service hook. It ignores duplicates.- github_hooks: action=create hookurl=http://11.111.111.111:2222 user={{→˓gituser }} oauthkey={{ oauthkey }} repo=https://api.github.com/repos/→˓pcgentry/Github-Auto-Deploy
# Cleaning all hooks for this repo that had an error on the last update.→˓Since this works for all hooks in a repo it is probably best that this→˓would be called from a handler.- local_action: github_hooks action=cleanall user={{ gituser }} oauthkey={{→˓oauthkey }} repo={{ repo }}
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
glance_image - Add/Delete images from glance
• DEPRECATED
• Synopsis
• Requirements
• Options
• Examples
378 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
DEPRECATED
Deprecated in 1.10. Use os_image instead
Synopsis
Add or Remove images from the glance repository.
Requirements
• python >= 2.6
• python-glanceclient
• python-keystoneclient
Options
Examples
# Upload an image from an HTTP URL- glance_image: login_username=admin
login_password=passmelogin_tenant_name=adminname=cirroscontainer_format=baredisk_format=qcow2state=presentcopy_from=http:launchpad.net/cirros/trunk/0.3.0/+download/
→˓cirros-0.3.0-x86_64-disk.img
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
gluster_volume - Manage GlusterFS volumes
New in version 1.9.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Create, remove, start, stop and tune GlusterFS volumes
1.6. Module Index 379
Ansible 1.2 Documentation, Release 0.01
Options
Examples
- name: create gluster volumegluster_volume: state=present name=test1 bricks=/bricks/brick1/g1
→˓rebalance=yes cluster="192.168.1.10,192.168.1.11"run_once: true
- name: tunegluster_volume: state=present name=test1 options='{performance.cache-size:
→˓256MB}'
- name: start gluster volumegluster_volume: state=started name=test1
- name: limit usagegluster_volume: state=present name=test1 directory=/foo quota=20.0MB
- name: stop gluster volumegluster_volume: state=stopped name=test1
- name: remove gluster volumegluster_volume: state=absent name=test1
- name: create gluster volume with multiple bricksgluster_volume: state=present name=test2 bricks="/bricks/brick1/g2,/bricks/
→˓brick2/g2" cluster="192.168.1.10,192.168.1.11"run_once: true
Notes
Note: Requires cli tools for GlusterFS on servers
Note: Will add new bricks, but not remove them
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
group - Add or remove groups
• Synopsis
380 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Requirements
• Options
• Examples
• This is a Core Module
Synopsis
Manage presence of groups on a host.
Requirements
• groupadd
• groupdel
• groupmod
Options
Examples
# Example group command from Ansible Playbooks- group: name=somegroup state=present
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
group_by - Create Ansible groups based on facts
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Use facts to create ad-hoc groups that can be used later in a playbook.
1.6. Module Index 381
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Create groups based on the machine architecture- group_by: key=machine_{{ ansible_machine }}# Create groups like 'kvm-host'- group_by: key=virt_{{ ansible_virtualization_type }}_{{ ansible_→˓virtualization_role }}
Notes
Note: Spaces in group names are converted to dashes ‘-‘.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
grove - Sends a notification to a grove.io channel
New in version 1.4.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
The grove module sends a message for a service to a Grove.io channel.
Options
Examples
- grove: >channel_token=6Ph62VBBJOccmtTPZbubiPzdrhipZXtgservice=my-appmessage=deployed {{ target }}
382 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
hall - Send notification to Hall
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
The hall module connects to the https://hall.com messaging API and allows you to deliver notication messages torooms.
Options
Examples
- name: Send Hall notifiationlocal_action:
module: hallroom_token: <hall room integration token>title: Nginxmsg: Created virtual host file on {{ inventory_hostname }}
- name: Send Hall notification if EC2 servers were created.when: ec2.instances|length > 0local_action:
module: hallroom_token: <hall room integration token>title: Server Creationmsg: "Created EC2 instance {{ item.id }} of type {{ item.instance_type }}
→˓.\nInstance can be reached at {{ item.public_ip }} in the {{ item.region }}→˓ region."with_items: ec2.instances
This is an Extras Module
For more information on what this means please read Extras Modules
1.6. Module Index 383
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
haproxy - Enable, disable, and set weights for HAProxy backend servers using socket commands.
New in version 1.9.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Enable, disable, and set weights for HAProxy backend servers using socket commands.
Options
Examples
# disable server in 'www' backend pool- haproxy: state=disabled host={{ inventory_hostname }} backend=www
# disable server without backend pool name (apply to all available backend→˓pool)- haproxy: state=disabled host={{ inventory_hostname }}
# disable server, provide socket file- haproxy: state=disabled host={{ inventory_hostname }} socket=/var/run/→˓haproxy.sock backend=www
# disable server, provide socket file, wait until status reports in→˓maintenance- haproxy: state=disabled host={{ inventory_hostname }} socket=/var/run/→˓haproxy.sock backend=www wait=yes
# disable backend server in 'www' backend pool and drop open sessions to it- haproxy: state=disabled host={{ inventory_hostname }} backend=www socket=/→˓var/run/haproxy.sock shutdown_sessions=true
# enable server in 'www' backend pool- haproxy: state=enabled host={{ inventory_hostname }} backend=www
# enable server in 'www' backend pool wait until healthy- haproxy: state=enabled host={{ inventory_hostname }} backend=www wait=yes
# enable server in 'www' backend pool wait until healthy. Retry 10 times→˓with intervals of 5 seconds to retrieve the health
384 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- haproxy: state=enabled host={{ inventory_hostname }} backend=www wait=yes→˓wait_retries=10 wait_interval=5
# enable server in 'www' backend pool with change server(s) weight- haproxy: state=enabled host={{ inventory_hostname }} socket=/var/run/→˓haproxy.sock weight=10 backend=www
author: "Ravi Bhure (@ravibhure)"
Notes
Note: Enable and disable commands are restricted and can only be issued on sockets configured for level ‘admin’. Forexample, you can add the line ‘stats socket /var/run/haproxy.sock level admin’ to the general section of haproxy.cfg.See http://haproxy.1wt.eu/download/1.5/doc/configuration.txt.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
hg - Manages Mercurial (hg) repositories.
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Manages Mercurial (hg) repositories. Supports SSH, HTTP/S and local address.
Options
Examples
# Ensure the current working copy is inside the stable branch and deletes→˓untracked files if any.- hg: repo=https://bitbucket.org/user/repo1 dest=/home/user/repo1→˓revision=stable purge=yes
1.6. Module Index 385
Ansible 1.2 Documentation, Release 0.01
Notes
Note: If the task seems to be hanging, first verify remote host is in known_hosts. SSH will prompt user toauthorize the first contact with a remote host. To avoid this prompt, one solution is to add the remote host publickey in /etc/ssh/ssh_known_hosts before calling the hg module, with the following command: ssh-keyscanremote_host.com >> /etc/ssh/ssh_known_hosts.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
hipchat - Send a message to hipchat.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Send a message to hipchat
Options
Examples
- hipchat: room=notify msg="Ansible task finished"
# Use Hipchat API version 2
- hipchat:api: "https://api.hipchat.com/v2/"token: OAUTH2_TOKENroom: notifymsg: "Ansible task finished"
This is an Extras Module
For more information on what this means please read Extras Modules
386 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
homebrew - Package manager for Homebrew
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manages Homebrew packages
Options
Examples
# Install formula foo with 'brew' in default path (C(/usr/local/bin))- homebrew: name=foo state=present
# Install formula foo with 'brew' in alternate path C(/my/other/location/bin)- homebrew: name=foo path=/my/other/location/bin state=present
# Update homebrew first and install formula foo with 'brew' in default path- homebrew: name=foo state=present update_homebrew=yes
# Update homebrew first and upgrade formula foo to latest available with→˓'brew' in default path- homebrew: name=foo state=latest update_homebrew=yes
# Update homebrew and upgrade all packages- homebrew: update_homebrew=yes upgrade_all=yes
# Miscellaneous other examples- homebrew: name=foo state=head- homebrew: name=foo state=linked- homebrew: name=foo state=absent- homebrew: name=foo,bar state=absent- homebrew: name=foo state=present install_options=with-baz,enable-debug
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 387
Ansible 1.2 Documentation, Release 0.01
homebrew_cask - Install/uninstall homebrew casks.
New in version 1.6.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manages Homebrew casks.
Options
Examples
- homebrew_cask: name=alfred state=present- homebrew_cask: name=alfred state=absent
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
homebrew_tap - Tap a Homebrew repository.
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Tap external Homebrew repositories.
388 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Requirements
• homebrew
Options
Examples
homebrew_tap: tap=homebrew/dupes state=presenthomebrew_tap: tap=homebrew/dupes state=absenthomebrew_tap: tap=homebrew/dupes,homebrew/science state=present
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
hostname - Manage hostname
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• This is a Core Module
Synopsis
Set system’s hostname. Currently implemented on Debian, Ubuntu, Fedora, RedHat, openSUSE, Linaro, Scientifi-cLinux, Arch, CentOS, AMI. Any distribution that uses systemd as their init system. Note, this module does NOTmodify /etc/hosts. You need to modify it yourself using other modules like template or replace.
Requirements
• hostname
Options
1.6. Module Index 389
Ansible 1.2 Documentation, Release 0.01
Examples
- hostname: name=web01
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
htpasswd - manage user files for basic authentication
New in version 1.3.
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Add and remove username/password entries in a password file using htpasswd. This is used by web servers such asApache and Nginx for basic authentication.
Options
Examples
# Add a user to a password file and ensure permissions are set- htpasswd: path=/etc/nginx/passwdfile name=janedoe password=9s36?;fyNp→˓owner=root group=www-data mode=0640# Remove a user from a password file- htpasswd: path=/etc/apache2/passwdfile name=foobar state=absent# Add a user to a password file suitable for use by libpam-pwdfile- htpasswd: path=/etc/mail/passwords name=alex password=oedu2eGh crypt_→˓scheme=md5_crypt
Notes
Note: This module depends on the passlib Python library, which needs to be installed on all target systems.
390 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: On Debian, Ubuntu, or Fedora: install python-passlib.
Note: On RHEL or CentOS: Enable EPEL, then install python-passlib.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
iam - Manage IAM users, groups, roles and keys
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Allows for the management of IAM users, groups, roles and access keys.
Requirements
• python >= 2.6
• boto
Options
Examples
# Basic user creation exampletasks:- name: Create two new IAM users with API keysiam:
iam_type: username: "{{ item }}"
1.6. Module Index 391
Ansible 1.2 Documentation, Release 0.01
state: presentpassword: "{{ temp_pass }}"access_key_state: create
with_items:- jcleese- mpython
# Advanced example, create two new groups and add the pre-existing user# jdavila to both groups.task:- name: Create Two Groups, Mario and Luigiiam:
iam_type: groupname: "{{ item }}"state: present
with_items:- Mario- Luigi
register: new_groups
- name:iam:
iam_type: username: jdavilastate: updategroups: "{{ item.created_group.group_name }}"
with_items: new_groups.results
Notes
Note: Currently boto does not support the removal of Managed Policies, the module will error out if youruser/group/role has managed policies when you try to do state=absent. They will need to be removed manually.
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
392 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
iam_cert - Manage server certificates for use on ELBs and CloudFront
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Allows for the management of server certificates
Requirements
• boto
• python >= 2.6
Options
Examples
# Basic server certificate uploadtasks:- name: Upload Certificateiam_cert:
name: very_sslstate: presentcert: somecert.pemkey: privcertkeycert_chain: myverytrustedchain
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,
1.6. Module Index 393
Ansible 1.2 Documentation, Release 0.01
AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
iam_policy - Manage IAM policies for users, groups, and roles
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Allows uploading or removing IAM policies for IAM users, groups or roles.
Requirements
• python >= 2.6
• boto
Options
394 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
# Create and policy with the name of 'Admin' to the group 'administrators'tasks:- name: Create two new IAM users with API keysiam_policy:
iam_type: groupiam_name: administratorspolicy_name: Adminstate: presentpolicy_document: admin_policy.json
# Advanced example, create two new groups and add a READ-ONLY policy to both# groups.task:- name: Create Two Groups, Mario and Luigiiam:
iam_type: groupname: "{{ item }}"state: present
with_items:- Mario- Luigi
register: new_groups
- name:iam_policy:
iam_type: groupiam_name: "{{ item.created_group.group_name }}"policy_name: "READ-ONLY"policy_document: readonlypolicy.jsonstate: present
with_items: new_groups.results
# Create a new S3 policy with prefix per usertasks:- name: Create S3 policy from templateiam_policy:
iam_type: useriam_name: "{{ item.user }}"policy_name: "s3_limited_access_{{ item.prefix }}"state: presentpolicy_json: " {{ lookup( 'template', 's3_policy.json.j2') }} "with_items:- user: s3_userprefix: s3_user_prefix
Notes
Note: Currently boto does not support the removal of Managed Policies, the module will not work removing/addingmanaged policies.
Note: If parameters are not set within the module, the following environment variables can be used in decreasing order
1.6. Module Index 395
Ansible 1.2 Documentation, Release 0.01
of precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
include_vars - Load variables from files, dynamically within a task.
New in version 1.4.
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
Loads variables from a YAML/JSON file dynamically during task runtime. It can work with conditionals, or use hostspecific variables to determine the path name to load from.
Options
Examples
# Conditionally decide to load in variables when x is 0, otherwise do not.- include_vars: contingency_plan.ymlwhen: x == 0
# Load a variable file based on the OS type, or a default if not found.- include_vars: "{{ item }}"with_first_found:- "{{ ansible_distribution }}.yml"
396 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- "{{ ansible_os_family }}.yml"- "default.yml"
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ini_file - Tweak settings in INI files
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Manage (add, remove, change) individual settings in an INI-style file without having to manage the file as a wholewith, say, template or assemble. Adds missing sections if they don’t exist. Before version 2.0, comments are discardedwhen the source file is read, and therefore will not show up in the destination file.
Requirements
• ConfigParser
Options
Examples
# Ensure "fav=lemonade is in section "[drinks]" in specified file- ini_file: dest=/etc/conf section=drinks option=fav value=lemonade→˓mode=0600 backup=yes
- ini_file: dest=/etc/anotherconfsection=drinksoption=temperaturevalue=coldbackup=yes
1.6. Module Index 397
Ansible 1.2 Documentation, Release 0.01
Notes
Note: While it is possible to add an option without specifying a value, this makes no sense.
Note: A section named default cannot be added by the module, but if it exists, individual options within thesection can be updated. (This is a limitation of Python’s ConfigParser.) Either use template to create a base INI filewith a [default] section, or use lineinfile to add the missing line.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ipify_facts - Retrieve the public IP of your internet gateway.
New in version 2.0.
• Synopsis
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
If behind NAT and need to know the public IP of your internet gateway.
Options
Examples
# Gather IP facts from ipify.org- name: get my public IPipify_facts:
# Gather IP facts from your own ipify service endpoint- name: get my public IPipify_facts: api_url=http://api.example.com/ipify
398 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Visit https://www.ipify.org to get more information.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
iptables - Modify the systems iptables
New in version 2.0.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Iptables is used to set up, maintain, and inspect the tables of IP packet filter rules in the Linux kernel. This module doesnot handle the saving and/or loading of rules, but rather only manipulates the current rules that are present in memory.This is the same as the behaviour of the “iptables” and “ip6tables” command which this module uses internally.
Options
Examples
# Block specific IP- iptables: chain=INPUT source=8.8.8.8 jump=DROPbecome: yes
# Forward port 80 to 8600- iptables: table=nat chain=PREROUTING in_interface=eth0 protocol=tcp→˓match=tcp destination_port=80 jump=REDIRECT to_ports=8600 comment=→˓"Redirect web traffic to port 8600"become: yes
1.6. Module Index 399
Ansible 1.2 Documentation, Release 0.01
# Allow related and established connections- iptables: chain=INPUT ctstate=ESTABLISHED,RELATED jump=ACCEPTbecome: yes
Notes
Note: This module just deals with individual rules. If you need advanced chaining of rules the recommended way isto template the iptables restore file.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
irc - Send a message to an IRC channel
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Send a message to an IRC channel. This is a very simplistic implementation.
Requirements
• socket
Options
Examples
- irc: server=irc.example.net channel="#t1" msg="Hello world"
- local_action: irc port=6669server="irc.example.net"
400 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
channel="#t1"msg="All finished at {{ ansible_date_time.iso8601 }}"color=rednick=ansibleIRC
- local_action: irc port=6669server="irc.example.net"channel="#t1"nick_to=["nick1", "nick2"]msg="All finished at {{ ansible_date_time.iso8601 }}"color=rednick=ansibleIRC
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
jabber - Send a message to jabber user or chat room
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Send a message to jabber
Requirements
• python xmpp (xmpppy)
Options
Examples
# send a message to a user- jabber: [email protected]
[email protected]="Ansible task finished"
1.6. Module Index 401
Ansible 1.2 Documentation, Release 0.01
# send a message to a room- jabber: [email protected]
[email protected]/ansiblebotmsg="Ansible task finished"
# send a message, specifying the host and port- jabber [email protected]
host=talk.example.netport=5223password=secretto=mychaps@example.netmsg="Ansible task finished"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
jboss - deploy applications to JBoss
New in version 1.4.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Deploy applications to JBoss standalone using the filesystem
Options
Examples
# Deploy a hello world application- jboss: src=/tmp/hello-1.0-SNAPSHOT.war deployment=hello.war state=present# Update the hello world application- jboss: src=/tmp/hello-1.1-SNAPSHOT.war deployment=hello.war state=present# Undeploy the hello world application- jboss: deployment=hello.war state=absent
402 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Notes
Note: The JBoss standalone deployment-scanner has to be enabled in standalone.xml
Note: Ensure no identically named application is deployed through the JBoss CLI
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
jira - create and modify issues in a JIRA instance
New in version 1.6.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Create and modify issues in a JIRA instance.
Options
Examples
# Create a new issue and add a comment to it:- name: Create an issuejira: uri={{server}} username={{user}} password={{pass}}
project=ANS operation=createsummary="Example Issue" description="Created using Ansible"
→˓issuetype=Taskregister: issue
- name: Comment on issuejira: uri={{server}} username={{user}} password={{pass}}
issue={{issue.meta.key}} operation=commentcomment="A comment added by Ansible"
1.6. Module Index 403
Ansible 1.2 Documentation, Release 0.01
# Assign an existing issue using edit- name: Assign an issue using free-form fieldsjira: uri={{server}} username={{user}} password={{pass}}
issue={{issue.meta.key}} operation=editassignee=ssmith
# Create an issue with an existing assignee- name: Create an assigned issuejira: uri={{server}} username={{user}} password={{pass}}
project=ANS operation=createsummary="Assigned issue" description="Created and assigned using
→˓Ansible"issuetype=Task assignee=ssmith
# Edit an issue using free-form fields- name: Set the labels on an issue using free-form fieldsjira: uri={{server}} username={{user}} password={{pass}}
issue={{issue.meta.key}} operation=editargs: { fields: {labels: ["autocreated", "ansible"]}}
- name: Set the labels on an issue, YAML versionjira: uri={{server}} username={{user}} password={{pass}}
issue={{issue.meta.key}} operation=editargs:
fields:labels:- "autocreated"- "ansible"- "yaml"
# Retrieve metadata for an issue and use it to create an account- name: Get an issuejira: uri={{server}} username={{user}} password={{pass}}
project=ANS operation=fetch issue="ANS-63"register: issue
- name: Create a unix account for the reportersudo: trueuser: name="{{issue.meta.fields.creator.name}}" comment="{{issue.meta.
→˓fields.creator.displayName}}"
# Transition an issue by target status- name: Close the issuejira: uri={{server}} username={{user}} password={{pass}}
issue={{issue.meta.key}} operation=transition status="Done"
Notes
Note: Currently this only works with basic-auth.
404 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
kernel_blacklist - Blacklist kernel modules
New in version 1.4.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Add or remove kernel modules from blacklist.
Options
Examples
# Blacklist the nouveau driver module- kernel_blacklist: name=nouveau state=present
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
keystone_user - Manage OpenStack Identity (keystone) users, tenants and roles
• DEPRECATED
• Synopsis
• Requirements
• Options
• Examples
1.6. Module Index 405
Ansible 1.2 Documentation, Release 0.01
DEPRECATED
Deprecated in 2.0. Use os_user instead
Synopsis
Manage users,tenants, roles from OpenStack.
Requirements
• python >= 2.6
• python-keystoneclient
Options
Examples
# Create a tenant- keystone_user: tenant=demo tenant_description="Default Tenant"
# Create a user- keystone_user: user=john tenant=demo password=secrete
# Apply the admin role to the john user in the demo tenant- keystone_user: role=admin user=john tenant=demo
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
known_hosts - Add or remove a host from the known_hosts file
New in version 1.9.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
The known_hosts module lets you add or remove a host from the known_hosts file. This is useful if you’re goingto want to use the git module over ssh, for example. If you have a very large number of host keys to manage, you willfind the template module more useful.
406 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Example using with_file to set the system known_hosts file- name: tell the host about our servers it might want to ssh toknown_hosts: path='/etc/ssh/ssh_known_hosts'
name='foo.com.invalid'key="{{ lookup('file', 'pubkeys/foo.com.invalid') }}"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
layman - Manage Gentoo overlays
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Uses Layman to manage an additional repositories for the Portage package manager on Gentoo Linux. Please notethat Layman must be installed on a managed node prior using this module.
Requirements
• python >= 2.6
• layman python module
Options
Examples
1.6. Module Index 407
Ansible 1.2 Documentation, Release 0.01
# Install the overlay 'mozilla' which is on the central overlays list.- layman: name=mozilla
# Install the overlay 'cvut' from the specified alternative list.- layman: name=cvut list_url=http://raw.github.com/cvut/gentoo-overlay/→˓master/overlay.xml
# Update (sync) the overlay 'cvut', or install if not installed yet.- layman: name=cvut list_url=http://raw.github.com/cvut/gentoo-overlay/→˓master/overlay.xml state=updated
# Update (sync) all of the installed overlays.- layman: name=ALL state=updated
# Uninstall the overlay 'cvut'.- layman: name=cvut state=absent
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
librato_annotation - create an annotation in librato
New in version 1.6.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Create an annotation event on the given annotation stream :name. If the annotation stream does not exist, it will becreated automatically
Options
Examples
# Create a simple annotation event with a source- librato_annotation:
user: [email protected]_key: XXXXXXXXXXXXXXXXXtitle: 'App Config Change'
408 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
source: 'foo.bar'description: 'This is a detailed description of the config change'
# Create an annotation that includes a link- librato_annotation:
user: [email protected]_key: XXXXXXXXXXXXXXXXXXname: 'code.deploy'title: 'app code deploy'description: 'this is a detailed description of a deployment'links:
- { rel: 'example', href: 'http://www.example.com/deploy' }
# Create an annotation with a start_time and end_time- librato_annotation:
user: [email protected]_key: XXXXXXXXXXXXXXXXXXname: 'maintenance'title: 'Maintenance window'description: 'This is a detailed description of maintenance'start_time: 1395940006end_time: 1395954406
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
lineinfile - Ensure a particular line is in a file, or replace an existing line using a back-referencedregular expression.
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
This module will search a file for a line, and ensure that it is present or absent. This is primarily useful when you wantto change a single line in a file only. See the replace module if you want to change multiple, similar lines; for othercases, see the copy or template modules.
Options
1.6. Module Index 409
Ansible 1.2 Documentation, Release 0.01
Examples
- lineinfile: dest=/etc/selinux/config regexp=^SELINUX=→˓line=SELINUX=enforcing
- lineinfile: dest=/etc/sudoers state=absent regexp="^%wheel"
- lineinfile: dest=/etc/hosts regexp='^127\.0\.0\.1' line='127.0.0.1→˓localhost' owner=root group=root mode=0644
- lineinfile: dest=/etc/httpd/conf/httpd.conf regexp="^Listen " insertafter=→˓"^#Listen " line="Listen 8080"
- lineinfile: dest=/etc/services regexp="^# port for http" insertbefore="^→˓www.*80/tcp" line="# port for http by default"
# Add a line to a file if it does not exist, without passing regexp- lineinfile: dest=/tmp/testfile line="192.168.1.99 foo.lab.net foo"
# Fully quoted because of the ': ' on the line. See the Gotchas in the YAML→˓docs.- lineinfile: "dest=/etc/sudoers state=present regexp='^%wheel' line='%wheel→˓ALL=(ALL) NOPASSWD: ALL'"
- lineinfile: dest=/opt/jboss-as/bin/standalone.conf regexp='^(.*)Xms(\d+)m(.→˓*)$' line='\1Xms${xms}m\3' backrefs=yes
# Validate the sudoers file before saving- lineinfile: dest=/etc/sudoers state=present regexp='^%ADMIN ALL\=' line='→˓%ADMIN ALL=(ALL) NOPASSWD:ALL' validate='visudo -cf %s'
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
linode - create / delete / stop / restart an instance in Linode Public Cloud
New in version 1.3.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
410 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
creates / deletes a Linode Public Cloud instance and optionally waits for it to be ‘running’.
Requirements
• python >= 2.6
• linode-python
• pycurl
Options
Examples
# Create a server- local_action:
module: linodeapi_key: 'longStringFromLinodeApi'name: linode-test1plan: 1datacenter: 2distribution: 99password: 'superSecureRootPassword'ssh_pub_key: 'ssh-rsa qwerty'swap: 768wait: yeswait_timeout: 600state: present
# Ensure a running server (create if missing)- local_action:
module: linodeapi_key: 'longStringFromLinodeApi'name: linode-test1linode_id: 12345678plan: 1datacenter: 2distribution: 99password: 'superSecureRootPassword'ssh_pub_key: 'ssh-rsa qwerty'swap: 768wait: yeswait_timeout: 600state: present
# Delete a server- local_action:
module: linodeapi_key: 'longStringFromLinodeApi'name: linode-test1linode_id: 12345678state: absent
1.6. Module Index 411
Ansible 1.2 Documentation, Release 0.01
# Stop a server- local_action:
module: linodeapi_key: 'longStringFromLinodeApi'name: linode-test1linode_id: 12345678state: stopped
# Reboot a server- local_action:
module: linodeapi_key: 'longStringFromLinodeApi'name: linode-test1linode_id: 12345678state: restarted
Notes
Note: LINODE_API_KEY env variable can be used instead
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
lldp - get details reported by lldp
New in version 1.6.
• Synopsis
• Requirements
• Examples
• Notes
• This is an Extras Module
Synopsis
Reads data out of lldpctl
Requirements
• lldpctl
412 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
# Retrieve switch/port information- name: Gather information from lldp
lldp:
- name: Print each switch/portdebug: msg="{{ lldp[item]['chassis']['name'] }} / {{ lldp[item]['port'][
→˓'ifalias'] }}with_items: lldp.keys()
# TASK: [Print each switch/port]→˓***********************************************************# ok: [10.13.0.22] => (item=eth2) => {"item": "eth2", "msg": "switch1.→˓example.com / Gi0/24"}# ok: [10.13.0.22] => (item=eth1) => {"item": "eth1", "msg": "switch2.→˓example.com / Gi0/3"}# ok: [10.13.0.22] => (item=eth0) => {"item": "eth0", "msg": "switch3.→˓example.com / Gi0/3"}
Notes
Note: Requires lldpd running and lldp enabled on switches
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
locale_gen - Creates or removes locales.
New in version 1.6.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manages locales by editing /etc/locale.gen and invoking locale-gen.
1.6. Module Index 413
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Ensure a locale exists.- locale_gen: name=de_CH.UTF-8 state=present
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
logentries - Module for tracking logs via logentries.com
New in version 1.6.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Sends logs to LogEntries in realtime
Options
Examples
- logentries: path=/var/log/nginx/access.log state=present name=nginx-access-→˓log- logentries: path=/var/log/nginx/error.log state=absent
Notes
Note: Requires the LogEntries agent which can be installed following the instructions at logentries.com
414 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
lvg - Configure LVM volume groups
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
This module creates, removes or resizes volume groups.
Options
Examples
# Create a volume group on top of /dev/sda1 with physical extent size = 32MB.- lvg: vg=vg.services pvs=/dev/sda1 pesize=32
# Create or resize a volume group on top of /dev/sdb1 and /dev/sdc5.# If, for example, we already have VG vg.services on top of /dev/sdb1,# this VG will be extended by /dev/sdc5. Or if vg.services was created on# top of /dev/sda5, we first extend it with /dev/sdb1 and /dev/sdc5,# and then reduce by /dev/sda5.- lvg: vg=vg.services pvs=/dev/sdb1,/dev/sdc5
# Remove a volume group with name vg.services.- lvg: vg=vg.services state=absent
Notes
Note: module does not modify PE size for already present volume group
This is an Extras Module
For more information on what this means please read Extras Modules
1.6. Module Index 415
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
lvol - Configure LVM logical volumes
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
This module creates, removes or resizes logical volumes.
Options
Examples
# Create a logical volume of 512m.- lvol: vg=firefly lv=test size=512
# Create a logical volume of 512g.- lvol: vg=firefly lv=test size=512g
# Create a logical volume the size of all remaining space in the volume group- lvol: vg=firefly lv=test size=100%FREE
# Create a logical volume with special options- lvol: vg=firefly lv=test size=512g opts="-r 16"
# Extend the logical volume to 1024m.- lvol: vg=firefly lv=test size=1024
# Reduce the logical volume to 512m- lvol: vg=firefly lv=test size=512 force=yes
# Remove the logical volume.- lvol: vg=firefly lv=test state=absent force=yes
Notes
Note: Filesystems on top of the volume are not resized.
416 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
lxc_container - Manage LXC Containers
New in version 1.8.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Management of LXC containers
Requirements
• lxc >= 1.0 # OS package
• python >= 2.6 # OS Package
• lxc-python2 >= 0.1 # PIP Package from https://github.com/lxc/python2-lxc
Options
Examples
- name: Create a started containerlxc_container:
name: test-container-startedcontainer_log: truetemplate: ubuntustate: startedtemplate_options: --release trusty
- name: Create a stopped containerlxc_container:
name: test-container-stoppedcontainer_log: truetemplate: ubuntu
1.6. Module Index 417
Ansible 1.2 Documentation, Release 0.01
state: stoppedtemplate_options: --release trusty
- name: Create a frozen containerlxc_container:
name: test-container-frozencontainer_log: truetemplate: ubuntustate: frozentemplate_options: --release trustycontainer_command: |echo 'hello world.' | tee /opt/started-frozen
# Create filesystem container, configure it, and archive it, and start it.- name: Create filesystem containerlxc_container:
name: test-container-configbacking_store: dircontainer_log: truetemplate: ubuntustate: startedarchive: truearchive_compression: nonecontainer_config:- "lxc.aa_profile=unconfined"- "lxc.cgroup.devices.allow=a *:* rmw"
template_options: --release trusty
# Create an lvm container, run a complex command in it, add additional# configuration to it, create an archive of it, and finally leave the→˓container# in a frozen state. The container archive will be compressed using bzip2- name: Create a frozen lvm containerlxc_container:
name: test-container-lvmcontainer_log: truetemplate: ubuntustate: frozenbacking_store: lvmtemplate_options: --release trustycontainer_command: |apt-get updateapt-get install -y vim lxc-devecho 'hello world.' | tee /opt/startedif [[ -f "/opt/started" ]]; then
echo 'hello world.' | tee /opt/found-startedfi
container_config:- "lxc.aa_profile=unconfined"- "lxc.cgroup.devices.allow=a *:* rmw"
archive: truearchive_compression: bzip2
register: lvm_container_info
- name: Debug info on container "test-container-lvm"debug: var=lvm_container_info
- name: Run a command in a container and ensure its in a "stopped" state.
418 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
lxc_container:name: test-container-startedstate: stoppedcontainer_command: |
echo 'hello world.' | tee /opt/stopped
- name: Run a command in a container and ensure its it in a "frozen" state.lxc_container:
name: test-container-stoppedstate: frozencontainer_command: |echo 'hello world.' | tee /opt/frozen
- name: Start a containerlxc_container:
name: test-container-stoppedstate: started
- name: Run a command in a container and then restart itlxc_container:
name: test-container-startedstate: restartedcontainer_command: |
echo 'hello world.' | tee /opt/restarted
- name: Run a complex command within a "running" containerlxc_container:
name: test-container-startedcontainer_command: |apt-get updateapt-get install -y curl wget vim apache2echo 'hello world.' | tee /opt/startedif [[ -f "/opt/started" ]]; then
echo 'hello world.' | tee /opt/found-startedfi
# Create an archive of an existing container, save the archive to a defined# path and then destroy it.- name: Archive containerlxc_container:
name: test-container-startedstate: absentarchive: truearchive_path: /opt/archives
# Create a container using overlayfs, create an archive of it, create a# snapshot clone of the container and and finally leave the container# in a frozen state. The container archive will be compressed using gzip.- name: Create an overlayfs container archive and clone itlxc_container:
name: test-container-overlayfscontainer_log: truetemplate: ubuntustate: startedbacking_store: overlayfstemplate_options: --release trustyclone_snapshot: trueclone_name: test-container-overlayfs-clone-snapshot
1.6. Module Index 419
Ansible 1.2 Documentation, Release 0.01
archive: truearchive_compression: gzip
register: clone_container_info
- name: debug info on container "test-container"debug: var=clone_container_info
- name: Clone a container using snapshotlxc_container:
name: test-container-overlayfs-clone-snapshotbacking_store: overlayfsclone_name: test-container-overlayfs-clone-snapshot2clone_snapshot: true
- name: Create a new container and clone itlxc_container:
name: test-container-new-archivebacking_store: dirclone_name: test-container-new-archive-clone
- name: Archive and clone a container then destroy itlxc_container:
name: test-container-new-archivestate: absentclone_name: test-container-new-archive-destroyed-clonearchive: truearchive_compression: gzip
- name: Start a cloned container.lxc_container:
name: test-container-new-archive-destroyed-clonestate: started
- name: Destroy a containerlxc_container:
name: "{{ item }}"state: absent
with_items:- test-container-stopped- test-container-started- test-container-frozen- test-container-lvm- test-container-config- test-container-overlayfs- test-container-overlayfs-clone- test-container-overlayfs-clone-snapshot- test-container-overlayfs-clone-snapshot2- test-container-new-archive- test-container-new-archive-clone- test-container-new-archive-destroyed-clone
Notes
420 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: Containers must have a unique name. If you attempt to create a container with a name that already exists in theusers namespace the module will simply return as “unchanged”.
Note: The “container_command” can be used with any state except “absent”. If used with state “stopped” thecontainer will be “started”, the command executed, and then the container “stopped” again. Likewise if the stateis “stopped” and the container does not exist it will be first created, “started”, the command executed, and then“stopped”. If you use a “|” in the variable you can use common script formatting within the variable iteself The“container_command” option will always execute as BASH. When using “container_command” a log file is createdin the /tmp/ directory which contains both stdout and stderr of any command executed.
Note: If “archive” is true the system will attempt to create a compressed tarball of the running container. The“archive” option supports LVM backed containers and will create a snapshot of the running container when creatingthe archive.
Note: If your distro does not have a package for “python2-lxc”, which is a requirement for this module, it can beinstalled from source at “https://github.com/lxc/python2-lxc” or installed via pip using the package name lxc-python2.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
macports - Package manager for MacPorts
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manages MacPorts packages
Options
1.6. Module Index 421
Ansible 1.2 Documentation, Release 0.01
Examples
- macports: name=foo state=present- macports: name=foo state=present update_cache=yes- macports: name=foo state=absent- macports: name=foo state=active- macports: name=foo state=inactive
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
mail - Send an email
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
This module is useful for sending emails from playbooks. One may wonder why automate sending emails? In complexenvironments there are from time to time processes that cannot be automated, either because you lack the authorityto make it so, or because not everyone agrees to a common approach. If you cannot automate a specific step, but thestep is non-blocking, sending out an email to the responsible party to make him perform his part of the bargain is anelegant way to put the responsibility in someone else’s lap. Of course sending out a mail can be equally useful as away to notify one or more people in a team that a specific action has been (successfully) taken.
Options
Examples
# Example playbook sending mail to root- local_action: mail subject='System {{ ansible_hostname }} has been→˓successfully provisioned.'
# Sending an e-mail using Gmail SMTP servers- local_action: mail
host='smtp.gmail.com'[email protected]='mysecret'to="John Smith <[email protected]>"
422 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
subject='Ansible-report'body='System {{ ansible_hostname }} has been successfully
→˓provisioned.'
# Send e-mail to a bunch of users, attaching files- local_action: mail
host='127.0.0.1'port=2025subject="Ansible-report"body="Hello, this is an e-mail. I hope you like it ;-)"from="[email protected] (Jane Jolie)"to="John Doe <[email protected]>, Suzie Something <sue@example.
→˓com>"cc="Charlie Root <root@localhost>"attach="/etc/group /tmp/pavatar2.png"[email protected]|X-Special="Something or
→˓other"charset=utf8
# Sending an e-mail using the remote machine, not the Ansible controller node- mail:
host='localhost'port=25to="John Smith <[email protected]>"subject='Ansible-report'body='System {{ ansible_hostname }} has been successfully provisioned.'
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
maven_artifact - Downloads an Artifact from a Maven Repository
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Downloads an artifact from a maven repository given the maven coordinates provided to the module. Can retrievesnapshots or release versions of the artifact and will resolve the latest available version if one is not available.
1.6. Module Index 423
Ansible 1.2 Documentation, Release 0.01
Requirements
• python >= 2.6
• lxml
Options
Examples
# Download the latest version of the JUnit framework artifact from Maven→˓Central- maven_artifact: group_id=junit artifact_id=junit dest=/tmp/junit-latest.jar
# Download JUnit 4.11 from Maven Central- maven_artifact: group_id=junit artifact_id=junit version=4.11 dest=/tmp/→˓junit-4.11.jar
# Download an artifact from a private repository requiring authentication- maven_artifact: group_id=com.company artifact_id=library-name repository_→˓url=https://repo.company.com/maven username=user password=pass dest=/tmp/→˓library-name-latest.jar
# Download a WAR File to the Tomcat webapps directory to be deployed- maven_artifact: group_id=com.company artifact_id=web-app extension=war→˓repository_url=https://repo.company.com/maven dest=/var/lib/tomcat7/→˓webapps/web-app.war
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
modprobe - Add or remove kernel modules
New in version 1.4.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Add or remove kernel modules.
424 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Add the 802.1q module- modprobe: name=8021q state=present# Add the dummy module- modprobe: name=dummy state=present params="numdummies=2"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
mongodb_user - Adds or removes a user from a MongoDB database.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Adds or removes a user from a MongoDB database.
Requirements
• pymongo
Options
Examples
# Create 'burgers' database user with name 'bob' and password '12345'.- mongodb_user: database=burgers name=bob password=12345 state=present
# Create a database user via SSL (MongoDB must be compiled with the SSL→˓option and configured properly)- mongodb_user: database=burgers name=bob password=12345 state=present→˓ssl=True
1.6. Module Index 425
Ansible 1.2 Documentation, Release 0.01
# Delete 'burgers' database user with name 'bob'.- mongodb_user: database=burgers name=bob state=absent
# Define more users with various specific roles (if not defined, no roles is→˓assigned, and the user will be added via pre mongo 2.2 style)- mongodb_user: database=burgers name=ben password=12345 roles='read'→˓state=present- mongodb_user: database=burgers name=jim password=12345 roles='readWrite,→˓dbAdmin,userAdmin' state=present- mongodb_user: database=burgers name=joe password=12345 roles=→˓'readWriteAnyDatabase' state=present
# add a user to database in a replica set, the primary server is→˓automatically discovered and written to- mongodb_user: database=burgers name=bob replica_set=blecher password=12345→˓roles='readWriteAnyDatabase' state=present
Notes
Note: Requires the pymongo Python package on the remote host, version 2.4.2+. This can be installed using pip orthe OS package manager. @see http://api.mongodb.org/python/current/installation.html
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
monit - Manage the state of a program monitored via Monit
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manage the state of a program monitored via Monit
Options
426 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
# Manage the state of program "httpd" to be in "started" state.- monit: name=httpd state=started
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
mount - Control active and configured mount points
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
This module controls active and configured mount points in /etc/fstab.
Options
Examples
# Mount DVD read-only- mount: name=/mnt/dvd src=/dev/sr0 fstype=iso9660 opts=ro state=present
# Mount up device by label- mount: name=/srv/disk src='LABEL=SOME_LABEL' fstype=ext4 state=present
# Mount up device by UUID- mount: name=/home src='UUID=b3e48f45-f933-4c8e-a700-22a159ec9077'→˓fstype=xfs opts=noatime state=present
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 427
Ansible 1.2 Documentation, Release 0.01
mqtt - Publish a message on an MQTT topic for the IoT
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Publish a message on an MQTT topic.
Requirements
• mosquitto
Options
Examples
- local_action: mqtttopic=service/ansible/{{ ansible_hostname }}payload="Hello at {{ ansible_date_time.iso8601 }}"qos=0retain=falseclient_id=ans001
Notes
Note: This module requires a connection to an MQTT broker such as Mosquitto http://mosquitto.org and the Pahomqtt Python client (https://pypi.python.org/pypi/paho-mqtt).
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
428 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
mysql_db - Add or remove MySQL databases from a remote host.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Add or remove MySQL databases from a remote host.
Requirements
• MySQLdb
Options
Examples
# Create a new database with name 'bobdata'- mysql_db: name=bobdata state=present
# Copy database dump file to remote host and restore it to database 'my_db'- copy: src=dump.sql.bz2 dest=/tmp- mysql_db: name=my_db state=import target=/tmp/dump.sql.bz2
# Dumps all databases to hostname.sql- mysql_db: state=dump name=all target=/tmp/{{ inventory_hostname }}.sql
# Imports file.sql similiar to mysql -u <username> -p <password> < hostname.→˓sql- mysql_db: state=import name=all target=/tmp/{{ inventory_hostname }}.sql
Notes
Note: Requires the MySQLdb Python package on the remote host. For Ubuntu, this is as easy as apt-get installpython-mysqldb. (See apt.) For CentOS/Fedora, this is as easy as yum install MySQL-python. (See yum.)
Note: Both login_password and login_user are required when you are passing credentials. If none arepresent, the module will attempt to read the credentials from ~/.my.cnf, and finally fall back to using the MySQL
1.6. Module Index 429
Ansible 1.2 Documentation, Release 0.01
default login of ‘root’ with no password.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
mysql_replication - Manage MySQL replication
New in version 1.3.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manages MySQL server replication, slave, master status get and change master host.
Requirements
• MySQLdb
Options
Examples
# Stop mysql slave thread- mysql_replication: mode=stopslave
# Get master binlog file name and binlog position- mysql_replication: mode=getmaster
# Change master to master server 192.168.1.1 and use binary log 'mysql-bin.→˓000009' with position 4578- mysql_replication: mode=changemaster master_host=192.168.1.1 master_log_→˓file=mysql-bin.000009 master_log_pos=4578
# Check slave status using port 3308- mysql_replication: mode=getslave login_host=ansible.example.com login_→˓port=3308
430 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Notes
Note: Requires the MySQLdb Python package on the remote host. For Ubuntu, this is as easy as apt-get installpython-mysqldb. (See apt.) For CentOS/Fedora, this is as easy as yum install MySQL-python. (See yum.)
Note: Both login_password and login_user are required when you are passing credentials. If none arepresent, the module will attempt to read the credentials from ~/.my.cnf, and finally fall back to using the MySQLdefault login of ‘root’ with no password.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
mysql_user - Adds or removes a user from a MySQL database.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Adds or removes a user from a MySQL database.
Requirements
• MySQLdb
Options
1.6. Module Index 431
Ansible 1.2 Documentation, Release 0.01
Examples
# Create database user with name 'bob' and password '12345' with all→˓database privileges- mysql_user: name=bob password=12345 priv=*.*:ALL state=present
# Create database user with name 'bob' and previously hashed mysql native→˓password '*EE0D72C1085C46C5278932678FBE2C6A782821B4' with all database→˓privileges- mysql_user: name=bob password='*EE0D72C1085C46C5278932678FBE2C6A782821B4'→˓encrypted=yes priv=*.*:ALL state=present
# Creates database user 'bob' and password '12345' with all database→˓privileges and 'WITH GRANT OPTION'- mysql_user: name=bob password=12345 priv=*.*:ALL,GRANT state=present
# Modify user Bob to require SSL connections. Note that REQUIRESSL is a→˓special privilege that should only apply to *.* by itself.- mysql_user: name=bob append_privs=true priv=*.*:REQUIRESSL state=present
# Ensure no user named 'sally' exists, also passing in the auth credentials.- mysql_user: login_user=root login_password=123456 name=sally state=absent
# Specify grants composed of more than one word- mysql_user: name=replication password=12345 priv="*.*:REPLICATION CLIENT"→˓state=present
# Revoke all privileges for user 'bob' and password '12345'- mysql_user: name=bob password=12345 priv=*.*:USAGE state=present
# Example privileges string formatmydb.*:INSERT,UPDATE/anotherdb.*:SELECT/yetanotherdb.*:ALL
# Example using login_unix_socket to connect to server- mysql_user: name=root password=abc123 login_unix_socket=/var/run/mysqld/→˓mysqld.sock
# Example .my.cnf file for setting the root password
[client]user=rootpassword=n<_665{vS43y
Notes
Note: MySQL server installs with default login_user of ‘root’ and no password. To secure this user as part of anidempotent playbook, you must create at least two tasks: the first must change the root user’s password, withoutproviding any login_user/login_password details. The second must drop a ~/.my.cnf file containing the new rootcredentials. Subsequent runs of the playbook will then succeed by reading the new credentials from the file.
Note: Currently, there is only support for the mysql_native_password encryted password hash module.
432 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: Requires the MySQLdb Python package on the remote host. For Ubuntu, this is as easy as apt-get installpython-mysqldb. (See apt.) For CentOS/Fedora, this is as easy as yum install MySQL-python. (See yum.)
Note: Both login_password and login_user are required when you are passing credentials. If none arepresent, the module will attempt to read the credentials from ~/.my.cnf, and finally fall back to using the MySQLdefault login of ‘root’ with no password.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
mysql_variables - Manage MySQL global variables
New in version 1.3.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Query / Set MySQL variables
Requirements
• MySQLdb
Options
Examples
# Check for sync_binlog setting- mysql_variables: variable=sync_binlog
# Set read_only variable to 1- mysql_variables: variable=read_only value=1
1.6. Module Index 433
Ansible 1.2 Documentation, Release 0.01
Notes
Note: Requires the MySQLdb Python package on the remote host. For Ubuntu, this is as easy as apt-get installpython-mysqldb. (See apt.) For CentOS/Fedora, this is as easy as yum install MySQL-python. (See yum.)
Note: Both login_password and login_user are required when you are passing credentials. If none arepresent, the module will attempt to read the credentials from ~/.my.cnf, and finally fall back to using the MySQLdefault login of ‘root’ with no password.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
nagios - Perform common tasks in Nagios related to downtime and notifications.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
The nagios module has two basic functions: scheduling downtime and toggling alerts for services or hosts. All actionsrequire the host parameter to be given explicitly. In playbooks you can use the {{inventory_hostname}}variable to refer to the host the playbook is currently running on. You can specify multiple services at once byseparating them with commas, .e.g., services=httpd,nfs,puppet. When specifying what service to handlethere is a special service value, host, which will handle alerts/downtime for the host itself, e.g., service=host.This keyword may not be given with other services at the same time. Setting alerts/downtime for a host does not affectalerts/downtime for any of the services running on it. To schedule downtime for all services on particular host usekeyword “all”, e.g., service=all. When using the nagios module you will need to specify your Nagios serverusing the delegate_to parameter.
Options
434 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
# set 30 minutes of apache downtime- nagios: action=downtime minutes=30 service=httpd host={{ inventory_→˓hostname }}
# schedule an hour of HOST downtime- nagios: action=downtime minutes=60 service=host host={{ inventory_hostname→˓}}
# schedule an hour of HOST downtime, with a comment describing the reason- nagios: action=downtime minutes=60 service=host host={{ inventory_hostname→˓}}
comment='This host needs disciplined'
# schedule downtime for ALL services on HOST- nagios: action=downtime minutes=45 service=all host={{ inventory_hostname }→˓}
# schedule downtime for a few services- nagios: action=downtime services=frob,foobar,qeuz host={{ inventory_→˓hostname }}
# set 30 minutes downtime for all services in servicegroup foo- nagios: action=servicegroup_service_downtime minutes=30 servicegroup=foo→˓host={{ inventory_hostname }}
# set 30 minutes downtime for all host in servicegroup foo- nagios: action=servicegroup_host_downtime minutes=30 servicegroup=foo host=→˓{{ inventory_hostname }}
# enable SMART disk alerts- nagios: action=enable_alerts service=smart host={{ inventory_hostname }}
# "two services at once: disable httpd and nfs alerts"- nagios: action=disable_alerts service=httpd,nfs host={{ inventory_hostname→˓}}
# disable HOST alerts- nagios: action=disable_alerts service=host host={{ inventory_hostname }}
# silence ALL alerts- nagios: action=silence host={{ inventory_hostname }}
# unsilence all alerts- nagios: action=unsilence host={{ inventory_hostname }}
# SHUT UP NAGIOS- nagios: action=silence_nagios
# ANNOY ME NAGIOS- nagios: action=unsilence_nagios
# command something- nagios: action=command command='DISABLE_FAILURE_PREDICTION'
1.6. Module Index 435
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
netscaler - Manages Citrix NetScaler entities
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manages Citrix NetScaler server and service entities.
Options
Examples
# Disable the serveransible host -m netscaler -a "nsc_host=nsc.example.com user=apiuser→˓password=apipass"
# Enable the serveransible host -m netscaler -a "nsc_host=nsc.example.com user=apiuser→˓password=apipass action=enable"
# Disable the service local:8080ansible host -m netscaler -a "nsc_host=nsc.example.com user=apiuser→˓password=apipass name=local:8080 type=service action=disable"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
newrelic_deployment - Notify newrelic about app deployments
436 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Notify newrelic about app deployments (see https://docs.newrelic.com/docs/apm/new-relic-apm/maintenance/deployment-notifications#api)
Options
Examples
- newrelic_deployment: token=AAAAAAapp_name=myappuser='ansible deployment'revision=1.0
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
nexmo - Send a SMS via nexmo
New in version 1.6.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Send a SMS message via nexmo
1.6. Module Index 437
Ansible 1.2 Documentation, Release 0.01
Options
Examples
- name: Send notification message via Nexmolocal_action:
module: nexmoapi_key: 640c8a53api_secret: 0ce239a6src: 12345678901dest:
- 10987654321- 16789012345
msg: "{{ inventory_hostname }} completed"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
nmcli - Manage Networking
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Manage the network devices. Create, modify, and manage, ethernet, teams, bonds, vlans etc.
Requirements
• nmcli
• dbus
Options
438 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
The following examples are working examples that I have run in the field. I→˓followed follow the structure:```|_/inventory/cloud-hosts| /group_vars/openstack-stage.yml| /host_vars/controller-01.openstack.host.com| /host_vars/controller-02.openstack.host.com|_/playbook/library/nmcli.py| /playbook-add.yml| /playbook-del.yml```
## inventory examples### groups_vars```yml---#devops_os_define_networkstorage_gw: "192.168.0.254"external_gw: "10.10.0.254"tenant_gw: "172.100.0.254"
#Team varsnmcli_team:
- {conn_name: 'tenant', ip4: "{{tenant_ip}}", gw4: "{{tenant_gw}}"}- {conn_name: 'external', ip4: "{{external_ip}}", gw4: "{{external_gw}}"}- {conn_name: 'storage', ip4: "{{storage_ip}}", gw4: "{{storage_gw}}"}
nmcli_team_slave:- {conn_name: 'em1', ifname: 'em1', master: 'tenant'}- {conn_name: 'em2', ifname: 'em2', master: 'tenant'}- {conn_name: 'p2p1', ifname: 'p2p1', master: 'storage'}- {conn_name: 'p2p2', ifname: 'p2p2', master: 'external'}
#bond varsnmcli_bond:
- {conn_name: 'tenant', ip4: "{{tenant_ip}}", gw4: '', mode: 'balance-rr→˓'}
- {conn_name: 'external', ip4: "{{external_ip}}", gw4: '', mode:→˓'balance-rr'}
- {conn_name: 'storage', ip4: "{{storage_ip}}", gw4: "{{storage_gw}}",→˓mode: 'balance-rr'}nmcli_bond_slave:
- {conn_name: 'em1', ifname: 'em1', master: 'tenant'}- {conn_name: 'em2', ifname: 'em2', master: 'tenant'}- {conn_name: 'p2p1', ifname: 'p2p1', master: 'storage'}- {conn_name: 'p2p2', ifname: 'p2p2', master: 'external'}
#ethernet varsnmcli_ethernet:
- {conn_name: 'em1', ifname: 'em1', ip4: "{{tenant_ip}}", gw4: "{{tenant_→˓gw}}"}
- {conn_name: 'em2', ifname: 'em2', ip4: "{{tenant_ip1}}", gw4: "{→˓{tenant_gw}}"}
- {conn_name: 'p2p1', ifname: 'p2p1', ip4: "{{storage_ip}}", gw4: "{→˓{storage_gw}}"}
- {conn_name: 'p2p2', ifname: 'p2p2', ip4: "{{external_ip}}", gw4: "{→˓{external_gw}}"}
1.6. Module Index 439
Ansible 1.2 Documentation, Release 0.01
```
### host_vars```yml---storage_ip: "192.168.160.21/23"external_ip: "10.10.152.21/21"tenant_ip: "192.168.200.21/23"```
## playbook-add.yml example
```yml---- hosts: openstack-stageremote_user: roottasks:
- name: install needed network manager libsyum: name={{ item }} state=installedwith_items:
- libnm-qt-devel.x86_64- nm-connection-editor.x86_64- libsemanage-python- policycoreutils-python
##### Working with all cloud nodes - Teaming- name: try nmcli add team - conn_name only & ip4 gw4
nmcli: type=team conn_name={{item.conn_name}} ip4={{item.ip4}} gw4={→˓{item.gw4}} state=present
with_items:- "{{nmcli_team}}"
- name: try nmcli add teams-slavenmcli: type=team-slave conn_name={{item.conn_name}} ifname={{item.ifname}
→˓} master={{item.master}} state=presentwith_items:
- "{{nmcli_team_slave}}"
###### Working with all cloud nodes - Bonding# - name: try nmcli add bond - conn_name only & ip4 gw4 mode# nmcli: type=bond conn_name={{item.conn_name}} ip4={{item.ip4}} gw4={→˓{item.gw4}} mode={{item.mode}} state=present# with_items:# - "{{nmcli_bond}}"## - name: try nmcli add bond-slave# nmcli: type=bond-slave conn_name={{item.conn_name}} ifname={{item.→˓ifname}} master={{item.master}} state=present# with_items:# - "{{nmcli_bond_slave}}"
##### Working with all cloud nodes - Ethernet# - name: nmcli add Ethernet - conn_name only & ip4 gw4# nmcli: type=ethernet conn_name={{item.conn_name}} ip4={{item.ip4}} gw4={→˓{item.gw4}} state=present
440 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# with_items:# - "{{nmcli_ethernet}}"```
## playbook-del.yml example
```yml---- hosts: openstack-stageremote_user: roottasks:
- name: try nmcli del team - multiplenmcli: conn_name={{item.conn_name}} state=absentwith_items:
- { conn_name: 'em1'}- { conn_name: 'em2'}- { conn_name: 'p1p1'}- { conn_name: 'p1p2'}- { conn_name: 'p2p1'}- { conn_name: 'p2p2'}- { conn_name: 'tenant'}- { conn_name: 'storage'}- { conn_name: 'external'}- { conn_name: 'team-em1'}- { conn_name: 'team-em2'}- { conn_name: 'team-p1p1'}- { conn_name: 'team-p1p2'}- { conn_name: 'team-p2p1'}- { conn_name: 'team-p2p2'}
```# To add an Ethernet connection with static IP configuration, issue a→˓command as follows- nmcli: conn_name=my-eth1 ifname=eth1 type=ethernet ip4=192.168.100.100/24→˓gw4=192.168.100.1 state=present
# To add an Team connection with static IP configuration, issue a command as→˓follows- nmcli: conn_name=my-team1 ifname=my-team1 type=team ip4=192.168.100.100/24→˓gw4=192.168.100.1 state=present autoconnect=yes
# Optionally, at the same time specify IPv6 addresses for the device as→˓follows:- nmcli: conn_name=my-eth1 ifname=eth1 type=ethernet ip4=192.168.100.100/24→˓gw4=192.168.100.1 ip6=abbe::cafe gw6=2001:db8::1 state=present
# To add two IPv4 DNS server addresses:-nmcli: conn_name=my-eth1 dns4=["8.8.8.8", "8.8.4.4"] state=present
# To make a profile usable for all compatible Ethernet interfaces, issue a→˓command as follows- nmcli: ctype=ethernet name=my-eth1 ifname="*" state=present
# To change the property of a setting e.g. MTU, issue a command as follows:- nmcli: conn_name=my-eth1 mtu=9000 state=present
Exit Status's:- nmcli exits with status 0 if it succeeds, a value greater than 0 is
1.6. Module Index 441
Ansible 1.2 Documentation, Release 0.01
returned if an error occurs.- 0 Success - indicates the operation succeeded- 1 Unknown or unspecified error- 2 Invalid user input, wrong nmcli invocation- 3 Timeout expired (see --wait option)- 4 Connection activation failed- 5 Connection deactivation failed- 6 Disconnecting device failed- 7 Connection deletion failed- 8 NetworkManager is not running- 9 nmcli and NetworkManager versions mismatch- 10 Connection, device, or access point does not exist.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
nova_compute - Create/Delete VMs from OpenStack
• DEPRECATED
• Synopsis
• Requirements
• Options
• Examples
DEPRECATED
Deprecated in 2.0. Use os_server instead
Synopsis
Create or Remove virtual machines from Openstack.
Requirements
• python >= 2.6
• python-novaclient
442 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Creates a new VM and attaches to a network and passes metadata to the→˓instance- nova_compute:
state: presentlogin_username: adminlogin_password: adminlogin_tenant_name: adminname: vm1image_id: 4f905f38-e52a-43d2-b6ec-754a13ffb529key_name: ansible_keywait_for: 200flavor_id: 4nics:- net-id: 34605f38-e52a-25d2-b6ec-754a13ffb723
meta:hostname: test1group: uge_master
# Creates a new VM in HP Cloud AE1 region availability zone az2 and→˓automatically assigns a floating IP- name: launch a nova instancehosts: localhosttasks:- name: launch an instance
nova_compute:state: presentlogin_username: usernamelogin_password: Equality7-2521login_tenant_name: username-project1name: vm1auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/region_name: region-b.geo-1availability_zone: az2image_id: 9302692b-b787-4b52-a3a6-daebb79cb498key_name: testwait_for: 200flavor_id: 101security_groups: defaultauto_floating_ip: yes
# Creates a new VM in HP Cloud AE1 region availability zone az2 and assigns→˓a pre-known floating IP- name: launch a nova instancehosts: localhosttasks:- name: launch an instance
nova_compute:state: presentlogin_username: usernamelogin_password: Equality7-2521login_tenant_name: username-project1name: vm1auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/
1.6. Module Index 443
Ansible 1.2 Documentation, Release 0.01
region_name: region-b.geo-1availability_zone: az2image_id: 9302692b-b787-4b52-a3a6-daebb79cb498key_name: testwait_for: 200flavor_id: 101floating-ips:- 12.34.56.79
# Creates a new VM with 4G of RAM on Ubuntu Trusty, ignoring deprecated→˓images- name: launch a nova instancehosts: localhosttasks:- name: launch an instance
nova_compute:name: vm1state: presentlogin_username: usernamelogin_password: Equality7-2521login_tenant_name: username-project1auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/region_name: region-b.geo-1image_name: Ubuntu Server 14.04image_exclude: deprecatedflavor_ram: 4096
# Creates a new VM with 4G of RAM on Ubuntu Trusty on a Rackspace→˓Performance node in DFW- name: launch a nova instancehosts: localhosttasks:- name: launch an instance
nova_compute:name: vm1state: presentlogin_username: usernamelogin_password: Equality7-2521login_tenant_name: username-project1auth_url: https://identity.api.rackspacecloud.com/v2.0/region_name: DFWimage_name: Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)flavor_ram: 4096flavor_include: Performance
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
nova_keypair - Add/Delete key pair from nova
• DEPRECATED
• Synopsis
• Requirements
444 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Options
• Examples
DEPRECATED
Deprecated in 2.0. Use os_keypair instead
Synopsis
Add or Remove key pair from nova .
Requirements
• python >= 2.6
• python-novaclient
Options
Examples
# Creates a key pair with the running users public key- nova_keypair: state=present login_username=admin
login_password=admin login_tenant_name=admin name=ansible_keypublic_key={{ lookup('file','~/.ssh/id_rsa.pub') }}
# Creates a new key pair and the private key returned after the run.- nova_keypair: state=present login_username=admin login_password=admin
login_tenant_name=admin name=ansible_key
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
npm - Manage node.js packages with npm
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manage node.js packages with Node Package Manager (npm)
1.6. Module Index 445
Ansible 1.2 Documentation, Release 0.01
Options
Examples
description: Install "coffee-script" node.js package.- npm: name=coffee-script path=/app/location
description: Install "coffee-script" node.js package on version 1.6.1.- npm: name=coffee-script version=1.6.1 path=/app/location
description: Install "coffee-script" node.js package globally.- npm: name=coffee-script global=yes
description: Remove the globally package "coffee-script".- npm: name=coffee-script global=yes state=absent
description: Install "coffee-script" node.js package from custom registry.- npm: name=coffee-script registry=http://registry.mysite.com
description: Install packages based on package.json.- npm: path=/app/location
description: Update packages based on package.json to their latest version.- npm: path=/app/location state=latest
description: Install packages based on package.json using the npm installed→˓with nvm v0.10.1.- npm: path=/app/location executable=/opt/nvm/v0.10.1/bin/npm state=present
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ohai - Returns inventory data from Ohai
• Synopsis
• Requirements
• Examples
• This is an Extras Module
Synopsis
Similar to the facter module, this runs the Ohai discovery program (http://wiki.opscode.com/display/chef/Ohai) on theremote host and returns JSON inventory data. Ohai data is a bit more verbose and nested than facter.
446 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Requirements
• ohai
Examples
# Retrieve (ohai) data from all Web servers and store in one-file per hostansible webservers -m ohai --tree=/tmp/ohaidata
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
open_iscsi - Manage iscsi targets with open-iscsi
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Discover targets on given portal, (dis)connect targets, mark targets to manually or auto start, return device nodes ofconnected targets.
Requirements
• open_iscsi library and tools (iscsiadm)
Options
Examples
# perform a discovery on 10.1.2.3 and show available target nodes- open_iscsi: show_nodes=yes discover=yes portal=10.1.2.3
# discover targets on portal and login to the one available# (only works if exactly one target is exported to the initiator)
1.6. Module Index 447
Ansible 1.2 Documentation, Release 0.01
- open_iscsi: portal={{iscsi_target}} login=yes discover=yes
# description: connect to the named target, after updating the local# persistent database (cache)- open_iscsi: login=yes target=iqn.1986-03.com.sun:02:f8c1f9e0-c3ec-ec84-→˓c9c9-8bfb0cd5de3d
# description: discconnect from the cached named target- open_iscsi: login=no target=iqn.1986-03.com.sun:02:f8c1f9e0-c3ec-ec84-c9c9-→˓8bfb0cd5de3d"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
openbsd_pkg - Manage packages on OpenBSD.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manage packages on OpenBSD using the pkg tools.
Options
Examples
# Make sure nmap is installed- openbsd_pkg: name=nmap state=present
# Make sure nmap is the latest version- openbsd_pkg: name=nmap state=latest
# Make sure nmap is not installed- openbsd_pkg: name=nmap state=absent
# Specify a pkg flavour with '--'- openbsd_pkg: name=vim--nox11 state=present
# Specify the default flavour to avoid ambiguity errors- openbsd_pkg: name=vim-- state=present
448 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# Update all packages on the system- openbsd_pkg: name=* state=latest
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
openvswitch_bridge - Manage Open vSwitch bridges
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Manage Open vSwitch bridges
Requirements
• ovs-vsctl
Options
Examples
# Create a bridge named br-int- openvswitch_bridge: bridge=br-int state=present
# Create an integration bridge- openvswitch_bridge: bridge=br-int state=present fail_mode=secureargs:
external_ids:bridge-id: "br-int"
1.6. Module Index 449
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
openvswitch_db - Configure open vswitch database.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Set column values in record in database table.
Requirements
• ovs-vsctl >= 2.3.3
Options
Examples
# Increase the maximum idle time to 50 seconds before pruning unused kernel# rules.- openvswitch_db: table=open_vswitch record=. col=other_config key=max-idle
value=50000
# Disable in band copy- openvswitch_db: table=Bridge record=br-int col=other_config
key=disable-in-band value=true
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
450 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
openvswitch_port - Manage Open vSwitch ports
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Manage Open vSwitch ports
Requirements
• ovs-vsctl
Options
Examples
# Creates port eth2 on bridge br-ex- openvswitch_port: bridge=br-ex port=eth2 state=present
# Creates port eth6 and set ofport equal to 6.- openvswitch_port: bridge=bridge-loop port=eth6 state=present
set Interface eth6 ofport_request=6
# Assign interface id server1-vifeth6 and mac address 52:54:00:30:6d:11# to port vifeth6 and setup port to be managed by a controller.- openvswitch_port: bridge=br-int port=vifeth6 state=presentargs:
external_ids:iface-id: "{{inventory_hostname}}-vifeth6"attached-mac: "52:54:00:30:6d:11"vm-id: "{{inventory_hostname}}"iface-status: "active"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 451
Ansible 1.2 Documentation, Release 0.01
opkg - Package manager for OpenWrt
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manages OpenWrt packages
Options
Examples
- opkg: name=foo state=present- opkg: name=foo state=present update_cache=yes- opkg: name=foo state=absent- opkg: name=foo,bar state=absent- opkg: name=foo state=present force=overwrite
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_auth - Retrieve an auth token
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
452 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
Retrieve an auth token from an OpenStack Cloud
Requirements
• python >= 2.6
• python >= 2.7
• shade
Options
Examples
# Authenticate to the cloud and retrieve the service catalog- os_auth:
cloud: rax-dfw- debug: var=service_catalog
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_client_config - Get OpenStack Client config
New in version 2.0.
• Synopsis
• Requirements
1.6. Module Index 453
Ansible 1.2 Documentation, Release 0.01
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Get openstack client config data from clouds.yaml or environment
Requirements
• os-client-config
Options
Examples
# Get list of clouds that do not support security groups- os_client_config:- debug: var={{ item }}with_items: "{{ openstack.clouds|rejectattr('secgroup_source', 'none
→˓')|list() }}"
# Get the information back just about the mordred cloud- os_client_config:
clouds:- mordred
Notes
Note: Facts are placed in the openstack.clouds variable.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_floating_ip - Add/Remove floating IP from an instance
New in version 2.0.
454 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Add or Remove a floating IP to an instance
Requirements
• python >= 2.7
• shade
Options
Examples
# Assign a floating IP to the fist interface of `cattle001` from an exiting# external network or nova pool. A new floating IP from the first available# external network is allocated to the project.- os_floating_ip:
cloud: dguerriserver: cattle001
# Assign a new floating IP to the instance fixed ip `192.0.2.3` of# `cattle001`. If a free floating IP is already allocated to the project, it→˓is# reused; if not, a new one is created.- os_floating_ip:
cloud: dguerristate: presentreuse: yesserver: cattle001network: ext_netfixed_address: 192.0.2.3wait: truetimeout: 180
# Detach a floating IP address from a server- os_floating_ip:
cloud: dguerristate: absentfloating_ip_address: 203.0.113.2server: cattle001
1.6. Module Index 455
Ansible 1.2 Documentation, Release 0.01
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_image - Add/Delete images from OpenStack Cloud
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Add or Remove images from the OpenStack Image Repository
Requirements
• python >= 2.7
• shade
Options
456 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
# Upload an image from a local file named cirros-0.3.0-x86_64-disk.img- os_image:
auth:auth_url: http://localhost/auth/v2.0username: adminpassword: passmeproject_name: admin
name: cirroscontainer_format: baredisk_format: qcow2state: presentfilename: cirros-0.3.0-x86_64-disk.imgkernel: cirros-vmlinuzramdisk: cirros-initrdproperties:
cpu_arch: x86_64distro: ubuntu
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_image_facts - Retrieve facts about an image within OpenStack.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
1.6. Module Index 457
Ansible 1.2 Documentation, Release 0.01
• Return Values
• Notes
• This is a Core Module
Synopsis
Retrieve facts about a image image from OpenStack.
Requirements
• python >= 2.6
• python >= 2.7
• shade
Options
Examples
# Gather facts about a previously created image named image1- os_image_facts:
auth:auth_url: https://your_api_url.com:9000/v2.0username: userpassword: passwordproject_name: someproject
image: image1- debug: var=openstack
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: Facts are placed in the openstack variable.
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then from
458 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
standard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_ironic - Create/Delete Bare Metal Resources from OpenStack
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Create or Remove Ironic nodes from OpenStack.
Requirements
• jsonpatch
• python >= 2.7
• shade
Options
Examples
# Enroll a node with some basic properties and driver info- os_ironic:
cloud: "devstack"driver: "pxe_ipmitool"uuid: "00000000-0000-0000-0000-000000000002"properties:cpus: 2cpu_arch: "x86_64"
1.6. Module Index 459
Ansible 1.2 Documentation, Release 0.01
ram: 8192disk_size: 64
nics:- mac: "aa:bb:cc:aa:bb:cc"- mac: "dd:ee:ff:dd:ee:ff"
driver_info:power:ipmi_address: "1.2.3.4"ipmi_username: "admin"ipmi_password: "adminpass"
chassis_uuid: "00000000-0000-0000-0000-000000000001"
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_ironic_node - Activate/Deactivate Bare Metal Resources from OpenStack
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Deploy to nodes controlled by Ironic.
460 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Requirements
• python >= 2.7
• shade
Options
Examples
# Activate a node by booting an image with a configdrive attachedos_ironic_node:cloud: "openstack"uuid: "d44666e1-35b3-4f6b-acb0-88ab7052da69"state: presentpower: presentdeploy: Truemaintenance: Falseconfig_drive: "http://192.168.1.1/host-configdrive.iso"instance_info:
image_source: "http://192.168.1.1/deploy_image.img"image_checksum: "356a6b55ecc511a20c33c946c4e678af"image_disk_format: "qcow"
delegate_to: localhost
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_keypair - Add/Delete a keypair from OpenStack
New in version 2.0.
1.6. Module Index 461
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is a Core Module
Synopsis
Add or Remove key pair from OpenStack
Requirements
• python >= 2.7
• shade
Options
Examples
# Creates a key pair with the running users public key- os_keypair:
cloud: mordredstate: presentname: ansible_keypublic_key_file: /home/me/.ssh/id_rsa.pub
# Creates a new key pair and the private key returned after the run.- os_keypair:
cloud: rax-dfwstate: presentname: ansible_key
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
462 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_network - Creates/removes networks from OpenStack
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is a Core Module
Synopsis
Add or remove network from OpenStack.
Requirements
• python >= 2.7
• shade
Options
Examples
# Create an externally accessible network named 'ext_network'.- os_network:
cloud: mycloudstate: present
1.6. Module Index 463
Ansible 1.2 Documentation, Release 0.01
name: ext_networkexternal: true
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_networks_facts - Retrieve facts about one or more OpenStack networks.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is a Core Module
Synopsis
Retrieve facts about one or more networks from OpenStack.
464 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Requirements
• python >= 2.6
• python >= 2.7
• shade
Options
Examples
# Gather facts about previously created networks- os_networks_facts:
auth:auth_url: https://your_api_url.com:9000/v2.0username: userpassword: passwordproject_name: someproject
- debug: var=openstack_networks
# Gather facts about a previously created network by name- os_networks_facts:
auth:auth_url: https://your_api_url.com:9000/v2.0username: userpassword: passwordproject_name: someproject
name: network1- debug: var=openstack_networks
# Gather facts about a previously created network with filter (note: name andfilters parameters are Not mutually exclusive)
- os_networks_facts:auth:
auth_url: https://your_api_url.com:9000/v2.0username: userpassword: passwordproject_name: someproject
filters:tenant_id: 55e2ce24b2a245b09f181bf025724cbesubnets:- 057d4bdf-6d4d-4728-bb0f-5ac45a6f7400- 443d4dc0-91d4-4998-b21c-357d10433483
- debug: var=openstack_networks
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
1.6. Module Index 465
Ansible 1.2 Documentation, Release 0.01
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_nova_flavor - Manage OpenStack compute flavors
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is a Core Module
Synopsis
Add or remove flavors from OpenStack.
Requirements
• python >= 2.7
• shade
Options
466 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
# Create 'tiny' flavor with 1024MB of RAM, 1 virtual CPU, and 10GB of# local disk, and 10GB of ephemeral.- os_nova_flavor:
cloud=mycloudstate=presentname=tinyram=1024vcpus=1disk=10ephemeral=10
# Delete 'tiny' flavor- os_nova_flavor:
cloud=mycloudstate=absentname=tiny
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_object - Create or Delete objects and containers from OpenStack
New in version 2.0.
• Synopsis
1.6. Module Index 467
Ansible 1.2 Documentation, Release 0.01
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Create or Delete objects and containers from OpenStack
Requirements
• python >= 2.7
• shade
Options
Examples
# Creates a object named 'fstab' in the 'config' container- os_object: cloud=mordred state=present name=fstab container=config file=/→˓etc/fstab
# Deletes a container called config and all of its contents- os_object: cloud=rax-iad state=absent container=config
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
468 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
os_port - Add/Update/Delete ports from an OpenStack cloud.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is a Core Module
Synopsis
Add, Update or Remove ports from an OpenStack cloud. A state=present, will ensure the port is created or updated ifrequired.
Requirements
• python >= 2.7
• shade
Options
Examples
# Create a port- os_port:
state: presentauth:auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/username: adminpassword: adminproject_name: admin
name: port1network: foo
# Create a port with a static IP- os_port:
state: presentauth:
auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/username: adminpassword: adminproject_name: admin
name: port1
1.6. Module Index 469
Ansible 1.2 Documentation, Release 0.01
network: foofixed_ips:
- ip_address: 10.1.0.21
# Create a port with No security groups- os_port:
state: presentauth:
auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/username: adminpassword: adminproject_name: admin
name: port1network: foono_security_groups: True
# Update the existing 'port1' port with multiple security groups (version 1)- os_port:
state: presentauth:
auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/dusername: adminpassword: adminproject_name: admin
name: port1security_groups: 1496e8c7-4918-482a-9172-f4f00fc4a3a5,057d4bdf-6d4d-472..
→˓.
# Update the existing 'port1' port with multiple security groups (version 2)- os_port:
state: presentauth:auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/dusername: adminpassword: adminproject_name: admin
name: port1security_groups:
- 1496e8c7-4918-482a-9172-f4f00fc4a3a5- 057d4bdf-6d4d-472...
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then from
470 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
standard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_project - Manage OpenStack Projects
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Manage OpenStack Projects. Projects can be created, updated or deleted using this module. A project will be updatedif name matches an existing project and state is present. The value for name cannot be updated without deleting andre-creating the project.
Requirements
• python >= 2.6
• python >= 2.7
• shade
Options
Examples
# Create a project- os_project:
cloud: mycloudstate: present
1.6. Module Index 471
Ansible 1.2 Documentation, Release 0.01
name: demoprojectdescription: demodescriptiondomain_id: demoidenabled: True
# Delete a project- os_project:
cloud: mycloudstate: absentname: demoproject
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_router - Create or delete routers from OpenStack
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
472 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• This is a Core Module
Synopsis
Create or Delete routers from OpenStack. Although Neutron allows routers to share the same name, this moduleenforces name uniqueness to be more user friendly.
Requirements
• python >= 2.7
• shade
Options
Examples
# Create a simple router, not attached to a gateway or subnets.- os_router:
cloud: mycloudstate: presentname: simple_router
# Creates a router attached to ext_network1 on an IPv4 subnet and one# internal subnet interface.- os_router:
cloud: mycloudstate: presentname: router1network: ext_network1external_fixed_ips:- subnet: public-subnetip: 172.24.4.2
interfaces:- private-subnet
# Update existing router1 external gateway to include the IPv6 subnet.# Note that since 'interfaces' is not provided, any existing internal# interfaces on an existing router will be left intact.- os_router:
cloud: mycloudstate: presentname: router1network: ext_network1external_fixed_ips:
- subnet: public-subnetip: 172.24.4.2
- subnet: ipv6-public-subnetip: 2001:db8::3
# Delete router1- os_router:
cloud: mycloud
1.6. Module Index 473
Ansible 1.2 Documentation, Release 0.01
state: absentname: router1
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_security_group - Add/Delete security groups from an OpenStack cloud.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Add or Remove security groups from an OpenStack cloud.
474 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Requirements
• python >= 2.7
• shade
Options
Examples
# Create a security group- os_security_group:
cloud=mordredstate=presentname=foodescription=security group for foo servers
# Update the existing 'foo' security group description- os_security_group:
cloud=mordredstate=presentname=foodescription=updated description for the foo security group
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_security_group_rule - Add/Delete rule from an existing security group
New in version 2.0.
1.6. Module Index 475
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is a Core Module
Synopsis
Add or Remove rule from an existing security group
Requirements
• python >= 2.7
• shade
Options
Examples
# Create a security group rule- os_security_group_rule:
cloud: mordredsecurity_group: fooprotocol: tcpport_range_min: 80port_range_max: 80remote_ip_prefix: 0.0.0.0/0
# Create a security group rule for ping- os_security_group_rule:
cloud: mordredsecurity_group: fooprotocol: icmpremote_ip_prefix: 0.0.0.0/0
# Another way to create the ping rule- os_security_group_rule:
cloud: mordredsecurity_group: fooprotocol: icmpport_range_min: -1port_range_max: -1remote_ip_prefix: 0.0.0.0/0
# Create a TCP rule covering all ports
476 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- os_security_group_rule:cloud: mordredsecurity_group: fooprotocol: tcpport_range_min: 1port_range_max: 65535remote_ip_prefix: 0.0.0.0/0
# Another way to create the TCP rule above (defaults to all ports)- os_security_group_rule:
cloud: mordredsecurity_group: fooprotocol: tcpremote_ip_prefix: 0.0.0.0/0
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_server - Create/Delete Compute Instances from OpenStack
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
1.6. Module Index 477
Ansible 1.2 Documentation, Release 0.01
• Notes
• This is a Core Module
Synopsis
Create or Remove compute instances from OpenStack.
Requirements
• python >= 2.6
• python >= 2.7
• shade
Options
Examples
# Creates a new instance and attaches to a network and passes metadata to# the instance- os_server:
state: presentauth:auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/username: adminpassword: adminproject_name: admin
name: vm1image: 4f905f38-e52a-43d2-b6ec-754a13ffb529key_name: ansible_keytimeout: 200flavor: 4nics:- net-id: 34605f38-e52a-25d2-b6ec-754a13ffb723- net-name: another_network
meta:hostname: test1group: uge_master
# Creates a new instance in HP Cloud AE1 region availability zone az2 and# automatically assigns a floating IP- name: launch a compute instancehosts: localhosttasks:- name: launch an instance
os_server:state: presentauth:auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/username: usernamepassword: Equality7-2521
478 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
project_name: username-project1name: vm1region_name: region-b.geo-1availability_zone: az2image: 9302692b-b787-4b52-a3a6-daebb79cb498key_name: testtimeout: 200flavor: 101security_groups: defaultauto_ip: yes
# Creates a new instance in named cloud mordred availability zone az2# and assigns a pre-known floating IP- name: launch a compute instancehosts: localhosttasks:- name: launch an instance
os_server:state: presentcloud: mordredname: vm1availability_zone: az2image: 9302692b-b787-4b52-a3a6-daebb79cb498key_name: testtimeout: 200flavor: 101floating-ips:- 12.34.56.79
# Creates a new instance with 4G of RAM on Ubuntu Trusty, ignoring# deprecated images- name: launch a compute instancehosts: localhosttasks:- name: launch an instance
os_server:name: vm1state: presentcloud: mordredregion_name: region-b.geo-1image: Ubuntu Server 14.04image_exclude: deprecatedflavor_ram: 4096
# Creates a new instance with 4G of RAM on Ubuntu Trusty on a Performance→˓node- name: launch a compute instancehosts: localhosttasks:- name: launch an instance
os_server:name: vm1cloud: rax-dfwstate: presentimage: Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)flavor_ram: 4096flavor_include: Performance
1.6. Module Index 479
Ansible 1.2 Documentation, Release 0.01
# Creates a new instance and attaches to multiple network- name: launch a compute instancehosts: localhosttasks:- name: launch an instance with a string
os_server:name: vm1auth:
auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/username: adminpassword: adminproject_name: admin
name: vm1image: 4f905f38-e52a-43d2-b6ec-754a13ffb529key_name: ansible_keytimeout: 200flavor: 4nics: "net-id=4cb08b20-62fe-11e5-9d70-feff819cdc9f,net-id=542f0430-
→˓62fe-11e5-9d70-feff819cdc9f..."
# Creates a new instance and attaches to a network and passes metadata to# the instance- os_server:
state: presentauth:auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/username: adminpassword: adminproject_name: admin
name: vm1image: 4f905f38-e52a-43d2-b6ec-754a13ffb529key_name: ansible_keytimeout: 200flavor: 4nics:- net-id: 34605f38-e52a-25d2-b6ec-754a13ffb723- net-name: another_network
meta: "hostname=test1,group=uge_master"
# Creates a new instance and attaches to a specific network- os_server:
state: presentauth:auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/username: adminpassword: adminproject_name: admin
name: vm1image: 4f905f38-e52a-43d2-b6ec-754a13ffb529key_name: ansible_keytimeout: 200flavor: 4network: another_network
# Creates a new instance with 4G of RAM on a 75G Ubuntu Trusty volume- name: launch a compute instancehosts: localhosttasks:
480 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- name: launch an instanceos_server:
name: vm1state: presentcloud: mordredregion_name: ams01image: Ubuntu Server 14.04flavor_ram: 4096boot_from_volume: Truevolume_size: 75
# Creates a new instance with 2 volumes attached- name: launch a compute instancehosts: localhosttasks:- name: launch an instance
os_server:name: vm1state: presentcloud: mordredregion_name: ams01image: Ubuntu Server 14.04flavor_ram: 4096volumes:- photos- music
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_server_actions - Perform actions on Compute Instances from OpenStack
New in version 2.0.
1.6. Module Index 481
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Perform server actions on an existing compute instance from OpenStack. This module does not return any data otherthan changed true/false.
Requirements
• python >= 2.6
• python >= 2.7
• shade
Options
Examples
# Pauses a compute instance- os_server_actions:
action: pauseauth:auth_url: https://mycloud.openstack.blueboxgrid.com:5001/v2.0username: adminpassword: adminproject_name: admin
server: vm1timeout: 200
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then from
482 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
standard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_server_facts - Retrieve facts about one or more compute instances
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Retrieve facts about server instances from OpenStack.
Requirements
• python >= 2.6
• python >= 2.7
• shade
Options
Examples
# Gather facts about all servers named C<web*>:- os_server_facts:
cloud: rax-dfwserver: web*
- debug:var: openstack_servers
1.6. Module Index 483
Ansible 1.2 Documentation, Release 0.01
Notes
Note: This module creates a new top-level openstack_servers fact, which contains a list of servers.
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_server_volume - Attach/Detach Volumes from OpenStack VM’s
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Attach or Detach volumes from OpenStack VM’s
Requirements
• python >= 2.6
• python >= 2.7
• shade
484 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Attaches a volume to a compute host- name: attach a volumehosts: localhosttasks:- name: attach volume to host
os_server_volume:state: presentcloud: mordredserver: Mysql-servervolume: mysql-datadevice: /dev/vdb
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_subnet - Add/Remove subnet to an OpenStack network
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
1.6. Module Index 485
Ansible 1.2 Documentation, Release 0.01
Synopsis
Add or Remove a subnet to an OpenStack network
Requirements
• python >= 2.6
• python >= 2.7
• shade
Options
Examples
# Create a new (or update an existing) subnet on the specified network- os_subnet:
state: presentnetwork_name: network1name: net1subnetcidr: 192.168.0.0/24dns_nameservers:
- 8.8.8.7- 8.8.8.8
host_routes:- destination: 0.0.0.0/0nexthop: 12.34.56.78
- destination: 192.168.0.0/24nexthop: 192.168.0.1
# Delete a subnet- os_subnet:
state: absentname: net1subnet
# Create an ipv6 stateless subnet- os_subnet:
state: presentname: intv6network_name: internalip_version: 6cidr: 2db8:1::/64dns_nameservers:
- 2001:4860:4860::8888- 2001:4860:4860::8844
ipv6_ra_mode: dhcpv6-statelessipv6_address_mode: dhcpv6-stateless
Notes
486 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_subnets_facts - Retrieve facts about one or more OpenStack subnets.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is a Core Module
Synopsis
Retrieve facts about one or more subnets from OpenStack.
Requirements
• python >= 2.6
• python >= 2.7
• shade
Options
1.6. Module Index 487
Ansible 1.2 Documentation, Release 0.01
Examples
# Gather facts about previously created subnets- os_subnets_facts:
auth:auth_url: https://your_api_url.com:9000/v2.0username: userpassword: passwordproject_name: someproject
- debug: var=openstack_subnets
# Gather facts about a previously created subnet by name- os_subnets_facts:
auth:auth_url: https://your_api_url.com:9000/v2.0username: userpassword: passwordproject_name: someproject
name: subnet1- debug: var=openstack_subnets
# Gather facts about a previously created subnet with filter (note: name andfilters parameters are Not mutually exclusive)
- os_subnets_facts:auth:
auth_url: https://your_api_url.com:9000/v2.0username: userpassword: passwordproject_name: someproject
filters:tenant_id: 55e2ce24b2a245b09f181bf025724cbe
- debug: var=openstack_subnets
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
488 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_user - Manage OpenStack Identity Users
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is a Core Module
Synopsis
Manage OpenStack Identity users. Users can be created, updated or deleted using this module. A user will be updatedif name matches an existing user and state is present. The value for name cannot be updated without deleting andre-creating the user.
Requirements
• python >= 2.6
• python >= 2.7
• shade
Options
Examples
# Create a user- os_user:
cloud: mycloudstate: presentname: demouserpassword: secretemail: [email protected]: defaultdefault_project: demo
1.6. Module Index 489
Ansible 1.2 Documentation, Release 0.01
# Delete a user- os_user:
cloud: mycloudstate: absentname: demouser
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_user_group - Associate OpenStack Identity users and groups
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Add and remove users from groups
490 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Requirements
• python >= 2.6
• python >= 2.7
• shade
Options
Examples
# Add the demo user to the demo group- os_user_group:cloud: myclouduser: demogroup: demo
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
os_volume - Create/Delete Cinder Volumes
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
1.6. Module Index 491
Ansible 1.2 Documentation, Release 0.01
• Notes
• This is a Core Module
Synopsis
Create or Remove cinder block storage volumes
Requirements
• python >= 2.6
• python >= 2.7
• shade
Options
Examples
# Creates a new volume- name: create a volumehosts: localhosttasks:- name: create 40g test volume
os_volume:state: presentcloud: mordredavailability_zone: az2size: 40display_name: test_volume
Notes
Note: The standard OpenStack environment variables, such as OS_USERNAME may be used instead of providingexplicit values.
Note: Auth information is driven by os-client-config, which means that values can come from a yaml con-fig file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then fromstandard environment variables, then finally by explicit parameters in plays. More information can be found athttp://docs.openstack.org/developer/os-client-config
This is a Core Module
For more information on what this means please read Core Modules
492 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
osx_defaults - osx_defaults allows users to read, write, and delete Mac OS X user defaults fromAnsible
New in version 2.0.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
osx_defaults allows users to read, write, and delete Mac OS X user defaults from Ansible scripts. Mac OS X ap-plications and other programs use the defaults system to record user preferences and other information that must bemaintained when the applications aren’t running (such as default font for new documents, or the position of an Infopanel).
Options
Examples
- osx_defaults: domain=com.apple.Safari key=IncludeInternalDebugMenu→˓type=bool value=true state=present- osx_defaults: domain=NSGlobalDomain key=AppleMeasurementUnits type=string→˓value=Centimeters state=present- osx_defaults: key=AppleMeasurementUnits type=string value=Centimeters- osx_defaults:
key: AppleLanguagestype: arrayvalue: ["en", "nl"]
- osx_defaults: domain=com.geekchimp.macable key=ExampleKeyToRemove→˓state=absent
Notes
Note: Apple Mac caches defaults. You may need to logout and login to apply the changes.
1.6. Module Index 493
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
osx_say - Makes an OSX computer to speak.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
makes an OS computer speak! Amuse your friends, annoy your coworkers!
Requirements
• say
Options
Examples
- local_action: osx_say msg="{{inventory_hostname}} is all done" voice=Zarvox
Notes
Note: If you like this module, you may also be interested in the osx_say callback in the plugins/ directory of thesource checkout.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
494 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
ovirt - oVirt/RHEV platform management
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
allows you to create new instances, either from scratch or an image, in addition to deleting or stopping instances onthe oVirt/RHEV platform
Requirements
• python >= 2.6
• ovirt-engine-sdk-python
Options
Examples
# Basic example provisioning from image.
action: ovirt >user=admin@internalurl=https://ovirt.example.cominstance_name=ansiblevm04password=secretimage=centos_64zone=cluster01resource_type=template"
# Full example to create new instance from scratchaction: ovirt >
instance_name=testansibleresource_type=newinstance_type=serveruser=admin@internalpassword=secreturl=https://ovirt.example.cominstance_disksize=10zone=cluster01region=datacenter1instance_cpus=1instance_nic=nic1
1.6. Module Index 495
Ansible 1.2 Documentation, Release 0.01
instance_network=rhevminstance_mem=1000disk_alloc=thinsdomain=FIBER01instance_cores=1instance_os=rhel_6x64disk_int=virtio"
# stopping an instanceaction: ovirt >
instance_name=testansiblestate=stoppeduser=admin@internalpassword=secreturl=https://ovirt.example.com
# starting an instanceaction: ovirt >
instance_name=testansiblestate=starteduser=admin@internalpassword=secreturl=https://ovirt.example.com
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
package - Generic OS package manager
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Installs, upgrade and removes packages using the underlying OS package manager.
496 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Requirements
• Whatever is required for the package plugins specific for each system.
Options
Examples
- name: install the latest version of ntpdatepackage: name=ntpdate state=latest
# This uses a variable as this changes per distribution.- name: remove the apache packagepackage : name={{apache}} state=absent
Notes
Note: This module actually calls the pertinent package modules for each system (apt, yum, etc).
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
pacman - Manage packages with pacman
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manage packages with the pacman package manager, which is used by Arch Linux and its variants.
Options
1.6. Module Index 497
Ansible 1.2 Documentation, Release 0.01
Examples
# Install package foo- pacman: name=foo state=present
# Upgrade package foo- pacman: name=foo state=latest update_cache=yes
# Remove packages foo and bar- pacman: name=foo,bar state=absent
# Recursively remove package baz- pacman: name=baz state=absent recurse=yes
# Run the equivalent of "pacman -Sy" as a separate step- pacman: update_cache=yes
# Run the equivalent of "pacman -Su" as a separate step- pacman: upgrade=yes
# Run the equivalent of "pacman -Syu" as a separate step- pacman: update_cache=yes upgrade=yes
# Run the equivalent of "pacman -Rdd", force remove package baz- pacman: name=baz state=absent force=yes
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
pagerduty - Create PagerDuty maintenance windows
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
This module will let you create PagerDuty maintenance windows
498 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Requirements
• PagerDuty API access
Options
Examples
# List ongoing maintenance windows using a user/passwd- pagerduty: name=companyabc [email protected] passwd=password123→˓state=ongoing
# List ongoing maintenance windows using a token- pagerduty: name=companyabc token=xxxxxxxxxxxxxx state=ongoing
# Create a 1 hour maintenance window for service FOO123, using a user/passwd- pagerduty: name=companyabc
[email protected]=password123state=runningservice=FOO123
# Create a 5 minute maintenance window for service FOO123, using a token- pagerduty: name=companyabc
token=xxxxxxxxxxxxxxhours=0minutes=5state=runningservice=FOO123
# Create a 4 hour maintenance window for service FOO123 with the description→˓"deployment".- pagerduty: name=companyabc
[email protected]=password123state=runningservice=FOO123hours=4desc=deployment
register: pd_window
# Delete the previous maintenance window- pagerduty: name=companyabc
[email protected]=password123state=absentservice={{ pd_window.result.maintenance_window.id }}
This is an Extras Module
For more information on what this means please read Extras Modules
1.6. Module Index 499
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
pagerduty_alert - Trigger, acknowledge or resolve PagerDuty incidents
New in version 1.9.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
This module will let you trigger, acknowledge or resolve a PagerDuty incident by sending events
Requirements
• PagerDuty API access
Options
Examples
# Trigger an incident with just the basic options- pagerduty_alert:
name: companyabcservice_key=xxxapi_key:yourapikeystate=triggereddesc="problem that led to this trigger"
# Trigger an incident with more options- pagerduty_alert:
service_key=xxxapi_key=yourapikeystate=triggereddesc="problem that led to this trigger"incident_key=somekeyclient="Sample Monitoring Service"client_url=http://service.example.com
# Acknowledge an incident based on incident_key- pagerduty_alert:
service_key=xxxapi_key=yourapikey
500 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
state=acknowledgedincident_key=somekeydesc="some text for incident's log"
# Resolve an incident based on incident_key- pagerduty_alert:
service_key=xxxapi_key=yourapikeystate=resolvedincident_key=somekeydesc="some text for incident's log"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
pam_limits - Modify Linux PAM limits
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
The pam_limits module modify PAM limits, default in /etc/security/limits.conf. For the full documentation, see manlimits.conf(5).
Options
Examples
# Add or modify nofile soft limit for the user joe- pam_limits: domain=joe limit_type=soft limit_item=nofile value=64000
# Add or modify fsize hard limit for the user smith. Keep or set the maximal→˓value.- pam_limits: domain=smith limit_type=hard limit_item=fsize value=1000000→˓use_max=yes
# Add or modify memlock, both soft and hard, limit for the user james with a→˓comment.- pam_limits: domain=james limit_type=- limit_item=memlock value=unlimited→˓comment="unlimited memory lock for james"
1.6. Module Index 501
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
patch - Apply patch files using the GNU patch tool.
New in version 1.9.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Apply patch files using the GNU patch tool.
Options
Examples
- name: apply patch to one filepatch: >
src=/tmp/index.html.patchdest=/var/www/index.html
- name: apply patch to multiple files under basedirpatch: >
src=/tmp/customize.patchbasedir=/var/wwwstrip=1
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
502 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
pause - Pause playbook execution
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
Pauses playbook execution for a set amount of time, or until a prompt is acknowledged. All parameters are optional.The default behavior is to pause with a prompt. You can use ctrl+c if you wish to advance a pause earlier than it isset to expire or if you need to abort a playbook run entirely. To continue early: press ctrl+c and then c. To aborta playbook: press ctrl+c and then a. The pause module integrates into async/parallelized playbooks without anyspecial considerations (see also: Rolling Updates). When using pauses with the serial playbook parameter (as inrolling updates) you are only prompted once for the current group of hosts.
Options
Examples
# Pause for 5 minutes to build app cache.- pause: minutes=5
# Pause until you can verify updates to an application were successful.- pause:
# A helpful reminder of what to look out for post-update.- pause: prompt="Make sure org.foo.FooOverload exception is not present"
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
pear - Manage pear/pecl packages
New in version 2.0.
• Synopsis
• Options
• Examples
1.6. Module Index 503
Ansible 1.2 Documentation, Release 0.01
• This is an Extras Module
Synopsis
Manage PHP packages with the pear package manager.
Options
Examples
# Install pear package- pear: name=Net_URL2 state=present
# Install pecl package- pear: name=pecl/json_post state=present
# Upgrade package- pear: name=Net_URL2 state=latest
# Remove packages- pear: name=Net_URL2,pecl/json_post state=absent
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ping - Try to connect to host, verify a usable python and return pong on success.
• Synopsis
• Examples
• This is a Core Module
Synopsis
A trivial test module, this module always returns pong on successful contact. It does not make sense in playbooks,but it is useful from /usr/bin/ansible to verify the ability to login and that a usable python is configured. Thisis NOT ICMP ping, this is just a trivial test module.
504 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
# Test we can logon to 'webservers' and execute python with json lib.ansible webservers -m ping
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
pingdom - Pause/unpause Pingdom alerts
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
This module will let you pause/unpause Pingdom alerts
Requirements
• This pingdom python library: https://github.com/mbabineau/pingdom-python
Options
Examples
# Pause the check with the ID of 12345.- pingdom: [email protected]
passwd=password123key=apipassword123checkid=12345state=paused
# Unpause the check with the ID of 12345.- pingdom: [email protected]
passwd=password123key=apipassword123
1.6. Module Index 505
Ansible 1.2 Documentation, Release 0.01
checkid=12345state=running
Notes
Note: This module does not yet have support to add/remove checks.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
pip - Manages Python library dependencies.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Manage Python library dependencies. To use this module, one of the following keys is required: name orrequirements.
Requirements
• virtualenv
• pip
Options
Examples
506 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# Install (Bottle) python package.- pip: name=bottle
# Install (Bottle) python package on version 0.11.- pip: name=bottle version=0.11
# Install (MyApp) using one of the remote protocols (bzr+,hg+,git+,svn+).→˓You do not have to supply '-e' option in extra_args.- pip: name='svn+http://myrepo/svn/MyApp#egg=MyApp'
# Install MyApp using one of the remote protocols (bzr+,hg+,git+) in a non→˓editable way.- pip: name='git+http://myrepo/app/MyApp' editable=false
# Install (MyApp) from local tarball- pip: name='file:///path/to/MyApp.tar.gz'
# Install (Bottle) into the specified (virtualenv), inheriting none of the→˓globally installed modules- pip: name=bottle virtualenv=/my_app/venv
# Install (Bottle) into the specified (virtualenv), inheriting globally→˓installed modules- pip: name=bottle virtualenv=/my_app/venv virtualenv_site_packages=yes
# Install (Bottle) into the specified (virtualenv), using Python 2.7- pip: name=bottle virtualenv=/my_app/venv virtualenv_command=virtualenv-2.7
# Install specified python requirements.- pip: requirements=/my_app/requirements.txt
# Install specified python requirements in indicated (virtualenv).- pip: requirements=/my_app/requirements.txt virtualenv=/my_app/venv
# Install specified python requirements and custom Index URL.- pip: requirements=/my_app/requirements.txt extra_args='-i https://example.→˓com/pypi/simple'
# Install (Bottle) for Python 3.3 specifically,using the 'pip-3.3'→˓executable.- pip: name=bottle executable=pip-3.3
Notes
Note: Please note that virtualenv (http://www.virtualenv.org/) must be installed on the remote host if the virtualenvparameter is specified and the virtualenv needs to be initialized.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 507
Ansible 1.2 Documentation, Release 0.01
pkg5 - Manages packages with the Solaris 11 Image Packaging System
New in version 1.9.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
IPS packages are the native packages in Solaris 11 and higher.
Options
Examples
# Install Vim:- pkg5: name=editor/vim
# Remove finger daemon:- pkg5: name=service/network/finger state=absent
# Install several packages at once:- pkg5:
name:- /file/gnu-findutils- /text/gnu-grep
Notes
Note: The naming of IPS packages is explained at http://www.oracle.com/technetwork/articles/servers-storage-admin/ips-package-versioning-2232906.html.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
508 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
pkg5_publisher - Manages Solaris 11 Image Packaging System publishers
New in version 1.9.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
IPS packages are the native packages in Solaris 11 and higher. This modules will configure which publishers a clientwill download IPS packages from.
Options
Examples
# Fetch packages for the solaris publisher direct from Oracle:- pkg5_publisher: name=solaris sticky=true origin=https://pkg.oracle.com/→˓solaris/support/
# Configure a publisher for locally-produced packages:- pkg5_publisher: name=site origin=https://pkg.example.com/site/
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
pkgin - Package manager for SmartOS, NetBSD, et al.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
1.6. Module Index 509
Ansible 1.2 Documentation, Release 0.01
Synopsis
The standard package manager for SmartOS, but also usable on NetBSD or any OS that uses pkgsrc. (Home:http://pkgin.net/)
Options
Examples
# install package foo- pkgin: name=foo state=present
# remove package foo- pkgin: name=foo state=absent
# remove packages foo and bar- pkgin: name=foo,bar state=absent
Notes
Note: Known bug with pkgin < 0.8.0: if a package is removed and another package depends on it, the other packagewill be silently removed as well. New to Ansible 1.9: check-mode support.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
pkgng - Package manager for FreeBSD >= 9.0
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manage binary packages for FreeBSD using ‘pkgng’ which is available in versions after 9.0.
510 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Install package foo- pkgng: name=foo state=present
# Annotate package foo and bar- pkgng: name=foo,bar annotation=+test1=baz,-test2,:test3=foobar
# Remove packages foo and bar- pkgng: name=foo,bar state=absent
Notes
Note: When using pkgsite, be careful that already in cache packages won’t be downloaded again.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
pkgutil - Manage CSW-Packages on Solaris
New in version 1.3.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manages CSW packages (SVR4 format) on Solaris 10 and 11. These were the native packages on Solaris <= 10 andare available as a legacy feature in Solaris 11. Pkgutil is an advanced packaging system, which resolves dependencyon installation. It is designed for CSW packages.
Options
1.6. Module Index 511
Ansible 1.2 Documentation, Release 0.01
Examples
# Install a packagepkgutil: name=CSWcommon state=present
# Install a package from a specific repositorypkgutil: name=CSWnrpe site='ftp://myinternal.repo/opencsw/kiel state=latest'
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
portage - Package manager for Gentoo
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Manages Gentoo packages
Requirements
• gentoolkit
Options
Examples
# Make sure package foo is installed- portage: package=foo state=present
# Make sure package foo is not installed- portage: package=foo state=absent
# Update package foo to the "best" version- portage: package=foo update=yes
512 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# Install package foo using PORTAGE_BINHOST setup- portage: package=foo getbinpkg=yes
# Re-install world from binary packages only and do not allow any compiling- portage: package=@world usepkgonly=yes
# Sync repositories and update world- portage: package=@world update=yes deep=yes sync=yes
# Remove unneeded packages- portage: depclean=yes
# Remove package foo if it is not explicitly needed- portage: package=foo state=absent depclean=yes
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
portinstall - Installing packages from FreeBSD’s ports system
New in version 1.3.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manage packages for FreeBSD using ‘portinstall’.
Options
Examples
# Install package foo- portinstall: name=foo state=present
# Install package security/cyrus-sasl2-saslauthd- portinstall: name=security/cyrus-sasl2-saslauthd state=present
# Remove packages foo and bar- portinstall: name=foo,bar state=absent
1.6. Module Index 513
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
postgresql_db - Add or remove PostgreSQL databases from a remote host.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Add or remove PostgreSQL databases from a remote host.
Requirements
• psycopg2
Options
Examples
# Create a new database with name "acme"- postgresql_db: name=acme
# Create a new database with name "acme" and specific encoding and locale# settings. If a template different from "template0" is specified, encoding# and locale settings must match those of the template.- postgresql_db: name=acme
encoding='UTF-8'lc_collate='de_DE.UTF-8'lc_ctype='de_DE.UTF-8'template='template0'
514 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Notes
Note: The default authentication assumes that you are either logging in as or sudo’ing to the postgres account onthe host.
Note: This module uses psycopg2, a Python PostgreSQL database adapter. You must ensure that psycopg2 isinstalled on the host before using this module. If the remote host is the PostgreSQL server (which is the default case),then PostgreSQL must also be installed on the remote host. For Ubuntu-based systems, install the postgresql,libpq-dev, and python-psycopg2 packages on the remote host before using this module.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
postgresql_ext - Add or remove PostgreSQL extensions from a database.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Add or remove PostgreSQL extensions from a database.
Requirements
• psycopg2
Options
Examples
# Adds postgis to the database "acme"- postgresql_ext: name=postgis db=acme
1.6. Module Index 515
Ansible 1.2 Documentation, Release 0.01
Notes
Note: The default authentication assumes that you are either logging in as or sudo’ing to the postgres account onthe host.
Note: This module uses psycopg2, a Python PostgreSQL database adapter. You must ensure that psycopg2 isinstalled on the host before using this module. If the remote host is the PostgreSQL server (which is the default case),then PostgreSQL must also be installed on the remote host. For Ubuntu-based systems, install the postgresql,libpq-dev, and python-psycopg2 packages on the remote host before using this module.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
postgresql_lang - Adds, removes or changes procedural languages with a PostgreSQL database.
New in version 1.7.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Adds, removes or changes procedural languages with a PostgreSQL database. This module allows you to add alanguage, remote a language or change the trust relationship with a PostgreSQL database. The module can be usedon the machine where executed or on a remote host. When removing a language from a database, it is possible thatdependencies prevent the database from being removed. In that case, you can specify casade to automatically dropobjects that depend on the language (such as functions in the language). In case the language can’t be deleted becauseit is required by the database system, you can specify fail_on_drop=no to ignore the error. Be carefull when markinga language as trusted since this could be a potential security breach. Untrusted languages allow only users with thePostgreSQL superuser privilege to use this language to create new functions.
Requirements
• psycopg2
516 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Add language pltclu to database testdb if it doesn't exist:- postgresql_lang db=testdb lang=pltclu state=present
# Add language pltclu to database testdb if it doesn't exist and mark it as→˓trusted:# Marks the language as trusted if it exists but isn't trusted yet# force_trust makes sure that the language will be marked as trusted- postgresql_lang db=testdb lang=pltclu state=present trust=yes force_→˓trust=yes
# Remove language pltclu from database testdb:- postgresql_lang: db=testdb lang=pltclu state=absent
# Remove language pltclu from database testdb and remove all dependencies:- postgresql_lang: db=testdb lang=pltclu state=absent cascade=yes
# Remove language c from database testdb but ignore errors if something→˓prevents the removal:- postgresql_lang: db=testdb lang=pltclu state=absent fail_on_drop=no
Notes
Note: The default authentication assumes that you are either logging in as or sudo’ing to the postgres account on thehost.
Note: This module uses psycopg2, a Python PostgreSQL database adapter. You must ensure that psycopg2 is installedon the host before using this module. If the remote host is the PostgreSQL server (which is the default case), thenPostgreSQL must also be installed on the remote host. For Ubuntu-based systems, install the postgresql, libpq-dev,and python-psycopg2 packages on the remote host before using this module.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
postgresql_privs - Grant or revoke privileges on PostgreSQL database objects.
• Synopsis
• Requirements
1.6. Module Index 517
Ansible 1.2 Documentation, Release 0.01
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Grant or revoke privileges on PostgreSQL database objects. This module is basically a wrapper around most of thefunctionality of PostgreSQL’s GRANT and REVOKE statements with detection of changes (GRANT/REVOKE privsON type objs TO/FROM roles)
Requirements
• psycopg2
Options
Examples
# On database "library":# GRANT SELECT, INSERT, UPDATE ON TABLE public.books, public.authors# TO librarian, reader WITH GRANT OPTION- postgresql_privs: >
database=librarystate=presentprivs=SELECT,INSERT,UPDATEtype=tableobjs=books,authorsschema=publicroles=librarian,readergrant_option=yes
# Same as above leveraging default values:- postgresql_privs: >
db=libraryprivs=SELECT,INSERT,UPDATEobjs=books,authorsroles=librarian,readergrant_option=yes
# REVOKE GRANT OPTION FOR INSERT ON TABLE books FROM reader# Note that role "reader" will be *granted* INSERT privilege itself if this# isn't already the case (since state=present).- postgresql_privs: >
db=librarystate=presentpriv=INSERTobj=booksrole=readergrant_option=no
518 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# REVOKE INSERT, UPDATE ON ALL TABLES IN SCHEMA public FROM reader# "public" is the default schema. This also works for PostgreSQL 8.x.- postgresql_privs: >
db=librarystate=absentprivs=INSERT,UPDATEobjs=ALL_IN_SCHEMArole=reader
# GRANT ALL PRIVILEGES ON SCHEMA public, math TO librarian- postgresql_privs: >
db=libraryprivs=ALLtype=schemaobjs=public,mathrole=librarian
# GRANT ALL PRIVILEGES ON FUNCTION math.add(int, int) TO librarian, reader# Note the separation of arguments with colons.- postgresql_privs: >
db=libraryprivs=ALLtype=functionobj=add(int:int)schema=mathroles=librarian,reader
# GRANT librarian, reader TO alice, bob WITH ADMIN OPTION# Note that group role memberships apply cluster-wide and therefore are not# restricted to database "library" here.- postgresql_privs: >
db=librarytype=groupobjs=librarian,readerroles=alice,bobadmin_option=yes
# GRANT ALL PRIVILEGES ON DATABASE library TO librarian# Note that here "db=postgres" specifies the database to connect to, not the# database to grant privileges on (which is specified via the "objs" param)- postgresql_privs: >
db=postgresprivs=ALLtype=databaseobj=libraryrole=librarian
# GRANT ALL PRIVILEGES ON DATABASE library TO librarian# If objs is omitted for type "database", it defaults to the database# to which the connection is established- postgresql_privs: >
db=libraryprivs=ALLtype=databaserole=librarian
1.6. Module Index 519
Ansible 1.2 Documentation, Release 0.01
Notes
Note: Default authentication assumes that postgresql_privs is run by the postgres user on the remote host. (Ansi-ble’s user or sudo-user).
Note: This module requires Python package psycopg2 to be installed on the remote host. In the default case ofthe remote host also being the PostgreSQL server, PostgreSQL has to be installed there as well, obviously. ForDebian/Ubuntu-based systems, install packages postgresql and python-psycopg2.
Note: Parameters that accept comma separated lists (privs, objs, roles) have singular alias names (priv, obj, role).
Note: To revoke only GRANT OPTION for a specific object, set state to present and grant_option to no (seeexamples).
Note: Note that when revoking privileges from a role R, this role may still have access via privileges granted to anyrole R is a member of including PUBLIC.
Note: Note that when revoking privileges from a role R, you do so as the user specified via login. If R has beengranted the same privileges by another user also, R can still access database objects via these privileges.
Note: When revoking privileges, RESTRICT is assumed (see PostgreSQL docs).
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
postgresql_user - Adds or removes a users (roles) from a PostgreSQL database.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
520 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
Add or remove PostgreSQL users (roles) from a remote host and, optionally, grant the users access to an existingdatabase or tables. The fundamental function of the module is to create, or delete, roles from a PostgreSQL cluster.Privilege assignment, or removal, is an optional step, which works on one database at a time. This allows for themodule to be called several times in the same module to modify the permissions on different databases, or to grantpermissions to already existing users. A user cannot be removed until all the privileges have been stripped from theuser. In such situation, if the module tries to remove the user it will fail. To avoid this from happening the fail_on_useroption signals the module to try to remove the user, but if not possible keep going; the module will report if changeshappened and separately if the user was removed or not.
Requirements
• psycopg2
Options
Examples
# Create django user and grant access to database and products table- postgresql_user: db=acme name=django password=ceec4eif7ya priv=CONNECT/→˓products:ALL
# Create rails user, grant privilege to create other databases and demote→˓rails from super user status- postgresql_user: name=rails password=secret role_attr_flags=CREATEDB,→˓NOSUPERUSER
# Remove test user privileges from acme- postgresql_user: db=acme name=test priv=ALL/products:ALL state=absent fail_→˓on_user=no
# Remove test user from test database and the cluster- postgresql_user: db=test name=test priv=ALL state=absent
# Example privileges string formatINSERT,UPDATE/table:SELECT/anothertable:ALL
# Remove an existing user's password- postgresql_user: db=test user=test password=NULL
Notes
Note: The default authentication assumes that you are either logging in as or sudo’ing to the postgres account on thehost.
Note: This module uses psycopg2, a Python PostgreSQL database adapter. You must ensure that psycopg2 is installedon the host before using this module. If the remote host is the PostgreSQL server (which is the default case), then
1.6. Module Index 521
Ansible 1.2 Documentation, Release 0.01
PostgreSQL must also be installed on the remote host. For Ubuntu-based systems, install the postgresql, libpq-dev,and python-psycopg2 packages on the remote host before using this module.
Note: If the passlib library is installed, then passwords that are encrypted in the DB but not encrypted when passedas arguments can be checked for changes. If the passlib library is not installed, unencrypted passwords stored in theDB encrypted will be assumed to have changed.
Note: If you specify PUBLIC as the user, then the privilege changes will apply to all users. You may not specifypassword or role_attr_flags when the PUBLIC user is specified.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
profitbricks - Create, destroy, start, stop, and reboot a ProfitBricks virtual machine.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Create, destroy, update, start, stop, and reboot a ProfitBricks virtual machine. When the virtual machine is created itcan optionally wait for it to be ‘running’ before returning. This module has a dependency on profitbricks >= 1.0.0
Requirements
• profitbricks
• python >= 2.6
Options
522 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
# Provisioning example. This will create three servers and enumerate their→˓names.
- profitbricks:datacenter: Tardis Onename: web%02d.stackpointcloud.comcores: 4ram: 2048volume_size: 50image: a3eae284-a2fe-11e4-b187-5f1f641608c8location: us/lascount: 3assign_public_ip: true
# Removing Virtual machines
- profitbricks:datacenter: Tardis Oneinstance_ids:
- 'web001.stackpointcloud.com'- 'web002.stackpointcloud.com'- 'web003.stackpointcloud.com'
wait_timeout: 500state: absent
# Starting Virtual Machines.
- profitbricks:datacenter: Tardis Oneinstance_ids:
- 'web001.stackpointcloud.com'- 'web002.stackpointcloud.com'- 'web003.stackpointcloud.com'
wait_timeout: 500state: running
# Stopping Virtual Machines
- profitbricks:datacenter: Tardis Oneinstance_ids:
- 'web001.stackpointcloud.com'- 'web002.stackpointcloud.com'- 'web003.stackpointcloud.com'
wait_timeout: 500state: stopped
This is an Extras Module
For more information on what this means please read Extras Modules
1.6. Module Index 523
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
profitbricks_datacenter - Create or destroy a ProfitBricks Virtual Datacenter.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
This is a simple module that supports creating or removing vDCs. A vDC is required before you can create servers.This module has a dependency on profitbricks >= 1.0.0
Requirements
• profitbricks
Options
Examples
# Create a Datacenter- profitbricks_datacenter:
datacenter: Tardis Onewait_timeout: 500
# Destroy a Datacenter. This will remove all servers, volumes, and other→˓objects in the datacenter.- profitbricks_datacenter:
datacenter: Tardis Onewait_timeout: 500state: absent
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
524 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
profitbricks_nic - Create or Remove a NIC.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
This module allows you to create or restore a volume snapshot. This module has a dependency on profitbricks >=1.0.0
Requirements
• profitbricks
Options
Examples
# Create a NIC- profitbricks_nic:
datacenter: Tardis Oneserver: node002lan: 2wait_timeout: 500state: present
# Remove a NIC- profitbricks_nic:
datacenter: Tardis Oneserver: node002name: 7341c2454fwait_timeout: 500state: absent
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 525
Ansible 1.2 Documentation, Release 0.01
profitbricks_volume - Create or destroy a volume.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Allows you to create or remove a volume from a ProfitBricks datacenter. This module has a dependency on profitbricks>= 1.0.0
Requirements
• profitbricks
Options
Examples
# Create Multiple Volumes
- profitbricks_volume:datacenter: Tardis Onename: vol%02dcount: 5auto_increment: yeswait_timeout: 500state: present
# Remove Volumes
- profitbricks_volume:datacenter: Tardis Oneinstance_ids:- 'vol01'- 'vol02'
wait_timeout: 500state: absent
This is an Extras Module
For more information on what this means please read Extras Modules
526 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
profitbricks_volume_attachments - Attach or detach a volume.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Allows you to attach or detach a volume from a ProfitBricks server. This module has a dependency on profitbricks >=1.0.0
Requirements
• profitbricks
Options
Examples
# Attach a Volume
- profitbricks_volume_attachments:datacenter: Tardis Oneserver: node002volume: vol01wait_timeout: 500state: present
# Detach a Volume
- profitbricks_volume_attachments:datacenter: Tardis Oneserver: node002volume: vol01wait_timeout: 500state: absent
1.6. Module Index 527
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
proxmox - management of instances in Proxmox VE cluster
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
allows you to create/delete/stop instances in Proxmox VE cluster
Requirements
• proxmoxer
• requests
Options
Examples
# Create new container with minimal options- proxmox: vmid=100 node='uk-mc02' api_user='root@pam' api_password='1q2w3e'→˓api_host='node1' password='123456' hostname='example.org' ostemplate=→˓'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
# Create new container with minimal options with force(it will rewrite→˓existing container)- proxmox: vmid=100 node='uk-mc02' api_user='root@pam' api_password='1q2w3e'→˓api_host='node1' password='123456' hostname='example.org' ostemplate=→˓'local:vztmpl/ubuntu-14.04-x86_64.tar.gz' force=yes
# Create new container with minimal options use environment PROXMOX_PASSWORD→˓variable(you should export it before)- proxmox: vmid=100 node='uk-mc02' api_user='root@pam' api_host='node1'→˓password='123456' hostname='example.org' ostemplate='local:vztmpl/ubuntu-→˓14.04-x86_64.tar.gz'
528 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# Start container- proxmox: vmid=100 api_user='root@pam' api_password='1q2w3e' api_host='node1→˓' state=started
# Stop container- proxmox: vmid=100 api_user='root@pam' api_password='1q2w3e' api_host='node1→˓' state=stopped
# Stop container with force- proxmox: vmid=100 api_user='root@pam' api_password='1q2w3e' api_host='node1→˓' force=yes state=stopped
# Restart container(stopped or mounted container you can't restart)- proxmox: vmid=100 api_user='root@pam' api_password='1q2w3e' api_host='node1→˓' state=stopped
# Remove container- proxmox: vmid=100 api_user='root@pam' api_password='1q2w3e' api_host='node1→˓' state=absent
Notes
Note: Requires proxmoxer and requests modules on host. This modules can be installed with pip.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
proxmox_template - management of OS templates in Proxmox VE cluster
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
1.6. Module Index 529
Ansible 1.2 Documentation, Release 0.01
Synopsis
allows you to upload/delete templates in Proxmox VE cluster
Requirements
• proxmoxer
• requests
Options
Examples
# Upload new openvz template with minimal options- proxmox_template: node='uk-mc02' api_user='root@pam' api_password='1q2w3e'→˓api_host='node1' src='~/ubuntu-14.04-x86_64.tar.gz'
# Upload new openvz template with minimal options use environment PROXMOX_→˓PASSWORD variable(you should export it before)- proxmox_template: node='uk-mc02' api_user='root@pam' api_host='node1' src=→˓'~/ubuntu-14.04-x86_64.tar.gz'
# Upload new openvz template with all options and force overwrite- proxmox_template: node='uk-mc02' api_user='root@pam' api_password='1q2w3e'→˓api_host='node1' storage='local' content_type='vztmpl' src='~/ubuntu-14.04-→˓x86_64.tar.gz' force=yes
# Delete template with minimal options- proxmox_template: node='uk-mc02' api_user='root@pam' api_password='1q2w3e'→˓api_host='node1' template='ubuntu-14.04-x86_64.tar.gz' state=absent
Notes
Note: Requires proxmoxer and requests modules on host. This modules can be installed with pip.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
puppet - Runs puppet
New in version 2.0.
530 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Runs puppet agent or apply in a reliable manner
Requirements
• puppet
Options
Examples
# Run puppet agent and fail if anything goes wrong- puppet
# Run puppet and timeout in 5 minutes- puppet: timeout=5m
# Run puppet using a different environment- puppet: environment=testing
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
pushbullet - Sends notifications to Pushbullet
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
1.6. Module Index 531
Ansible 1.2 Documentation, Release 0.01
• Notes
• This is an Extras Module
Synopsis
This module sends push notifications via Pushbullet to channels or devices.
Requirements
• pushbullet.py
Options
Examples
# Sends a push notification to a device- pushbullet:
api_key: "ABC123abc123ABC123abc123ABC123ab"device: "Chrome"title: "You may see this on Google Chrome"
# Sends a link to a device- pushbullet:
api_key: "ABC123abc123ABC123abc123ABC123ab"device: "Chrome"push_type: "link"title: "Ansible Documentation"body: "http://docs.ansible.com/"
# Sends a push notification to a channel- pushbullet:
api_key: "ABC123abc123ABC123abc123ABC123ab"channel: "my-awesome-channel"title: "Broadcasting a message to the #my-awesome-channel folks"
# Sends a push notification with title and body to a channel- pushbullet:
api_key: "ABC123abc123ABC123abc123ABC123ab"channel: "my-awesome-channel"title: "ALERT! Signup service is down"body: "Error rate on signup service is over 90% for more than 2 minutes"
Notes
Note: Requires pushbullet.py Python package on the remote host. You can install it via pip with ($ pip installpushbullet.py). See https://github.com/randomchars/pushbullet.py
532 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
pushover - Send notifications via u(https://pushover.net)
New in version 2.0.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Send notifications via pushover, to subscriber list of devices, and email addresses. Requires pushover app on devices.
Options
Examples
- local_action: pushover msg="{{inventory_hostname}} has exploded in flames,It is now time to panic" app_token=wxfdksl user_
→˓key=baa5fe97f2c5ab3ca8f0bb59
Notes
Note: You will require a pushover.net account to use this module. But no account is required to receive messages.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 533
Ansible 1.2 Documentation, Release 0.01
quantum_floating_ip - Add/Remove floating IP from an instance
• DEPRECATED
• Synopsis
• Requirements
• Options
• Examples
DEPRECATED
Deprecated in 2.0. Use os_floating_ip instead
Synopsis
Add or Remove a floating IP to an instance
Requirements
• python >= 2.6
• python-novaclient
• python-neutronclient or python-quantumclient
• python-keystoneclient
Options
Examples
# Assign a floating ip to the instance from an external network- quantum_floating_ip: state=present login_username=admin login_→˓password=admin
login_tenant_name=admin network_name=external_networkinstance_name=vm1 internal_network_name=internal_
→˓network
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
quantum_floating_ip_associate - Associate or disassociate a particular floating IP with an instance
• DEPRECATED
534 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
DEPRECATED
Deprecated in 2.0. Use os_floating_ip instead
Synopsis
Associates or disassociates a specific floating IP with a particular instance
Requirements
• python >= 2.6
• python-novaclient
• python-neutronclient or python-quantumclient
• python-keystoneclient
Options
Examples
# Associate a specific floating IP with an Instance- quantum_floating_ip_associate:
state=presentlogin_username=adminlogin_password=adminlogin_tenant_name=adminip_address=1.1.1.1instance_name=vm1
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
quantum_network - Creates/Removes networks from OpenStack
New in version 1.4.
• DEPRECATED
• Synopsis
1.6. Module Index 535
Ansible 1.2 Documentation, Release 0.01
• Requirements
• Options
• Examples
DEPRECATED
Deprecated in 2.0. Use os_network instead
Synopsis
Add or Remove network from OpenStack.
Requirements
• python >= 2.6
• python-neutronclient or python-quantumclient
• python-keystoneclient
Options
Examples
# Create a GRE backed Quantum network with tunnel id 1 for tenant1- quantum_network: name=t1network tenant_name=tenant1 state=present
provider_network_type=gre provider_segmentation_id=1login_username=admin login_password=admin login_tenant_
→˓name=admin
# Create an external network- quantum_network: name=external_network state=present
provider_network_type=local router_external=yeslogin_username=admin login_password=admin login_tenant_
→˓name=admin
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
quantum_router - Create or Remove router from openstack
• DEPRECATED
• Synopsis
• Requirements
• Options
536 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Examples
DEPRECATED
Deprecated in 2.0. Use os_router instead
Synopsis
Create or Delete routers from OpenStack
Requirements
• python >= 2.6
• python-neutronclient or python-quantumclient
• python-keystoneclient
Options
Examples
# Creates a router for tenant admin- quantum_router: state=present
login_username=adminlogin_password=adminlogin_tenant_name=adminname=router1"
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
quantum_router_gateway - set/unset a gateway interface for the router with the specified externalnetwork
• DEPRECATED
• Synopsis
• Requirements
• Options
• Examples
DEPRECATED
Deprecated in 2.0. Use os_router instead
1.6. Module Index 537
Ansible 1.2 Documentation, Release 0.01
Synopsis
Creates/Removes a gateway interface from the router, used to associate a external network with a router to routeexternal traffic.
Requirements
• python >= 2.6
• python-neutronclient or python-quantumclient
• python-keystoneclient
Options
Examples
# Attach an external network with a router to allow flow of external traffic- quantum_router_gateway: state=present login_username=admin login_→˓password=admin
login_tenant_name=admin router_name=external_routernetwork_name=external_network
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
quantum_router_interface - Attach/Dettach a subnet’s interface to a router
• DEPRECATED
• Synopsis
• Requirements
• Options
• Examples
DEPRECATED
Deprecated in 2.0. Use os_router instead
Synopsis
Attach/Dettach a subnet interface to a router, to provide a gateway for the subnet.
538 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Requirements
• python >= 2.6
• python-neutronclient or python-quantumclient
• python-keystoneclient
Options
Examples
# Attach tenant1's subnet to the external router- quantum_router_interface: state=present login_username=admin
login_password=adminlogin_tenant_name=admintenant_name=tenant1router_name=external_routesubnet_name=t1subnet
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
quantum_subnet - Add/remove subnet from a network
• DEPRECATED
• Synopsis
• Requirements
• Options
• Examples
DEPRECATED
Deprecated in 2.0. Use os_subnet instead
Synopsis
Add/remove subnet from a network
Requirements
• python >= 2.6
• python-neutronclient or python-quantumclient
• python-keystoneclient
1.6. Module Index 539
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Create a subnet for a tenant with the specified subnet- quantum_subnet: state=present login_username=admin login_password=admin
login_tenant_name=admin tenant_name=tenant1network_name=network1 name=net1subnet cidr=192.168.0.0/24"
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rabbitmq_binding - This module manages rabbitMQ bindings
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
This module uses rabbitMQ Rest API to create/delete bindings
Requirements
• python requests
Options
Examples
# Bind myQueue to directExchange with routing key info- rabbitmq_binding: name=directExchange destination=myQueue type=queue→˓routing_key=info
# Bind directExchange to topicExchange with routing key *.info- rabbitmq_binding: name=topicExchange destination=topicExchange→˓type=exchange routing_key="*.info"
540 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rabbitmq_exchange - This module manages rabbitMQ exchanges
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
This module uses rabbitMQ Rest API to create/delete exchanges
Requirements
• python requests
Options
Examples
# Create direct exchange- rabbitmq_exchange: name=directExchange
# Create topic exchange on vhost- rabbitmq_exchange: name=topicExchange type=topic vhost=myVhost
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 541
Ansible 1.2 Documentation, Release 0.01
rabbitmq_parameter - Adds or removes parameters to RabbitMQ
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manage dynamic, cluster-wide parameters for RabbitMQ
Options
Examples
# Set the federation parameter 'local_username' to a value of 'guest' (in→˓quotes)- rabbitmq_parameter: component=federation
name=local-usernamevalue='"guest"'state=present
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rabbitmq_plugin - Adds or removes plugins to RabbitMQ
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Enables or disables RabbitMQ plugins
542 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Enables the rabbitmq_management plugin- rabbitmq_plugin: names=rabbitmq_management state=enabled
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rabbitmq_policy - Manage the state of policies in RabbitMQ.
New in version 1.5.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manage the state of a virtual host in RabbitMQ.
Options
Examples
- name: ensure the default vhost contains the HA policy via a dictrabbitmq_policy: name=HA pattern='.*'args:
tags:"ha-mode": all
- name: ensure the default vhost contains the HA policyrabbitmq_policy: name=HA pattern='.*' tags="ha-mode=all"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 543
Ansible 1.2 Documentation, Release 0.01
rabbitmq_queue - This module manages rabbitMQ queues
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
This module uses rabbitMQ Rest API to create/delete queues
Requirements
• python requests
Options
Examples
# Create a queue- rabbitmq_queue: name=myQueue
# Create a queue on remote host- rabbitmq_queue: name=myRemoteQueue login_user=user login_password=secret→˓login_host=remote.example.org
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rabbitmq_user - Adds or removes users to RabbitMQ
• Synopsis
• Options
• Examples
• This is an Extras Module
544 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
Add or remove users to RabbitMQ and assign permissions
Options
Examples
# Add user to server and assign full access control- rabbitmq_user: user=joe
password=changemevhost=/configure_priv=.*read_priv=.*write_priv=.*state=present
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rabbitmq_vhost - Manage the state of a virtual host in RabbitMQ
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manage the state of a virtual host in RabbitMQ
Options
Examples
# Ensure that the vhost /test exists.- rabbitmq_vhost: name=/test state=present
1.6. Module Index 545
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
raw - Executes a low-down and dirty SSH command
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Executes a low-down and dirty SSH command, not going through the module subsystem. This is useful and shouldonly be done in two cases. The first case is installing python-simplejson on older (Python 2.4 and before) hoststhat need it as a dependency to run modules, since nearly all core modules require it. Another is speaking to anydevices such as routers that do not have any Python installed. In any other case, using the shell or command moduleis much more appropriate. Arguments given to raw are run directly through the configured remote shell. Standardoutput, error output and return code are returned when available. There is no change handler support for this module.This module does not require python on the remote system, much like the script module.
Options
Examples
# Bootstrap a legacy python 2.4 host- raw: yum -y install python-simplejson
# Bootstrap a host without python2 installed- raw: dnf install -y python2 python2-dnf libselinux-python
# Run a command that uses non-posix shell-isms (in this example /bin/sh# doesn't handle redirection and wildcards together but bash does)- raw: cat < /tmp/*txtargs:
executable: /bin/bash
Notes
546 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: If using raw from a playbook, you may need to disable fact gathering using gather_facts: no if you’reusing raw to bootstrap python onto the machine.
Note: If you want to execute a command securely and predictably, it may be better to use the command moduleinstead. Best practices when writing playbooks will follow the trend of using command unless shell is explicitlyrequired. When running ad-hoc commands, use your best judgement.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax - create / delete an instance in Rackspace Public Cloud
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
creates / deletes a Rackspace Public Cloud instance and optionally waits for it to be ‘running’.
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Build a Cloud Servergather_facts: Falsetasks:
- name: Server build request
1.6. Module Index 547
Ansible 1.2 Documentation, Release 0.01
local_action:module: raxcredentials: ~/.raxpubname: rax-test1flavor: 5image: b11d9567-e412-4255-96b9-bd63ab23bcfekey_name: my_rackspace_keyfiles:/root/test.txt: /home/localuser/test.txt
wait: yesstate: presentnetworks:- private- public
register: rax
- name: Build an exact count of cloud servers with incremented nameshosts: localgather_facts: Falsetasks:
- name: Server build requestslocal_action:module: raxcredentials: ~/.raxpubname: test%03d.example.orgflavor: performance1-1image: ubuntu-1204-lts-precise-pangolinstate: presentcount: 10count_offset: 10exact_count: yesgroup: testwait: yes
register: rax
Notes
Note: exact_count can be “destructive” if the number of running servers in the group is larger than that specified incount. In such a case, the state is effectively set to absent and the extra servers are deleted. In the case of deletion,the returned data structure will have action set to delete, and the oldest servers in the group will be deleted.
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
548 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_cbs - Manipulate Rackspace Cloud Block Storage Volumes
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Manipulate Rackspace Cloud Block Storage Volumes
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Build a Block Storage Volumegather_facts: Falsehosts: localconnection: localtasks:
- name: Storage volume create requestlocal_action:module: rax_cbscredentials: ~/.raxpubname: my-volume
1.6. Module Index 549
Ansible 1.2 Documentation, Release 0.01
description: My Volumevolume_type: SSDsize: 150region: DFWwait: yesstate: presentmeta:app: my-cool-app
register: my_volume
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_cbs_attachments - Manipulate Rackspace Cloud Block Storage Volume Attachments
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
550 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
Manipulate Rackspace Cloud Block Storage Volume Attachments
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Attach a Block Storage Volumegather_facts: Falsehosts: localconnection: localtasks:
- name: Storage volume attach requestlocal_action:module: rax_cbs_attachmentscredentials: ~/.raxpubvolume: my-volumeserver: my-serverdevice: /dev/xvddregion: DFWwait: yesstate: present
register: my_volume
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
1.6. Module Index 551
Ansible 1.2 Documentation, Release 0.01
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_cdb - create/delete or resize a Rackspace Cloud Databases instance
New in version 1.8.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
creates / deletes or resize a Rackspace Cloud Databases instance and optionally waits for it to be ‘running’. The nameoption needs to be unique since it’s used to identify the instance.
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Build a Cloud Databasesgather_facts: Falsetasks:
- name: Server build requestlocal_action:module: rax_cdbcredentials: ~/.raxpubregion: IADname: db-server1flavor: 1volume: 2cdb_type: MySQLcdb_version: 5.6wait: yes
552 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
state: presentregister: rax_db_server
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_cdb_database - create / delete a database in the Cloud Databases
New in version 1.8.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
create / delete a database in the Cloud Databases.
1.6. Module Index 553
Ansible 1.2 Documentation, Release 0.01
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Build a database in Cloud Databasestasks:
- name: Database build requestlocal_action:module: rax_cdb_databasecredentials: ~/.raxpubregion: IADcdb_id: 323e7ce0-9cb0-11e3-a5e2-0800200c9a66name: db1state: present
register: rax_db_database
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_cdb_user - create / delete a Rackspace Cloud Database
New in version 1.8.
554 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
create / delete a database in the Cloud Databases.
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Build a user in Cloud Databasestasks:
- name: User build requestlocal_action:module: rax_cdb_usercredentials: ~/.raxpubregion: IADcdb_id: 323e7ce0-9cb0-11e3-a5e2-0800200c9a66db_username: user1db_password: user1databases: ['db1']state: present
register: rax_db_user
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
1.6. Module Index 555
Ansible 1.2 Documentation, Release 0.01
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_clb - create / delete a load balancer in Rackspace Public Cloud
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
creates / deletes a Rackspace Public Cloud load balancer.
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Build a Load Balancergather_facts: Falsehosts: localconnection: localtasks:
- name: Load Balancer create request
556 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
local_action:module: rax_clbcredentials: ~/.raxpubname: my-lbport: 8080protocol: HTTPtype: SERVICENETtimeout: 30region: DFWwait: yesstate: presentmeta:app: my-cool-app
register: my_lb
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_clb_nodes - add, modify and remove nodes from a Rackspace Cloud Load Balancer
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
1.6. Module Index 557
Ansible 1.2 Documentation, Release 0.01
• Notes
• This is a Core Module
Synopsis
Adds, modifies and removes nodes from a Rackspace Cloud Load Balancer
Requirements
• python >= 2.6
• pyrax
Options
Examples
# Add a new node to the load balancer- local_action:
module: rax_clb_nodesload_balancer_id: 71address: 10.2.2.3port: 80condition: enabledtype: primarywait: yescredentials: /path/to/credentials
# Drain connections from a node- local_action:
module: rax_clb_nodesload_balancer_id: 71node_id: 410condition: drainingwait: yescredentials: /path/to/credentials
# Remove a node from the load balancer- local_action:
module: rax_clb_nodesload_balancer_id: 71node_id: 410state: absentwait: yescredentials: /path/to/credentials
Notes
558 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_clb_ssl - Manage SSL termination for a Rackspace Cloud Load Balancer.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Set up, reconfigure, or remove SSL termination for an existing load balancer.
Requirements
• python >= 2.6
• pyrax
1.6. Module Index 559
Ansible 1.2 Documentation, Release 0.01
Options
Examples
- name: Enable SSL termination on a load balancerrax_clb_ssl:
loadbalancer: the_loadbalancerstate: presentprivate_key: "{{ lookup('file', 'credentials/server.key' ) }}"certificate: "{{ lookup('file', 'credentials/server.crt' ) }}"intermediate_certificate: "{{ lookup('file', 'credentials/trust-chain.crt
→˓') }}"secure_traffic_only: truewait: true
- name: Disable SSL terminationrax_clb_ssl:
loadbalancer: "{{ registered_lb.balancer.id }}"state: absentwait: true
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_dns - Manage domains on Rackspace Cloud DNS
New in version 1.5.
560 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Manage domains on Rackspace Cloud DNS
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Create domainhosts: allgather_facts: Falsetasks:
- name: Domain create requestlocal_action:module: rax_dnscredentials: ~/.raxpubname: example.orgemail: [email protected]
register: rax_dns
Notes
Note: It is recommended that plays utilizing this module be run with serial: 1 to avoid exceeding the APIrequest limit imposed by the Rackspace CloudDNS API
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
1.6. Module Index 561
Ansible 1.2 Documentation, Release 0.01
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_dns_record - Manage DNS records on Rackspace Cloud DNS
New in version 1.5.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Manage DNS records on Rackspace Cloud DNS
Requirements
• python >= 2.6
• pyrax
Options
562 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
- name: Create DNS Recordshosts: allgather_facts: Falsetasks:
- name: Create A recordlocal_action:module: rax_dns_recordcredentials: ~/.raxpubdomain: example.orgname: www.example.orgdata: "{{ rax_accessipv4 }}"type: A
register: a_record
- name: Create PTR recordlocal_action:module: rax_dns_recordcredentials: ~/.raxpubserver: "{{ rax_id }}"name: "{{ inventory_hostname }}"region: DFW
register: ptr_record
Notes
Note: It is recommended that plays utilizing this module be run with serial: 1 to avoid exceeding the APIrequest limit imposed by the Rackspace CloudDNS API
Note: To manipulate a PTR record either loadbalancer or server must be supplied
Note: As of version 1.7, the type field is required and no longer defaults to an A record.
Note: PTR record support was added in version 1.7
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
1.6. Module Index 563
Ansible 1.2 Documentation, Release 0.01
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_facts - Gather facts for Rackspace Cloud Servers
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Gather facts for Rackspace Cloud Servers.
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Gather info about servershosts: allgather_facts: Falsetasks:
- name: Get facts about serverslocal_action:module: rax_factscredentials: ~/.raxpubname: "{{ inventory_hostname }}"region: DFW
564 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- name: Map some factsset_fact:ansible_ssh_host: "{{ rax_accessipv4 }}"
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_files - Manipulate Rackspace Cloud Files Containers
New in version 1.5.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Manipulate Rackspace Cloud Files Containers
1.6. Module Index 565
Ansible 1.2 Documentation, Release 0.01
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: "Test Cloud Files Containers"hosts: localgather_facts: notasks:
- name: "List all containers"rax_files: state=list
- name: "Create container called 'mycontainer'"rax_files: container=mycontainer
- name: "Create container 'mycontainer2' with metadata"rax_files:container: mycontainer2meta:key: valuefile_for: [email protected]
- name: "Set a container's web index page"rax_files: container=mycontainer web_index=index.html
- name: "Set a container's web error page"rax_files: container=mycontainer web_error=error.html
- name: "Make container public"rax_files: container=mycontainer public=yes
- name: "Make container public with a 24 hour TTL"rax_files: container=mycontainer public=yes ttl=86400
- name: "Make container private"rax_files: container=mycontainer private=yes
- name: "Test Cloud Files Containers Metadata Storage"hosts: localgather_facts: notasks:
- name: "Get mycontainer2 metadata"rax_files:container: mycontainer2type: meta
- name: "Set mycontainer2 metadata"rax_files:container: mycontainer2type: metameta:
566 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
uploaded_by: [email protected]
- name: "Remove mycontainer2 metadata"rax_files:container: "mycontainer2"type: metastate: absentmeta:key: ""file_for: ""
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_files_objects - Upload, download, and delete objects in Rackspace Cloud Files
New in version 1.5.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
1.6. Module Index 567
Ansible 1.2 Documentation, Release 0.01
Synopsis
Upload, download, and delete objects in Rackspace Cloud Files
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: "Test Cloud Files Objects"hosts: localgather_facts: Falsetasks:
- name: "Get objects from test container"rax_files_objects: container=testcont dest=~/Downloads/testcont
- name: "Get single object from test container"rax_files_objects: container=testcont src=file1 dest=~/Downloads/
→˓testcont
- name: "Get several objects from test container"rax_files_objects: container=testcont src=file1,file2,file3 dest=~/
→˓Downloads/testcont
- name: "Delete one object in test container"rax_files_objects: container=testcont method=delete dest=file1
- name: "Delete several objects in test container"rax_files_objects: container=testcont method=delete dest=file2,file3,
→˓file4
- name: "Delete all objects in test container"rax_files_objects: container=testcont method=delete
- name: "Upload all files to test container"rax_files_objects: container=testcont method=put src=~/Downloads/
→˓onehundred
- name: "Upload one file to test container"rax_files_objects: container=testcont method=put src=~/Downloads/
→˓testcont/file1
- name: "Upload one file to test container with metadata"rax_files_objects:container: testcontsrc: ~/Downloads/testcont/file2method: putmeta:testkey: testdatawho_uploaded_this: [email protected]
568 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- name: "Upload one file to test container with TTL of 60 seconds"rax_files_objects: container=testcont method=put src=~/Downloads/
→˓testcont/file3 expires=60
- name: "Attempt to get remote object that does not exist"rax_files_objects: container=testcont method=get
→˓src=FileThatDoesNotExist.jpg dest=~/Downloads/testcontignore_errors: yes
- name: "Attempt to delete remote object that does not exist"rax_files_objects: container=testcont method=delete
→˓dest=FileThatDoesNotExist.jpgignore_errors: yes
- name: "Test Cloud Files Objects Metadata"hosts: localgather_facts: falsetasks:
- name: "Get metadata on one object"rax_files_objects: container=testcont type=meta dest=file2
- name: "Get metadata on several objects"rax_files_objects: container=testcont type=meta src=file2,file1
- name: "Set metadata on an object"rax_files_objects:container: testconttype: metadest: file17method: putmeta:key1: value1key2: value2
clear_meta: true
- name: "Verify metadata is set"rax_files_objects: container=testcont type=meta src=file17
- name: "Delete metadata"rax_files_objects:container: testconttype: metadest: file17method: deletemeta:key1: ''key2: ''
- name: "Get metadata on all objects"rax_files_objects: container=testcont type=meta
Notes
1.6. Module Index 569
Ansible 1.2 Documentation, Release 0.01
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_identity - Load Rackspace Cloud Identity
New in version 1.5.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Verifies Rackspace Cloud credentials and returns identity information
Requirements
• python >= 2.6
• pyrax
570 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
- name: Load Rackspace Cloud Identitygather_facts: Falsehosts: localconnection: localtasks:
- name: Load Identitylocal_action:module: rax_identitycredentials: ~/.raxpubregion: DFW
register: rackspace_identity
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_keypair - Create a keypair for use with Rackspace Cloud Servers
New in version 1.5.
• Synopsis
• Requirements
• Options
1.6. Module Index 571
Ansible 1.2 Documentation, Release 0.01
• Examples
• Notes
• This is a Core Module
Synopsis
Create a keypair for use with Rackspace Cloud Servers
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Create a keypairhosts: localhostgather_facts: Falsetasks:
- name: keypair requestlocal_action:module: rax_keypaircredentials: ~/.raxpubname: my_keypairregion: DFW
register: keypair- name: Create local public key
local_action:module: copycontent: "{{ keypair.keypair.public_key }}"dest: "{{ inventory_dir }}/{{ keypair.keypair.name }}.pub"
- name: Create local private keylocal_action:module: copycontent: "{{ keypair.keypair.private_key }}"dest: "{{ inventory_dir }}/{{ keypair.keypair.name }}"
- name: Create a keypairhosts: localhostgather_facts: Falsetasks:
- name: keypair requestlocal_action:module: rax_keypaircredentials: ~/.raxpubname: my_keypairpublic_key: "{{ lookup('file', 'authorized_keys/id_rsa.pub') }}"region: DFW
register: keypair
572 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Notes
Note: Keypairs cannot be manipulated, only created and deleted. To “update” a keypair you must first delete and thenrecreate.
Note: The ability to specify a file path for the public key was added in 1.7
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_meta - Manipulate metadata for Rackspace Cloud Servers
New in version 1.7.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
1.6. Module Index 573
Ansible 1.2 Documentation, Release 0.01
Synopsis
Manipulate metadata for Rackspace Cloud Servers
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Set metadata for a serverhosts: allgather_facts: Falsetasks:
- name: Set metadatalocal_action:module: rax_metacredentials: ~/.raxpubname: "{{ inventory_hostname }}"region: DFWmeta:group: primary_groupgroups:- group_two- group_three
app: my_app
- name: Clear metadatalocal_action:module: rax_metacredentials: ~/.raxpubname: "{{ inventory_hostname }}"region: DFW
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
574 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_mon_alarm - Create or delete a Rackspace Cloud Monitoring alarm.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Create or delete a Rackspace Cloud Monitoring alarm that associates an existing rax_mon_entity, rax_mon_check,and rax_mon_notification_plan with criteria that specify what conditions will trigger which levels of notifi-cations. Rackspace monitoring module flow | rax_mon_entity -> rax_mon_check -> rax_mon_notification ->rax_mon_notification_plan -> rax_mon_alarm
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Alarm examplegather_facts: Falsehosts: localconnection: localtasks:- name: Ensure that a specific alarm exists.
rax_mon_alarm:
1.6. Module Index 575
Ansible 1.2 Documentation, Release 0.01
credentials: ~/.rax_pubstate: presentlabel: uhohentity_id: "{{ the_entity['entity']['id'] }}"check_id: "{{ the_check['check']['id'] }}"notification_plan_id: "{{ defcon1['notification_plan']['id'] }}"criteria: >if (rate(metric['average']) > 10) {return new AlarmStatus(WARNING);
}return new AlarmStatus(OK);
register: the_alarm
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_mon_check - Create or delete a Rackspace Cloud Monitoring check for an existing entity.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
576 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• This is an Extras Module
Synopsis
Create or delete a Rackspace Cloud Monitoring check associated with an existing rax_mon_entity. A check isa specific test or measurement that is performed, possibly from different monitoring zones, on the systems youmonitor. Rackspace monitoring module flow | rax_mon_entity -> rax_mon_check -> rax_mon_notification ->rax_mon_notification_plan -> rax_mon_alarm
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Create a monitoring checkgather_facts: Falsehosts: localconnection: localtasks:- name: Associate a check with an existing entity.
rax_mon_check:credentials: ~/.rax_pubstate: presententity_id: "{{ the_entity['entity']['id'] }}"label: the_checkcheck_type: remote.pingmonitoring_zones_poll: mziad,mzord,mzdfwdetails:count: 10
meta:hurf: durf
register: the_check
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
1.6. Module Index 577
Ansible 1.2 Documentation, Release 0.01
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_mon_entity - Create or delete a Rackspace Cloud Monitoring entity
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Create or delete a Rackspace Cloud Monitoring entity, which represents a device to monitor. Entities associate checksand alarms with a target system and provide a convenient, centralized place to store IP addresses. Rackspace mon-itoring module flow | rax_mon_entity -> rax_mon_check -> rax_mon_notification -> rax_mon_notification_plan ->rax_mon_alarm
Requirements
• python >= 2.6
• pyrax
Options
Examples
578 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- name: Entity examplegather_facts: Falsehosts: localconnection: localtasks:- name: Ensure an entity exists
rax_mon_entity:credentials: ~/.rax_pubstate: presentlabel: my_entitynamed_ip_addresses:web_box: 192.168.0.10db_box: 192.168.0.11
meta:hurf: durf
register: the_entity
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_mon_notification - Create or delete a Rackspace Cloud Monitoring notification.
New in version 2.0.
• Synopsis
• Requirements
• Options
1.6. Module Index 579
Ansible 1.2 Documentation, Release 0.01
• Examples
• Notes
• This is an Extras Module
Synopsis
Create or delete a Rackspace Cloud Monitoring notification that specifies a channel that can be used to commu-nicate alarms, such as email, webhooks, or PagerDuty. Rackspace monitoring module flow | rax_mon_entity ->rax_mon_check -> rax_mon_notification -> rax_mon_notification_plan -> rax_mon_alarm
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Monitoring notification examplegather_facts: Falsehosts: localconnection: localtasks:- name: Email me when something goes wrong.
rax_mon_entity:credentials: ~/.rax_publabel: omgtype: emaildetails:address: [email protected]
register: the_notification
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
580 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_mon_notification_plan - Create or delete a Rackspace Cloud Monitoring notification plan.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Create or delete a Rackspace Cloud Monitoring notification plan by associating existing rax_mon_notifications withseverity levels. Rackspace monitoring module flow | rax_mon_entity -> rax_mon_check -> rax_mon_notification ->rax_mon_notification_plan -> rax_mon_alarm
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Example notification plangather_facts: Falsehosts: localconnection: localtasks:- name: Establish who gets called when.
rax_mon_notification_plan:credentials: ~/.rax_pub
1.6. Module Index 581
Ansible 1.2 Documentation, Release 0.01
state: presentlabel: defcon1critical_state:- "{{ everyone['notification']['id'] }}"warning_state:- "{{ opsfloor['notification']['id'] }}"
register: defcon1
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_network - create / delete an isolated network in Rackspace Public Cloud
New in version 1.4.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
582 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
creates / deletes a Rackspace Public Cloud isolated network.
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Build an Isolated Networkgather_facts: False
tasks:- name: Network create request
local_action:module: rax_networkcredentials: ~/.raxpublabel: my-netcidr: 192.168.3.0/24state: present
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 583
Ansible 1.2 Documentation, Release 0.01
rax_queue - create / delete a queue in Rackspace Public Cloud
New in version 1.5.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
creates / deletes a Rackspace Public Cloud queue.
Requirements
• python >= 2.6
• pyrax
Options
Examples
- name: Build a Queuegather_facts: Falsehosts: localconnection: localtasks:
- name: Queue create requestlocal_action:module: rax_queuecredentials: ~/.raxpubname: my-queueregion: DFWstate: present
register: my_queue
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
584 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_scaling_group - Manipulate Rackspace Cloud Autoscale Groups
New in version 1.7.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Manipulate Rackspace Cloud Autoscale Groups
Requirements
• python >= 2.6
• pyrax
Options
1.6. Module Index 585
Ansible 1.2 Documentation, Release 0.01
Examples
---- hosts: localhostgather_facts: falseconnection: localtasks:
- rax_scaling_group:credentials: ~/.raxpubregion: ORDcooldown: 300flavor: performance1-1image: bb02b1a3-bc77-4d17-ab5b-421d89850fcamin_entities: 5max_entities: 10name: ASG Testserver_name: asgtestloadbalancers:
- id: 228385port: 80
register: asg
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rax_scaling_policy - Manipulate Rackspace Cloud Autoscale Scaling Policy
New in version 1.7.
586 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Manipulate Rackspace Cloud Autoscale Scaling Policy
Requirements
• python >= 2.6
• pyrax
Options
Examples
---- hosts: localhostgather_facts: falseconnection: localtasks:
- rax_scaling_policy:credentials: ~/.raxpubregion: ORDat: '2013-05-19T08:07:08Z'change: 25cooldown: 300is_percent: truename: ASG Test Policy - atpolicy_type: schedulescaling_group: ASG Test
register: asps_at
- rax_scaling_policy:credentials: ~/.raxpubregion: ORDcron: '1 0 * * *'change: 25cooldown: 300is_percent: truename: ASG Test Policy - cronpolicy_type: schedulescaling_group: ASG Test
register: asp_cron
1.6. Module Index 587
Ansible 1.2 Documentation, Release 0.01
- rax_scaling_policy:credentials: ~/.raxpubregion: ORDcooldown: 300desired_capacity: 5name: ASG Test Policy - webhookpolicy_type: webhookscaling_group: ASG Test
register: asp_webhook
Notes
Note: The following environment variables can be used, RAX_USERNAME, RAX_API_KEY, RAX_CREDS_FILE,RAX_CREDENTIALS, RAX_REGION.
Note: RAX_CREDENTIALS and RAX_CREDS_FILE points to a credentials file appropriate for pyrax. See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Note: RAX_USERNAME and RAX_API_KEY obviate the use of a credentials file
Note: RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rds - create, delete, or modify an Amazon rds instance
New in version 1.3.
• Synopsis
• Requirements
• Options
• Examples
• This is a Core Module
588 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
Creates, deletes, or modifies rds instances. When creating an instance it can be either a new instance or a read-onlyreplica of an existing instance. This module has a dependency on python-boto >= 2.5. The ‘promote’ commandrequires boto >= 2.18.0. Certain features such as tags rely on boto.rds2 (boto >= 2.26.0)
Requirements
• python >= 2.6
• boto
Options
Examples
# Basic mysql provisioning example- rds:
command: createinstance_name: new-databasedb_engine: MySQLsize: 10instance_type: db.m1.smallusername: mysql_adminpassword: 1nsecuretags:Environment: testingApplication: cms
# Create a read-only replica and wait for it to become available- rds:
command: replicateinstance_name: new-database-replicasource_instance: new_databasewait: yeswait_timeout: 600
# Delete an instance, but create a snapshot before doing so- rds:
command: deleteinstance_name: new-databasesnapshot: new_database_snapshot
# Get facts about an instance- rds:
command: factsinstance_name: new-databaseregister: new_database_facts
# Rename an instance and wait for the change to take effect- rds:
command: modifyinstance_name: new-databasenew_instance_name: renamed-database
1.6. Module Index 589
Ansible 1.2 Documentation, Release 0.01
wait: yes
# Reboot an instance and wait for it to become available again- rds
command: rebootinstance_name: databasewait: yes
# Restore a Postgres db instance from a snapshot, wait for it to become→˓available again, and# then modify it to add your security group. Also, display the new endpoint.# Note that the "publicly_accessible" option is allowed here just as it is→˓in the AWS CLI- local_action:
module: rdscommand: restoresnapshot: mypostgres-snapshotinstance_name: MyNewInstanceNameregion: us-west-2zone: us-west-2bsubnet: default-vpc-xx441xxxpublicly_accessible: yeswait: yeswait_timeout: 600tags:
Name: pg1_test_name_tagregister: rds
- local_action:module: rdscommand: modifyinstance_name: MyNewInstanceNameregion: us-west-2vpc_security_groups: sg-xxx945xx
- debug: msg="The new db endpoint is {{ rds.instance.endpoint }}"
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rds_param_group - manage RDS parameter groups
New in version 1.5.
• Synopsis
• Requirements
• Options
590 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Examples
• Notes
• This is a Core Module
Synopsis
Creates, modifies, and deletes RDS parameter groups. This module has a dependency on python-boto >= 2.5.
Requirements
• python >= 2.6
• boto
Options
Examples
# Add or change a parameter group, in this case setting auto_increment_→˓increment to 42 * 1024- rds_param_group:
state: presentname: norwegian_bluedescription: 'My Fancy Ex Parrot Group'engine: 'mysql5.6'params:
auto_increment_increment: "42K"
# Remove a parameter group- rds_param_group:
state: absentname: norwegian_blue
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
1.6. Module Index 591
Ansible 1.2 Documentation, Release 0.01
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rds_subnet_group - manage RDS database subnet groups
New in version 1.5.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Creates, modifies, and deletes RDS database subnet groups. This module has a dependency on python-boto >= 2.5.
Requirements
• python >= 2.6
• boto
Options
Examples
# Add or change a subnet group- rds_subnet_group
state: presentname: norwegian-bluedescription: My Fancy Ex Parrot Subnet Groupsubnets:- subnet-aaaaaaaa- subnet-bbbbbbbb
592 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# Remove a subnet group- rds_subnet_group:
state: absentname: norwegian-blue
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
redhat_subscription - Manage Red Hat Network registration and subscriptions using thesubscription-manager command
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Manage registration and subscription to the Red Hat Network entitlement platform.
1.6. Module Index 593
Ansible 1.2 Documentation, Release 0.01
Requirements
• subscription-manager
Options
Examples
# Register as user (joe_user) with password (somepass) and auto-subscribe to→˓available content.- redhat_subscription: state=present username=joe_user password=somepass→˓autosubscribe=true
# Register with activationkey (1-222333444) and consume subscriptions→˓matching# the names (Red hat Enterprise Server) and (Red Hat Virtualization)- redhat_subscription: state=present
activationkey=1-222333444pool='^(Red Hat Enterprise Server|Red Hat
→˓Virtualization)$'
# Update the consumed subscriptions from the previous example (remove the Red# Hat Virtualization subscription)- redhat_subscription: state=present
activationkey=1-222333444pool='^Red Hat Enterprise Server$'
Notes
Note: In order to register a system, subscription-manager requires either a username and password, or an activation-key.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
redis - Various redis commands, slave and flush
New in version 1.3.
• Synopsis
• Requirements
• Options
594 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Examples
• Notes
• This is an Extras Module
Synopsis
Unified utility to interact with redis instances. ‘slave’ sets a redis instance in slave or master mode. ‘flush’ flushes allthe instance or a specified db. ‘config’ (new in 1.6), ensures a configuration setting on an instance.
Requirements
• redis
Options
Examples
# Set local redis instance to be slave of melee.island on port 6377- redis: command=slave master_host=melee.island master_port=6377
# Deactivate slave mode- redis: command=slave slave_mode=master
# Flush all the redis db- redis: command=flush flush_mode=all
# Flush only one db in a redis instance- redis: command=flush db=1 flush_mode=db
# Configure local redis to have 10000 max clients- redis: command=config name=maxclients value=10000
# Configure local redis to have lua time limit of 100 ms- redis: command=config name=lua-time-limit value=100
Notes
Note: Requires the redis-py Python package on the remote host. You can install it with pip (pip install redis) or witha package manager. https://github.com/andymccurdy/redis-py
Note: If the redis master instance we are making slave of is password protected this needs to be in the redis.conf inthe masterauth variable
1.6. Module Index 595
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
replace - Replace all instances of a particular string in a file using a back-referenced regular expres-sion.
New in version 1.6.
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
This module will replace all instances of a pattern within a file. It is up to the user to maintain idempotence by ensuringthat the same pattern would never match any replacements made.
Options
Examples
- replace: dest=/etc/hosts regexp='(\s+)old\.host\.name(\s+.*)?$' replace=→˓'\1new.host.name\2' backup=yes
- replace: dest=/home/jdoe/.ssh/known_hosts regexp='^old\.host\.name[^\n]*\n→˓' owner=jdoe group=jdoe mode=644
- replace: dest=/etc/apache/ports regexp='^(NameVirtualHost|Listen)\s+80\s*$→˓' replace='\1 127.0.0.1:8080' validate='/usr/sbin/apache2ctl -f %s -t'
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rhn_channel - Adds or removes Red Hat software channels
596 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Adds or removes Red Hat software channels
Requirements
• none
Options
Examples
- rhn_channel: name=rhel-x86_64-server-v2vwin-6 sysname=server01 url=https://→˓rhn.redhat.com/rpc/api user=rhnuser password=guessme
Notes
Note: this module fetches the system id from RHN.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rhn_register - Manage Red Hat Network registration using the rhnreg_ks command
• Synopsis
• Requirements
• Options
1.6. Module Index 597
Ansible 1.2 Documentation, Release 0.01
• Examples
• Notes
• This is a Core Module
Synopsis
Manage registration to the Red Hat Network.
Requirements
• rhnreg_ks
Options
Examples
# Unregister system from RHN.- rhn_register: state=absent username=joe_user password=somepass
# Register as user (joe_user) with password (somepass) and auto-subscribe to→˓available content.- rhn_register: state=present username=joe_user password=somepass
# Register with activationkey (1-222333444) and enable extended update→˓support.- rhn_register: state=present activationkey=1-222333444 enable_eus=true
# Register with activationkey (1-222333444) and set a profilename which may→˓differ from the hostname.- rhn_register: state=present activationkey=1-222333444 profilename=host.→˓example.com.custom
# Register as user (joe_user) with password (somepass) against a satellite# server specified by (server_url).- rhn_register: >
state=presentusername=joe_userpassword=somepassserver_url=https://xmlrpc.my.satellite/XMLRPC
# Register as user (joe_user) with password (somepass) and enable# channels (rhel-x86_64-server-6-foo-1) and (rhel-x86_64-server-6-bar-1).- rhn_register: state=present username=joe_user
password=somepasschannels=rhel-x86_64-server-6-foo-1,rhel-x86_64-server-6-bar-
→˓1
Notes
598 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: In order to register a system, rhnreg_ks requires either a username and password, or an activationkey.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
riak - This module handles some common Riak operations
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
This module can be used to join nodes to a cluster, check the status of the cluster.
Options
Examples
# Join's a Riak node to another node- riak: command=join [email protected]
# Wait for handoffs to finish. Use with async and poll.- riak: wait_for_handoffs=yes
# Wait for riak_kv service to startup- riak: wait_for_service=kv
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rollbar_deployment - Notify Rollbar about app deployments
New in version 1.6.
1.6. Module Index 599
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Notify Rollbar about app deployments (see https://rollbar.com/docs/deploys_other/)
Options
Examples
- rollbar_deployment: token=AAAAAAenvironment='staging'user='ansible'revision=4.2,rollbar_user='admin',comment='Test Deploy'
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
route53 - add or delete entries in Amazons Route53 DNS service
New in version 1.3.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Creates and deletes DNS records in Amazons Route53 service
600 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Requirements
• python >= 2.6
• boto
Options
Examples
# Add new.foo.com as an A record with 3 IPs- route53:
command: createzone: foo.comrecord: new.foo.comtype: Attl: 7200value: 1.1.1.1,2.2.2.2,3.3.3.3
# Retrieve the details for new.foo.com- route53:
command: getzone: foo.comrecord: new.foo.comtype: A
register: rec
# Delete new.foo.com A record using the results from the get command- route53:
command: deletezone: foo.comrecord: "{{ rec.set.record }}"ttl: "{{ rec.set.ttl }}"type: "{{ rec.set.type }}"value: "{{ rec.set.value }}"
# Add an AAAA record. Note that because there are colons in the value# that the entire parameter list must be quoted:- route53:
command: "create"zone: "foo.com"record: "localhost.foo.com"type: "AAAA"ttl: "7200"value: "::1"
# Add a TXT record. Note that TXT and SPF records must be surrounded# by quotes when sent to Route 53:- route53:
command: "create"zone: "foo.com"record: "localhost.foo.com"type: "TXT"ttl: "7200"value: '"bar"'
1.6. Module Index 601
Ansible 1.2 Documentation, Release 0.01
# Add an alias record that points to an Amazon ELB:- route53:
command=createzone=foo.comrecord=elb.foo.comtype=Avalue="{{ elb_dns_name }}"alias=Truealias_hosted_zone_id="{{ elb_zone_id }}"
# Add an AAAA record with Hosted Zone ID. Note that because there are→˓colons in the value# that the entire parameter list must be quoted:- route53:
command: "create"zone: "foo.com"hosted_zone_id: "Z2AABBCCDDEEFF"record: "localhost.foo.com"type: "AAAA"ttl: "7200"value: "::1"
# Add an AAAA record with Hosted Zone ID. Note that because there are→˓colons in the value# that the entire parameter list must be quoted:- route53:
command: "create"zone: "foo.com"hosted_zone_id: "Z2AABBCCDDEEFF"record: "localhost.foo.com"type: "AAAA"ttl: "7200"value: "::1"
# Use a routing policy to distribute traffic:- route53:
command: "create"zone: "foo.com"record: "www.foo.com"type: "CNAME"value: "host1.foo.com"ttl: 30# Routing policyidentifier: "host1@www"weight: 100health_check: "d994b780-3150-49fd-9205-356abdd42e75"
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
602 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
route53_facts - Retrieves route53 details using AWS methods
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Gets various details related to Route53 zone, record set or health check details
Requirements
• python >= 2.6
• boto
Options
Examples
# Simple example of listing all hosted zones- name: List all hosted zonesroute53_facts:
query: hosted_zone
1.6. Module Index 603
Ansible 1.2 Documentation, Release 0.01
register: hosted_zones
# Getting a count of hosted zones- name: Return a count of all hosted zonesroute53_facts:
query: hosted_zonehosted_zone_method: count
register: hosted_zone_count
- name: List the first 20 resource record sets in a given hosted zoneroute53_facts:
profile: account_namequery: record_setshosted_zone_id: 'ZZZ1111112222'max_items: 20
register: record_sets
- name: List first 20 health checksroute53_facts:
query: health_checkhealth_check_method: listmax_items: 20
register: health_checks
- name: Get health check last failure_reasonroute53_facts:
query: health_checkhealth_check_method: failure_reasonhealth_check_id: '00000000-1111-2222-3333-12345678abcd'
register: health_check_failure_reason
- name: Retrieve reusable delegation set detailsroute53_facts:
query: reusable_delegation_setdelegation_set_id: 'delegation id'
register: delegation_sets
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
604 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
route53_health_check - add or delete health-checks in Amazons Route53 DNS service
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Creates and deletes DNS Health checks in Amazons Route53 service Only the port, resource_path, string_match andrequest_interval are considered when updating existing health-checks.
Requirements
• python >= 2.6
• boto
Options
Examples
# Create a health-check for host1.example.com and use it in record- route53_health_check:
state: presentfqdn: host1.example.comtype: HTTP_STR_MATCHresource_path: /string_match: "Hello"request_interval: 10failure_threshold: 2
register: my_health_check
- route53:action: createzone: "example.com"
1.6. Module Index 605
Ansible 1.2 Documentation, Release 0.01
type: CNAMErecord: "www.example.com"value: host1.example.comttl: 30# Routing policyidentifier: "host1@www"weight: 100health_check: "{{ my_health_check.health_check.id }}"
# Delete health-check- route53_health_check:
state: absentfqdn: host1.example.com
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
route53_zone - add or delete Route53 zones
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
606 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• This is an Extras Module
Synopsis
Creates and deletes Route53 private and public zones
Requirements
• python >= 2.6
• boto
Options
Examples
# create a public zone- route53_zone: zone=example.com state=present comment="this is an example"
# delete a public zone- route53_zone: zone=example.com state=absent
- name: private zone for develroute53_zome: zone=devel.example.com state=present vpc_id={{myvpc_id}}
→˓comment='developer domain'
# more complex example- name: register output after creating zone in parameterized regionroute53_zone:
vpc_id: "{{ vpc.vpc_id }}"vpc_region: "{{ ec2_region }}"zone: "{{ vpc_dns_zone }}"state: presentregister: zone_out
- debug: var=zone_out
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
1.6. Module Index 607
Ansible 1.2 Documentation, Release 0.01
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
rpm_key - Adds or removes a gpg key from the rpm db
New in version 1.3.
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
Adds or removes (rpm –import) a gpg key to your rpm database.
Options
Examples
# Example action to import a key from a url- rpm_key: state=present key=http://apt.sw.be/RPM-GPG-KEY.dag.txt
# Example action to import a key from a file- rpm_key: state=present key=/path/to/key.gpg
# Example action to ensure a key is not present in the db- rpm_key: state=absent key=DEADB33F
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
608 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
s3 - manage objects in S3.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
This module allows the user to manage S3 buckets and the objects within them. Includes support for creating anddeleting both objects and buckets, retrieving objects as files or strings and generating download links. This modulehas a dependency on python-boto.
Requirements
• boto
• python >= 2.6
Options
Examples
# Simple PUT operation- s3: bucket=mybucket object=/my/desired/key.txt src=/usr/local/myfile.txt→˓mode=put
# Simple GET operation- s3: bucket=mybucket object=/my/desired/key.txt dest=/usr/local/myfile.txt→˓mode=get
# Get a specific version of an object.- s3: bucket=mybucket object=/my/desired/key.txt→˓version=48c9ee5131af7a716edc22df9772aa6f dest=/usr/local/myfile.txt→˓mode=get
# PUT/upload with metadata- s3: bucket=mybucket object=/my/desired/key.txt src=/usr/local/myfile.txt→˓mode=put metadata='Content-Encoding=gzip,Cache-Control=no-cache'
# PUT/upload with custom headers- s3: bucket=mybucket object=/my/desired/key.txt src=/usr/local/myfile.txt→˓mode=put [email protected]
# List keys simple- s3: bucket=mybucket mode=list
1.6. Module Index 609
Ansible 1.2 Documentation, Release 0.01
# List keys all options- s3: bucket=mybucket mode=list prefix=/my/desired/ marker=/my/desired/0023.→˓txt max_keys=472
# Create an empty bucket- s3: bucket=mybucket mode=create permission=public-read
# Create a bucket with key as directory, in the EU region- s3: bucket=mybucket object=/my/directory/path mode=create region=eu-west-1
# Delete a bucket and all contents- s3: bucket=mybucket mode=delete
# GET an object but dont download if the file checksums match. New in 2.0- s3: bucket=mybucket object=/my/desired/key.txt dest=/usr/local/myfile.txt→˓mode=get overwrite=different
# Delete an object from a bucket- s3: bucket=mybucket object=/my/desired/key.txt mode=delobj
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
s3_bucket - Manage s3 buckets in AWS
New in version 2.0.
610 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manage s3 buckets in AWS
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
# Create a simple s3 bucket- s3_bucket:
name: mys3bucket
# Remove an s3 bucket and any keys it contains- s3_bucket:
name: mys3bucketstate: absentforce: yes
# Create a bucket, add a policy from a file, enable requester pays, enable→˓versioning and tag- s3_bucket:
name: mys3bucketpolicy: "{{ lookup('file','policy.json') }}"requester_pays: yesversioning: yestags:
example: tag1another: tag2
Notes
1.6. Module Index 611
Ansible 1.2 Documentation, Release 0.01
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
s3_lifecycle - Manage s3 bucket lifecycle rules in AWS
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manage s3 bucket lifecycle rules in AWS
Requirements
• boto
• python >= 2.6
• python-dateutil
612 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
# Configure a lifecycle rule on a bucket to expire (delete) items with a→˓prefix of /logs/ after 30 days- s3_lifecycle:
name: mybucketexpiration_days: 30prefix: /logs/status: enabledstate: present
# Configure a lifecycle rule to transition all items with a prefix of /logs/→˓to glacier after 7 days and then delete after 90 days- s3_lifecycle:
name: mybuckettransition_days: 7expiration_days: 90prefix: /logs/status: enabledstate: present
# Configure a lifecycle rule to transition all items with a prefix of /logs/→˓to glacier on 31 Dec 2020 and then delete on 31 Dec 2030. Note that→˓midnight GMT must be specified.# Be sure to quote your date strings- s3_lifecycle:
name: mybuckettransition_date: "2020-12-30T00:00:00.000Z"expiration_date: "2030-12-30T00:00:00.000Z"prefix: /logs/status: enabledstate: present
# Disable the rule created above- s3_lifecycle:
name: mybucketprefix: /logs/status: disabledstate: present
# Delete the lifecycle rule created above- s3_lifecycle:
name: mybucketprefix: /logs/state: absent
Notes
1.6. Module Index 613
Ansible 1.2 Documentation, Release 0.01
Note: If specifying expiration time as days then transition time must also be specified in days
Note: If specifying expiration time as a date then transition time must also be specified as a date
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
s3_logging - Manage logging facility of an s3 bucket in AWS
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manage logging facility of an s3 bucket in AWS
614 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
- name: Enable logging of s3 bucket mywebsite.com to s3 bucket mylogss3_logging:
name: mywebsite.comtarget_bucket: mylogstarget_prefix: logs/mywebsite.comstate: present
- name: Remove logging on an s3 buckets3_logging:
name: mywebsite.comstate: absent
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 615
Ansible 1.2 Documentation, Release 0.01
script - Runs a local script on a remote node after transferring it
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
The script module takes the script name followed by a list of space-delimited arguments. The local script at path willbe transferred to the remote node and then executed. The given script will be processed through the shell environmenton the remote node. This module does not require python on the remote system, much like the raw module.
Options
Examples
# Example from Ansible Playbooks- script: /some/local/script.sh --some-arguments 1234
# Run a script that creates a file, but only if the file is not yet created- script: /some/local/create_file.sh --some-arguments 1234 creates=/the/→˓created/file.txt
# Run a script that removes a file, but only if the file is not yet removed- script: /some/local/remove_file.sh --some-arguments 1234 removes=/the/→˓removed/file.txt
Notes
Note: It is usually preferable to write Ansible modules than pushing scripts. Convert your script to an Ansible modulefor bonus points!
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
616 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
seboolean - Toggles SELinux booleans.
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Toggles SELinux booleans.
Options
Examples
# Set (httpd_can_network_connect) flag on and keep it persistent across→˓reboots- seboolean: name=httpd_can_network_connect state=yes persistent=yes
Notes
Note: Not tested on any debian based system
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
selinux - Change policy and state of SELinux
• Synopsis
• Requirements
• Options
• Examples
• Notes
1.6. Module Index 617
Ansible 1.2 Documentation, Release 0.01
• This is a Core Module
Synopsis
Configures the SELinux mode and policy. A reboot may be required after usage. Ansible will not issue this reboot butwill let you know when it is required.
Requirements
• libselinux-python
Options
Examples
- selinux: policy=targeted state=enforcing- selinux: policy=targeted state=permissive- selinux: state=disabled
Notes
Note: Not tested on any debian based system
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
selinux_permissive - Change permissive domain in SELinux policy
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
618 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
Add and remove domain from the list of permissive domain.
Requirements
• policycoreutils-python
Options
Examples
- selinux_permissive: name=httpd_t permissive=true
Notes
Note: Requires a version of SELinux recent enough ( ie EL 6 or newer )
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
sendgrid - Sends an email with the SendGrid API
New in version 2.0.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Sends an email with a SendGrid account through their API, not through the SMTP service.
1.6. Module Index 619
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# send an email to a single recipient that the deployment was successful- sendgrid:
username: "{{ sendgrid_username }}"password: "{{ sendgrid_password }}"from_address: "[email protected]"to_addresses:- "[email protected]"
subject: "Deployment success."body: "The most recent Ansible deployment was successful."
delegate_to: localhost
# send an email to more than one recipient that the build failed- sendgrid
username: "{{ sendgrid_username }}"password: "{{ sendgrid_password }}"from_address: "[email protected]"to_addresses:- "[email protected]"- "[email protected]"
subject: "Build failure!."body: "Unable to pull source repository from Git server."
delegate_to: localhost
Notes
Note: This module is non-idempotent because it sends an email through the external API. It is idempotent only in thecase that the module fails.
Note: Like the other notification modules, this one requires an external dependency to work. In this case, you’ll needan active SendGrid account.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
sensu_check - Manage Sensu checks
New in version 2.0.
620 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manage the checks that should be run on a machine by Sensu. Most options do not have a default and will not beadded to the check definition unless specified. All defaults except path, state, backup and metric are not managed bythis module, they are simply specified for your convenience.
Options
Examples
# Fetch metrics about the CPU load every 60 seconds,# the sensu server has a handler called 'relay' which forwards stats to→˓graphite- name: get cpu metricssensu_check: name=cpu_load
command=/etc/sensu/plugins/system/cpu-mpstat-metrics.rbmetric=yes handlers=relay subscribers=common interval=60
# Check whether nginx is running- name: check nginx processsensu_check: name=nginx_running
command='/etc/sensu/plugins/processes/check-procs.rb -f /var/→˓run/nginx.pid'
handlers=default subscribers=nginx interval=60
# Stop monitoring the disk capacity.# Note that the check will still show up in the sensu dashboard,# to remove it completely you need to issue a DELETE request to the sensu→˓api.- name: check disksensu_check: name=check_disk_capacity state=absent
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
seport - Manages SELinux network port type definitions
New in version 2.0.
1.6. Module Index 621
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manages SELinux network port type definitions.
Requirements
• libselinux-python
• policycoreutils-python
Options
Examples
# Allow Apache to listen on tcp port 8888- seport: ports=8888 proto=tcp setype=http_port_t state=present# Allow sshd to listen on tcp port 8991- seport: ports=8991 proto=tcp setype=ssh_port_t state=present# Allow memcached to listen on tcp ports 10000-10100 and 10112- seport: ports=10000-10100,10112 proto=tcp setype=memcache_port_t→˓state=present
Notes
Note: The changes are persistent across reboots
Note: Not tested on any debian based system
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
622 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
service - Manage services.
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
Controls services on remote hosts. Supported init systems include BSD init, OpenRC, SysV, Solaris SMF, systemd,upstart.
Options
Examples
# Example action to start service httpd, if not running- service: name=httpd state=started
# Example action to stop service httpd, if running- service: name=httpd state=stopped
# Example action to restart service httpd, in all cases- service: name=httpd state=restarted
# Example action to reload service httpd, in all cases- service: name=httpd state=reloaded
# Example action to enable service httpd, and not touch the running state- service: name=httpd enabled=yes
# Example action to start service foo, based on running process /usr/bin/foo- service: name=foo pattern=/usr/bin/foo state=started
# Example action to restart network service for interface eth0- service: name=network state=restarted args=eth0
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
set_fact - Set host facts from a task
1.6. Module Index 623
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
This module allows setting new variables. Variables are set on a host-by-host basis just like facts discovered bythe setup module. These variables will survive between plays during an Ansible run, but will not be saved acrossexecutions even if you use a fact cache.
Options
Examples
# Example setting host facts using key=value pairs- set_fact: one_fact="something" other_fact="{{ local_var }}"
# Example setting host facts using complex arguments- set_fact:
one_fact: somethingother_fact: "{{ local_var * 2 }}"another_fact: "{{ some_registered_var.results | map(attribute='ansible_
→˓facts.some_fact') | list }}"
# As of 1.8, Ansible will convert boolean strings ('true', 'false', 'yes',→˓'no')# to proper boolean values when using the key=value syntax, however it is→˓still# recommended that booleans be set using the complex argument style:- set_fact:
one_fact: trueother_fact: false
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
setup - Gathers facts about remote hosts
• Synopsis
• Options
624 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Examples
• Notes
• This is a Core Module
Synopsis
This module is automatically called by playbooks to gather useful variables about remote hosts that can be used inplaybooks. It can also be executed directly by /usr/bin/ansible to check what variables are available to a host.Ansible provides many facts about the system, automatically.
Options
Examples
# Display facts from all hosts and store them indexed by I(hostname) at C(/→˓tmp/facts).ansible all -m setup --tree /tmp/facts
# Display only facts regarding memory found by ansible on all hosts and→˓output them.ansible all -m setup -a 'filter=ansible_*_mb'
# Display only facts returned by facter.ansible all -m setup -a 'filter=facter_*'
# Display only facts about certain interfaces.ansible all -m setup -a 'filter=ansible_eth[0-2]'
Notes
Note: More ansible facts will be added with successive releases. If facter or ohai are installed, variables fromthese programs will also be snapshotted into the JSON file for usage in templating. These variables are prefixed withfacter_ and ohai_ so it’s easy to tell their source. All variables are bubbled up to the caller. Using the ansiblefacts and choosing to not install facter and ohai means you can avoid Ruby-dependencies on your remote systems.(See also facter and ohai.)
Note: The filter option filters only the first level subkey below ansible_facts.
Note: If the target host is Windows, you will not currently have the ability to use fact_path or filter as this isprovided by a simpler implementation of the module. Different facts are returned for Windows hosts.
1.6. Module Index 625
Ansible 1.2 Documentation, Release 0.01
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
shell - Execute commands in nodes.
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
The shell module takes the command name followed by a list of space-delimited arguments. It is almost exactly likethe command module but runs the command through a shell (/bin/sh) on the remote node.
Options
Examples
# Execute the command in remote shell; stdout goes to the specified# file on the remote.- shell: somescript.sh >> somelog.txt
# Change the working directory to somedir/ before executing the command.- shell: somescript.sh >> somelog.txt chdir=somedir/
# You can also use the 'args' form to provide the options. This command# will change the working directory to somedir/ and will only run when# somedir/somelog.txt doesn't exist.- shell: somescript.sh >> somelog.txtargs:
chdir: somedir/creates: somelog.txt
# Run a command that uses non-posix shell-isms (in this example /bin/sh# doesn't handle redirection and wildcards together but bash does)- shell: cat < /tmp/*txtargs:
executable: /bin/bash
Notes
626 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: If you want to execute a command securely and predictably, it may be better to use the command moduleinstead. Best practices when writing playbooks will follow the trend of using command unless shell is explicitlyrequired. When running ad-hoc commands, use your best judgement.
Note: To sanitize any variables passed to the shell module, you should use “{{ var | quote }}” instead of just “{{ var}}” to make sure they don’t include evil things like semicolons.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
slack - Send Slack notifications
New in version 1.6.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
The slack module sends notifications to http://slack.com via the Incoming WebHook integration
Options
Examples
- name: Send notification message via Slacklocal_action:
module: slacktoken: thetoken/generatedby/slackmsg: "{{ inventory_hostname }} completed"
- name: Send notification message via Slack all optionslocal_action:
module: slacktoken: thetoken/generatedby/slackmsg: "{{ inventory_hostname }} completed"channel: "#ansible"username: "Ansible on {{ inventory_hostname }}"
1.6. Module Index 627
Ansible 1.2 Documentation, Release 0.01
icon_url: "http://www.example.com/some-image-file.png"link_names: 0parse: 'none'
- name: insert a color bar in front of the message for visibility purposes→˓and use the default webhook icon and name configured in Slackslack:
token: thetoken/generatedby/slackmsg: "{{ inventory_hostname }} is alive!"color: goodusername: ""icon_url: ""
- name: Use the attachments APIslack:
token: thetoken/generatedby/slackattachments:
- text: "Display my system load on host A and B"color: "#ff00dd"title: "System load"fields:- title: "System A"value: "load average: 0,74, 0,66, 0,63"short: "true"
- title: "System B"value: "load average: 5,16, 4,64, 2,43"short: "true"
- name: Send notification message via Slack (deprecated API using domian)local_action:
module: slackdomain: future500.slack.comtoken: thetokengeneratedbyslackmsg: "{{ inventory_hostname }} completed"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
slackpkg - Package manager for Slackware >= 12.2
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
628 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
Manage binary packages for Slackware using ‘slackpkg’ which is available in versions after 12.2.
Requirements
• Slackware >= 12.2
Options
Examples
# Install package foo- slackpkg: name=foo state=present
# Remove packages foo and bar- slackpkg: name=foo,bar state=absent
# Make sure that it is the most updated package- slackpkg: name=foo state=latest
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
slurp - Slurps a file from remote nodes
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
This module works like fetch. It is used for fetching a base64- encoded blob containing the data in a remote file.
Options
1.6. Module Index 629
Ansible 1.2 Documentation, Release 0.01
Examples
ansible host -m slurp -a 'src=/tmp/xx'host | success >> {
"content": "aGVsbG8gQW5zaWJsZSB3b3JsZAo=","encoding": "base64"
}
Notes
Note: See also: fetch
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
snmp_facts - Retrive facts for a device using SNMP.
New in version 1.9.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Retrieve facts for a device using SNMP, the facts will be inserted to the ansible_facts key.
Requirements
• pysnmp
Options
630 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
# Gather facts with SNMP version 2- snmp_facts: host={{ inventory_hostname }} version=2c community=publicconnection: local
# Gather facts using SNMP version 3- snmp_facts:
host={{ inventory_hostname }}version=v3level=authPrivintegrity=shaprivacy=aesusername=snmp-userauthkey=abc12345privkey=def6789
delegate_to: localhost
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
sns - Send Amazon Simple Notification Service (SNS) messages
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
The sns module sends notifications to a topic on your Amazon SNS account
Requirements
• boto
Options
1.6. Module Index 631
Ansible 1.2 Documentation, Release 0.01
Examples
- name: Send default notification message via SNSlocal_action:
module: snsmsg: "{{ inventory_hostname }} has completed the play."subject: "Deploy complete!"topic: "deploy"
- name: Send notification messages via SNS with short message for SMSlocal_action:
module: snsmsg: "{{ inventory_hostname }} has completed the play."sms: "deployed!"subject: "Deploy complete!"topic: "deploy"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
sns_topic - Manages AWS SNS topics and subscriptions
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
The sns_topic module allows you to create, delete, and manage subscriptions for AWS SNS topics.
Requirements
• boto
• python >= 2.6
632 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
- name: Create alarm SNS topicsns_topic:
name: "alarms"state: presentdisplay_name: "alarm SNS topic"delivery_policy:
http:defaultHealthyRetryPolicy:
minDelayTarget: 2maxDelayTarget: 4numRetries: 3numMaxDelayRetries: 5backoffFunction: "<linear|arithmetic|geometric|exponential>"
disableSubscriptionOverrides: TruedefaultThrottlePolicy:
maxReceivesPerSecond: 10subscriptions:- endpoint: "[email protected]"protocol: "email"
- endpoint: "my_mobile_number"protocol: "sms"
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
1.6. Module Index 633
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
solaris_zone - Manage Solaris zones
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Create, start, stop and delete Solaris zones. This module doesn’t currently allow changing of options for a zone that’salready been created.
Requirements
• Solaris 10 or 11
Options
Examples
# Create and install a zone, but don't boot itsolaris_zone: name=zone1 state=present path=/zones/zone1 sparse=true root_→˓password="Be9oX7OSwWoU."
config='set autoboot=true; add net; set physical=bge0; set address=10.→˓1.1.1; end'
# Create and install a zone and boot itsolaris_zone: name=zone1 state=running path=/zones/zone1 root_password=→˓"Be9oX7OSwWoU."
config='set autoboot=true; add net; set physical=bge0; set address=10.→˓1.1.1; end'
# Boot an already installed zonesolaris_zone: name=zone1 state=running
# Stop a zonesolaris_zone: name=zone1 state=stopped
# Destroy a zonesolaris_zone: name=zone1 state=absent
634 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# Detach a zonesolaris_zone: name=zone1 state=detached
# Configure a zone, ready to be attachedsolaris_zone: name=zone1 state=configured path=/zones/zone1 root_password=→˓"Be9oX7OSwWoU."
config='set autoboot=true; add net; set physical=bge0; set address=10.→˓1.1.1; end'
# Attach a zonesolaris_zone: name=zone1 state=attached attach_options='-u'
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
sqs_queue - Creates or deletes AWS SQS queues.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Create or delete AWS SQS queues. Update attributes on existing queues.
Requirements
• boto
• boto >= 2.33.0
• python >= 2.6
Options
1.6. Module Index 635
Ansible 1.2 Documentation, Release 0.01
Examples
# Create SQS queue- sqs_queue:
name: my-queueregion: ap-southeast-2default_visibility_timeout: 120message_retention_period: 86400maximum_message_size: 1024delivery_delay: 30receive_message_wait_time: 20
# Delete SQS queue- sqs_queue:
name: my-queueregion: ap-southeast-2state: absent
Notes
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
stackdriver - Send code deploy and annotation events to stackdriver
New in version 1.6.
• Synopsis
• Options
636 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Examples
• This is an Extras Module
Synopsis
Send code deploy and annotation events to Stackdriver
Options
Examples
- stackdriver: key=AAAAAA event=deploy deployed_to=production deployed_→˓by=leeroyjenkins repository=MyWebApp revision_id=abcd123
- stackdriver: key=AAAAAA event=annotation msg="Greetings from Ansible"→˓annotated_by=leeroyjenkins level=WARN instance_id=i-abcd1234
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
stat - retrieve file or file system status
New in version 1.3.
• Synopsis
• Options
• Examples
• Return Values
• This is a Core Module
Synopsis
Retrieves facts for a file similar to the linux/unix ‘stat’ command.
Options
1.6. Module Index 637
Ansible 1.2 Documentation, Release 0.01
Examples
# Obtain the stats of /etc/foo.conf, and check that the file still belongs# to 'root'. Fail otherwise.- stat: path=/etc/foo.confregister: st
- fail: msg="Whoops! file ownership has changed"when: st.stat.pw_name != 'root'
# Determine if a path exists and is a symlink. Note that if the path does# not exist, and we test sym.stat.islnk, it will fail with an error. So# therefore, we must test whether it is defined.# Run this to understand the structure, the skipped ones do not pass the# check performed by 'when'- stat: path=/path/to/somethingregister: sym
- debug: msg="islnk isn't defined (path doesn't exist)"when: sym.stat.islnk is not defined
- debug: msg="islnk is defined (path must exist)"when: sym.stat.islnk is defined
- debug: msg="Path exists and is a symlink"when: sym.stat.islnk is defined and sym.stat.islnk
- debug: msg="Path exists and isn't a symlink"when: sym.stat.islnk is defined and sym.stat.islnk == False
# Determine if a path exists and is a directory. Note that we need to test# both that p.stat.isdir actually exists, and also that it's set to true.- stat: path=/path/to/somethingregister: p
- debug: msg="Path exists and is a directory"when: p.stat.isdir is defined and p.stat.isdir
# Don't do md5 checksum- stat: path=/path/to/myhugefile get_md5=no
# Use sha256 to calculate checksum- stat: path=/path/to/something checksum_algorithm=sha256
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
sts_assume_role - Assume a role using AWS Security Token Service and obtain temporary creden-tials
New in version 2.0.
638 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Assume a role using AWS Security Token Service and obtain temporary credentials
Requirements
• python >= 2.6
• boto
Options
Examples
# Note: These examples do not set authentication details, see the AWS Guide→˓for details.
# Assume an existing role (more details: http://docs.aws.amazon.com/STS/→˓latest/APIReference/API_AssumeRole.html)sts_assume_role:role_arn: "arn:aws:iam::123456789012:role/someRole"role_session_name: "someRoleSession"
register: assumed_role
# Use the assumed role above to tag an instance in account 123456789012ec2_tag:aws_access_key: "{{ assumed_role.sts_creds.access_key }}"aws_secret_key: "{{ assumed_role.sts_creds.secret_key }}"security_token: "{{ assumed_role.sts_creds.session_token }}"resource: i-xyzxyz01state: presenttags:
MyNewTag: value
Notes
1.6. Module Index 639
Ansible 1.2 Documentation, Release 0.01
Note: In order to use the assumed role in a following playbook task you must pass the access_key, access_secret andaccess_token
Note: If parameters are not set within the module, the following environment variables can be used in decreasing orderof precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY,AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN orEC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION
Note: Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html
Note: AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but thiscan also be configured in the boto config file
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
subversion - Deploys a subversion repository.
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Deploy given repository URL / revision to dest. If dest exists, update to the specified revision, otherwise perform acheckout.
Options
640 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
# Checkout subversion repository to specified folder.- subversion: repo=svn+ssh://an.example.org/path/to/repo dest=/src/checkout
# Export subversion directory to folder- subversion: repo=svn+ssh://an.example.org/path/to/repo dest=/src/export→˓export=True
Notes
Note: Requires svn to be installed on the client.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
supervisorctl - Manage the state of a program or group of programs running via supervisord
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Manage the state of a program or group of programs running via supervisord
Requirements
• supervisorctl
Options
1.6. Module Index 641
Ansible 1.2 Documentation, Release 0.01
Examples
# Manage the state of program to be in 'started' state.- supervisorctl: name=my_app state=started
# Manage the state of program group to be in 'started' state.- supervisorctl: name='my_apps:' state=started
# Restart my_app, reading supervisorctl configuration from a specified file.- supervisorctl: name=my_app state=restarted config=/var/opt/my_project/→˓supervisord.conf
# Restart my_app, connecting to supervisord with credentials and server URL.- supervisorctl: name=my_app state=restarted username=test password=testpass→˓server_url=http://localhost:9001
Notes
Note: When state = present, the module will call supervisorctl reread then supervisorctl add ifthe program/group does not exist.
Note: When state = restarted, the module will call supervisorctl update then call supervisorctlrestart.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
svc - Manage daemontools services.
New in version None.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Controls daemontools services on remote hosts using the svc utility.
642 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Example action to start svc dnscache, if not running- svc: name=dnscache state=started
# Example action to stop svc dnscache, if running- svc: name=dnscache state=stopped
# Example action to kill svc dnscache, in all cases- svc : name=dnscache state=killed
# Example action to restart svc dnscache, in all cases- svc : name=dnscache state=restarted
# Example action to reload svc dnscache, in all cases- svc: name=dnscache state=reloaded
# Example using alt svc directory location- svc: name=dnscache state=reloaded service_dir=/var/service
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
svr4pkg - Manage Solaris SVR4 packages
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manages SVR4 packages on Solaris 10 and 11. These were the native packages on Solaris <= 10 and are availableas a legacy feature in Solaris 11. Note that this is a very basic packaging system. It will not enforce dependencies oninstall or remove.
Options
1.6. Module Index 643
Ansible 1.2 Documentation, Release 0.01
Examples
# Install a package from an already copied file- svr4pkg: name=CSWcommon src=/tmp/cswpkgs.pkg state=present
# Install a package directly from an http site- svr4pkg: name=CSWpkgutil src=http://get.opencsw.org/now state=present→˓zone=current
# Install a package with a response file- svr4pkg: name=CSWggrep src=/tmp/third-party.pkg response_file=/tmp/ggrep.→˓response state=present
# Ensure that a package is not installed.- svr4pkg: name=SUNWgnome-sound-recorder state=absent
# Ensure that a category is not installed.- svr4pkg: name=FIREFOX state=absent category=true
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
swdepot - Manage packages with swdepot package manager (HP-UX)
New in version 1.4.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Will install, upgrade and remove packages with swdepot package manager (HP-UX)
Options
Examples
- swdepot: name=unzip-6.0 state=installed depot=repository:/path- swdepot: name=unzip state=latest depot=repository:/path- swdepot: name=unzip state=absent
644 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
synchronize - Uses rsync to make synchronizing file paths in your playbooks quick and easy.
New in version 1.4.
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
synchronize is a wrapper around the rsync command, meant to make common tasks with rsync easier. It is runand originates on the local host where Ansible is being run. Of course, you could just use the command action to callrsync yourself, but you also have to add a fair number of boilerplate options and host facts. You still may need to callrsync directly via command or shell depending on your use case. synchronize does not provide access to thefull power of rsync, but does make most invocations easier to follow.
Options
Examples
# Synchronization of src on the control machine to dest on the remote hostssynchronize: src=some/relative/path dest=/some/absolute/path
# Synchronization without any --archive options enabledsynchronize: src=some/relative/path dest=/some/absolute/path archive=no
# Synchronization with --archive options enabled except for --recursivesynchronize: src=some/relative/path dest=/some/absolute/path recursive=no
# Synchronization with --archive options enabled except for --times, with --→˓checksum option enabledsynchronize: src=some/relative/path dest=/some/absolute/path checksum=yes→˓times=no
# Synchronization without --archive options enabled except use --linkssynchronize: src=some/relative/path dest=/some/absolute/path archive=no→˓links=yes
# Synchronization of two paths both on the control machine
1.6. Module Index 645
Ansible 1.2 Documentation, Release 0.01
local_action: synchronize src=some/relative/path dest=/some/absolute/path
# Synchronization of src on the inventory host to the dest on the localhost→˓in pull modesynchronize: mode=pull src=some/relative/path dest=/some/absolute/path
# Synchronization of src on delegate host to dest on the current inventory→˓host.synchronize:
src: /first/absolute/pathdest: /second/absolute/path
delegate_to: delegate.host
# Synchronize two directories on one remote host.synchronize:
src: /first/absolute/pathdest: /second/absolute/path
delegate_to: "{{ inventory_hostname }}"
# Synchronize and delete files in dest on the remote host that are not found→˓in src of localhost.synchronize: src=some/relative/path dest=/some/absolute/path delete=yes
# Synchronize using an alternate rsync command# This specific command is granted su privileges on the destinationsynchronize: src=some/relative/path dest=/some/absolute/path rsync_path="su -→˓c rsync"
# Example .rsync-filter file in the source directory- var # exclude any path whose last part is 'var'- /var # exclude any path starting with 'var' starting at the source→˓directory+ /var/conf # include /var/conf even though it was previously excluded
# Synchronize passing in extra rsync optionssynchronize:
src: /tmp/helloworlddest: /var/www/hellowordrsync_opts:
- "--no-motd"- "--exclude=.git"
Notes
Note: rsync must be installed on both the local and remote host.
Note: For the synchronize module, the “local host” is the host the synchronize task originates on, and the“destination host” is the host synchronize is connecting to.
Note: The “local host” can be changed to a different host by using delegate_to. This enables copying between two
646 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
remote hosts or entirely on one remote machine.
Note: The user and permissions for the synchronize src are those of the user running the Ansible task on the localhost (or the remote_user for a delegate_to host when delegate_to is used).
Note: The user and permissions for the synchronize dest are those of the remote_user on the destination host or thebecome_user if become=yes is active.
Note: In 2.0.0.0 a bug in the synchronize module made become occur on the “local host”. This was fixed in 2.0.1.
Note: Expect that dest=~/x will be ~<remote_user>/x even if using sudo.
Note: Inspect the verbose output to validate the destination user/host/path are what was expected.
Note: To exclude files and directories from being synchronized, you may add .rsync-filter files to the sourcedirectory.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
sysctl - Manage entries in sysctl.conf.
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
This module manipulates sysctl entries and optionally performs a /sbin/sysctl -p after changing them.
1.6. Module Index 647
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Set vm.swappiness to 5 in /etc/sysctl.conf- sysctl: name=vm.swappiness value=5 state=present
# Remove kernel.panic entry from /etc/sysctl.conf- sysctl: name=kernel.panic state=absent sysctl_file=/etc/sysctl.conf
# Set kernel.panic to 3 in /tmp/test_sysctl.conf- sysctl: name=kernel.panic value=3 sysctl_file=/tmp/test_sysctl.conf→˓reload=no
# Set ip forwarding on in /proc and do not reload the sysctl file- sysctl: name="net.ipv4.ip_forward" value=1 sysctl_set=yes
# Set ip forwarding on in /proc and in the sysctl file and reload if→˓necessary- sysctl: name="net.ipv4.ip_forward" value=1 sysctl_set=yes state=present→˓reload=yes
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
taiga_issue - Creates/deletes an issue in a Taiga Project Management Platform
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Creates/deletes an issue in a Taiga Project Management Platform (https://taiga.io). An issue is identified by the com-bination of project, issue subject and issue type. This module implements the creation or deletion of issues (not theupdate).
648 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Requirements
• python-taiga
Options
Examples
# Create an issue in the my hosted Taiga environment and attach an error log- taiga_issue:
taiga_host: https://mytaigahost.example.comproject: myprojectsubject: An error has been foundissue_type: Bugpriority: Highstatus: Newseverity: Importantdescription: An error has been found. Please check the attached error
→˓log for details.attachment: /path/to/error.logattachment_description: Error log filetags:- Error- Needs manual check
state: present
# Deletes the previously created issue- taiga_issue:
taiga_host: https://mytaigahost.example.comproject: myprojectsubject: An error has been foundissue_type: Bugstate: absent
Notes
Note: The authentication is achieved either by the environment variable TAIGA_TOKEN or by the pair of environ-ment variables TAIGA_USERNAME and TAIGA_PASSWORD
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
template - Templates a file out to a remote server.
1.6. Module Index 649
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Templates are processed by the Jinja2 templating language (http://jinja.pocoo.org/docs/) - documentation on the tem-plate formatting can be found in the Template Designer Documentation (http://jinja.pocoo.org/docs/templates/). Sixadditional variables can be used in templates: ansible_managed (configurable via the defaults section ofansible.cfg) contains a string which can be used to describe the template name, host, modification time of the tem-plate file and the owner uid, template_host contains the node name of the template’s machine, template_uidthe owner, template_path the absolute path of the template, template_fullpath is the absolute path of thetemplate, and template_run_date is the date that the template was rendered. Note that including a string thatuses a date in the template will result in the template being marked ‘changed’ each time.
Options
Examples
# Example from Ansible Playbooks- template: src=/mytemplates/foo.j2 dest=/etc/file.conf owner=bin→˓group=wheel mode=0644
# The same example, but using symbolic modes equivalent to 0644- template: src=/mytemplates/foo.j2 dest=/etc/file.conf owner=bin→˓group=wheel mode="u=rw,g=r,o=r"
# Copy a new "sudoers" file into place, after passing validation with visudo- template: src=/mine/sudoers dest=/etc/sudoers validate='visudo -cf %s'
Notes
Note: Since Ansible version 0.9, templates are loaded with trim_blocks=True.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
650 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
twilio - Sends a text message to a mobile phone through Twilio.
New in version 1.6.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Sends a text message to a phone number through the Twilio messaging API.
Options
Examples
# send an SMS about the build status to (555) 303 5681# note: replace account_sid and auth_token values with your credentials# and you have to have the 'from_number' on your Twilio account- twilio:
msg: "All servers with webserver role are now configured."account_sid: "ACXXXXXXXXXXXXXXXXX"auth_token: "ACXXXXXXXXXXXXXXXXX"from_number: "+15552014545"to_number: "+15553035681"
delegate_to: localhost
# send an SMS to multiple phone numbers about the deployment# note: replace account_sid and auth_token values with your credentials# and you have to have the 'from_number' on your Twilio account- twilio:
msg: "This server's configuration is now complete."account_sid: "ACXXXXXXXXXXXXXXXXX"auth_token: "ACXXXXXXXXXXXXXXXXX"from_number: "+15553258899"to_number:
- "+15551113232"- "+12025551235"- "+19735559010"
delegate_to: localhost
# send an MMS to a single recipient with an update on the deployment# and an image of the results# note: replace account_sid and auth_token values with your credentials# and you have to have the 'from_number' on your Twilio account- twilio:
msg: "Deployment complete!"account_sid: "ACXXXXXXXXXXXXXXXXX"
1.6. Module Index 651
Ansible 1.2 Documentation, Release 0.01
auth_token: "ACXXXXXXXXXXXXXXXXX"from_number: "+15552014545"to_number: "+15553035681"media_url: "https://demo.twilio.com/logo.png"
delegate_to: localhost
Notes
Note: This module is non-idempotent because it sends an email through the external API. It is idempotent only in thecase that the module fails.
Note: Like the other notification modules, this one requires an external dependency to work. In this case, you’ll needa Twilio account with a purchased or verified phone number to send the text message.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
typetalk - Send a message to typetalk
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Send a message to typetalk using typetalk API ( http://developers.typetalk.in/ )
Requirements
• json
652 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
- typetalk: client_id=12345 client_secret=12345 topic=1 msg="install→˓completed"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
ufw - Manage firewall with UFW
New in version 1.6.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manage firewall with UFW.
Requirements
• ufw package
Options
Examples
# Allow everything and enable UFWufw: state=enabled policy=allow
# Set loggingufw: logging=on
# Sometimes it is desirable to let the sender know when traffic is
1.6. Module Index 653
Ansible 1.2 Documentation, Release 0.01
# being denied, rather than simply ignoring it. In these cases, use# reject instead of deny. In addition, log rejected connections:ufw: rule=reject port=auth log=yes
# ufw supports connection rate limiting, which is useful for protecting# against brute-force login attacks. ufw will deny connections if an IP# address has attempted to initiate 6 or more connections in the last# 30 seconds. See http://www.debian-administration.org/articles/187# for details. Typical usage is:ufw: rule=limit port=ssh proto=tcp
# Allow OpenSSHufw: rule=allow name=OpenSSH
# Delete OpenSSH ruleufw: rule=allow name=OpenSSH delete=yes
# Deny all access to port 53:ufw: rule=deny port=53
# Allow all access to tcp port 80:ufw: rule=allow port=80 proto=tcp
# Allow all access from RFC1918 networks to this host:ufw: rule=allow src={{ item }}with_items:- 10.0.0.0/8- 172.16.0.0/12- 192.168.0.0/16
# Deny access to udp port 514 from host 1.2.3.4:ufw: rule=deny proto=udp src=1.2.3.4 port=514
# Allow incoming access to eth0 from 1.2.3.5 port 5469 to 1.2.3.4 port 5469ufw: rule=allow interface=eth0 direction=in proto=udp src=1.2.3.5 from_→˓port=5469 dest=1.2.3.4 to_port=5469
# Deny all traffic from the IPv6 2001:db8::/32 to tcp port 25 on this host.# Note that IPv6 must be enabled in /etc/default/ufw for IPv6 firewalling to→˓work.ufw: rule=deny proto=tcp src=2001:db8::/32 port=25
# Deny forwarded/routed traffic from subnet 1.2.3.0/24 to subnet 4.5.6.0/24.# Can be used to further restrict a global FORWARD policy set to allowufw: rule=deny route=yes src=1.2.3.0/24 dest=4.5.6.0/24
Notes
Note: See man ufw for more examples.
This is an Extras Module
For more information on what this means please read Extras Modules
654 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
unarchive - Unpacks an archive after (optionally) copying it from the local machine.
New in version 1.4.
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
The unarchive module unpacks an archive. By default, it will copy the source file from the local system to the targetbefore unpacking - set copy=no to unpack an archive which already exists on the target..
Options
Examples
# Example from Ansible Playbooks- unarchive: src=foo.tgz dest=/var/lib/foo
# Unarchive a file that is already on the remote machine- unarchive: src=/tmp/foo.zip dest=/usr/local/bin copy=no
# Unarchive a file that needs to be downloaded (added in 2.0)- unarchive: src=https://example.com/example.zip dest=/usr/local/bin copy=no
Notes
Note: requires tar/unzip command on target host
Note: can handle gzip, bzip2 and xz compressed as well as uncompressed tar files
Note: detects type of archive automatically
1.6. Module Index 655
Ansible 1.2 Documentation, Release 0.01
Note: uses tar’s --diff arg to calculate if changed or not. If this arg is not supported, it will always unpack thearchive
Note: does not detect if a .zip file is different from destination - always unzips
Note: existing files/directories in the destination which are not in the archive are not touched. This is the samebehavior as a normal archive extraction
Note: existing files/directories in the destination which are not in the archive are ignored for purposes of deciding ifthe archive should be unpacked or not
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
uptimerobot - Pause and start Uptime Robot monitoring
New in version 1.9.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
This module will let you start and pause Uptime Robot Monitoring
Requirements
• Valid Uptime Robot API Key
656 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# Pause the monitor with an ID of 12345.- uptimerobot: monitorid=12345
apikey=12345-1234512345state=paused
# Start the monitor with an ID of 12345.- uptimerobot: monitorid=12345
apikey=12345-1234512345state=started
Notes
Note: Support for adding and removing monitors and alert contacts has not yet been implemented.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
uri - Interacts with webservices
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Interacts with HTTP and HTTPS web services and supports Digest, Basic and WSSE HTTP authentication mecha-nisms.
Options
1.6. Module Index 657
Ansible 1.2 Documentation, Release 0.01
Examples
# Check that you can connect (GET) to a page and it returns a status 200- uri: url=http://www.example.com
# Check that a page returns a status 200 and fail if the word AWESOME is not# in the page contents.- action: uri url=http://www.example.com return_content=yesregister: webpage
- action: failwhen: "'AWESOME' not in webpage.content"
# Create a JIRA issue- uri:
url: https://your.jira.example.com/rest/api/2/issue/method: POSTuser: your_usernamepassword: your_passbody: "{{ lookup('file','issue.json') }}"force_basic_auth: yesstatus_code: 201body_format: json
# Login to a form based webpage, then use the returned cookie to# access the app in later tasks
- uri:url: https://your.form.based.auth.example.com/index.phpmethod: POSTbody: "name=your_username&password=your_password&enter=Sign%20in"status_code: 302HEADER_Content-Type: "application/x-www-form-urlencoded"
register: login
- uri:url: https://your.form.based.auth.example.com/dashboard.phpmethod: GETreturn_content: yesHEADER_Cookie: "{{login.set_cookie}}"
# Queue build of a project in Jenkins:- uri:
url: "http://{{ jenkins.host }}/job/{{ jenkins.job }}/build?token={{→˓jenkins.token }}"
method: GETuser: "{{ jenkins.user }}"password: "{{ jenkins.password }}"force_basic_auth: yesstatus_code: 201
Notes
658 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: The dependency on httplib2 was removed in Ansible 2.1
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
urpmi - Urpmi manager
New in version 1.3.4.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manages packages with urpmi (such as for Mageia or Mandriva)
Options
Examples
# install package foo- urpmi: pkg=foo state=present# remove package foo- urpmi: pkg=foo state=absent# description: remove packages foo and bar- urpmi: pkg=foo,bar state=absent# description: update the package database (urpmi.update -a -q) and install→˓bar (bar will be the updated if a newer version exists)- urpmi: name=bar, state=present, update_cache=yes
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 659
Ansible 1.2 Documentation, Release 0.01
user - Manage user accounts
• Synopsis
• Requirements
• Options
• Examples
• This is a Core Module
Synopsis
Manage user accounts and user attributes.
Requirements
• useradd
• userdel
• usermod
Options
Examples
# Add the user 'johnd' with a specific uid and a primary group of 'admin'- user: name=johnd comment="John Doe" uid=1040 group=admin
# Add the user 'james' with a bash shell, appending the group 'admins' and→˓'developers' to the user's groups- user: name=james shell=/bin/bash groups=admins,developers append=yes
# Remove the user 'johnd'- user: name=johnd state=absent remove=yes
# Create a 2048-bit SSH key for user jsmith in ~jsmith/.ssh/id_rsa- user: name=jsmith generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/→˓id_rsa
# added a consultant whose account you want to expire- user: name=james18 shell=/bin/zsh groups=developers expires=1422403387
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
660 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
vca_fw - add remove firewall rules in a gateway in a vca
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Adds or removes firewall rules from a gateway in a vca environment
Options
Examples
#Add a set of firewall rules
- hosts: localhostconnection: localtasks:- vca_fw:
instance_id: 'b15ff1e5-1024-4f55-889f-ea0209726282'vdc_name: 'benz_ansible'state: 'absent'fw_rules:- description: "ben testing"source_ip: "Any"dest_ip: 192.168.2.11
- description: "ben testing 2"source_ip: 192.168.2.100source_port: "Any"dest_port: "22"dest_ip: 192.168.2.13is_enable: "true"enable_logging: "false"protocol: "Tcp"policy: "allow"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 661
Ansible 1.2 Documentation, Release 0.01
vca_nat - add remove nat rules in a gateway in a vca
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Adds or removes nat rules from a gateway in a vca environment
Options
Examples
#An example for a source nat
- hosts: localhostconnection: localtasks:- vca_nat:
instance_id: 'b15ff1e5-1024-4f55-889f-ea0209726282'vdc_name: 'benz_ansible'state: 'present'nat_rules:- rule_type: SNAToriginal_ip: 192.168.2.10translated_ip: 107.189.95.208
#example for a DNAT- hosts: localhostconnection: localtasks:- vca_nat:
instance_id: 'b15ff1e5-1024-4f55-889f-ea0209726282'vdc_name: 'benz_ansible'state: 'present'nat_rules:- rule_type: DNAToriginal_ip: 107.189.95.208original_port: 22translated_ip: 192.168.2.10translated_port: 22
This is an Extras Module
For more information on what this means please read Extras Modules
662 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vca_vapp - Manages vCloud Air vApp instances.
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
This module will actively managed vCloud Air vApp instances. Instances can be created and deleted as well as bothdeployed and undeployed.
Options
Examples
- name: Creates a new vApp in a VCA instancevca_vapp:
vapp_name: towerstate=presenttemplate_name='Ubuntu Server 12.04 LTS (amd64 20150127)'vdc_name=VDC1instance_id=<your instance id here>username=<your username here>password=<your password here>
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vertica_configuration - Updates Vertica configuration parameters.
New in version 2.0.
• Synopsis
• Requirements
1.6. Module Index 663
Ansible 1.2 Documentation, Release 0.01
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Updates Vertica configuration parameters.
Requirements
• unixODBC
• pyodbc
Options
Examples
- name: updating load_balance_policyvertica_configuration: name=failovertostandbyafter value='8 hours'
Notes
Note: The default authentication assumes that you are either logging in as or sudo’ing to the dbadmin account onthe host.
Note: This module uses pyodbc, a Python ODBC database adapter. You must ensure that unixODBC and pyodbcis installed on the host and properly configured.
Note: Configuring unixODBC for Vertica requires Driver = /opt/vertica/lib64/libverticaodbc.so to be added to the Vertica section of either /etc/odbcinst.ini or $HOME/.odbcinst.ini andboth ErrorMessagesPath = /opt/vertica/lib64 and DriverManagerEncoding = UTF-16 to beadded to the Driver section of either /etc/vertica.ini or $HOME/.vertica.ini.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
664 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
vertica_facts - Gathers Vertica database facts.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Gathers Vertica database facts.
Requirements
• unixODBC
• pyodbc
Options
Examples
- name: gathering vertica factsvertica_facts: db=db_name
Notes
Note: The default authentication assumes that you are either logging in as or sudo’ing to the dbadmin account onthe host.
Note: This module uses pyodbc, a Python ODBC database adapter. You must ensure that unixODBC and pyodbcis installed on the host and properly configured.
Note: Configuring unixODBC for Vertica requires Driver = /opt/vertica/lib64/libverticaodbc.so to be added to the Vertica section of either /etc/odbcinst.ini or $HOME/.odbcinst.ini andboth ErrorMessagesPath = /opt/vertica/lib64 and DriverManagerEncoding = UTF-16 to beadded to the Driver section of either /etc/vertica.ini or $HOME/.vertica.ini.
1.6. Module Index 665
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vertica_role - Adds or removes Vertica database roles and assigns roles to them.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Adds or removes Vertica database role and, optionally, assign other roles.
Requirements
• unixODBC
• pyodbc
Options
Examples
- name: creating a new vertica rolevertica_role: name=role_name db=db_name state=present
- name: creating a new vertica role with other role assignedvertica_role: name=role_name assigned_role=other_role_name state=present
Notes
Note: The default authentication assumes that you are either logging in as or sudo’ing to the dbadmin account onthe host.
666 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: This module uses pyodbc, a Python ODBC database adapter. You must ensure that unixODBC and pyodbcis installed on the host and properly configured.
Note: Configuring unixODBC for Vertica requires Driver = /opt/vertica/lib64/libverticaodbc.so to be added to the Vertica section of either /etc/odbcinst.ini or $HOME/.odbcinst.ini andboth ErrorMessagesPath = /opt/vertica/lib64 and DriverManagerEncoding = UTF-16 to beadded to the Driver section of either /etc/vertica.ini or $HOME/.vertica.ini.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vertica_schema - Adds or removes Vertica database schema and roles.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Adds or removes Vertica database schema and, optionally, roles with schema access privileges. A schema will not beremoved until all the objects have been dropped. In such a situation, if the module tries to remove the schema it willfail and only remove roles created for the schema if they have no dependencies.
Requirements
• unixODBC
• pyodbc
Options
1.6. Module Index 667
Ansible 1.2 Documentation, Release 0.01
Examples
- name: creating a new vertica schemavertica_schema: name=schema_name db=db_name state=present
- name: creating a new schema with specific schema ownervertica_schema: name=schema_name owner=dbowner db=db_name state=present
- name: creating a new schema with rolesvertica_schema:
name=schema_namecreate_roles=schema_name_allusage_roles=schema_name_ro,schema_name_rwdb=db_namestate=present
Notes
Note: The default authentication assumes that you are either logging in as or sudo’ing to the dbadmin account onthe host.
Note: This module uses pyodbc, a Python ODBC database adapter. You must ensure that unixODBC and pyodbcis installed on the host and properly configured.
Note: Configuring unixODBC for Vertica requires Driver = /opt/vertica/lib64/libverticaodbc.so to be added to the Vertica section of either /etc/odbcinst.ini or $HOME/.odbcinst.ini andboth ErrorMessagesPath = /opt/vertica/lib64 and DriverManagerEncoding = UTF-16 to beadded to the Driver section of either /etc/vertica.ini or $HOME/.vertica.ini.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vertica_user - Adds or removes Vertica database users and assigns roles.
New in version 2.0.
• Synopsis
• Requirements
• Options
668 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Examples
• Notes
• This is an Extras Module
Synopsis
Adds or removes Vertica database user and, optionally, assigns roles. A user will not be removed until all the depen-dencies have been dropped. In such a situation, if the module tries to remove the user it will fail and only remove rolesgranted to the user.
Requirements
• unixODBC
• pyodbc
Options
Examples
- name: creating a new vertica user with passwordvertica_user: name=user_name password=md5<encrypted_password> db=db_name
→˓state=present
- name: creating a new vertica user authenticated via ldap with roles→˓assignedvertica_user:
name=user_nameldap=truedb=db_nameroles=schema_name_rostate=present
Notes
Note: The default authentication assumes that you are either logging in as or sudo’ing to the dbadmin account onthe host.
Note: This module uses pyodbc, a Python ODBC database adapter. You must ensure that unixODBC and pyodbcis installed on the host and properly configured.
Note: Configuring unixODBC for Vertica requires Driver = /opt/vertica/lib64/libverticaodbc.so to be added to the Vertica section of either /etc/odbcinst.ini or $HOME/.odbcinst.ini and
1.6. Module Index 669
Ansible 1.2 Documentation, Release 0.01
both ErrorMessagesPath = /opt/vertica/lib64 and DriverManagerEncoding = UTF-16 to beadded to the Driver section of either /etc/vertica.ini or $HOME/.vertica.ini.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
virt - Manages virtual machines supported by libvirt
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Manages virtual machines supported by libvirt.
Requirements
• python >= 2.6
• libvirt-python
Options
Examples
# a playbook task line:- virt: name=alpha state=running
# /usr/bin/ansible invocationsansible host -m virt -a "name=alpha command=status"ansible host -m virt -a "name=alpha command=get_xml"ansible host -m virt -a "name=alpha command=create uri=lxc:///"
# a playbook example of defining and launching an LXC guesttasks:- name: define vm
virt: name=foocommand=define
670 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
xml="{{ lookup('template', 'container-template.xml.j2') }}"uri=lxc:///
- name: start vmvirt: name=foo state=running uri=lxc:///
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
virt_net - Manage libvirt network configuration
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Manage libvirt networks.
Requirements
• python >= 2.6
• python-libvirt
• python-lxml
Options
Examples
# Define a new network- virt_net: command=define name=br_nat xml='{{ lookup("template", "network/→˓bridge.xml.j2") }}'
# Start a network- virt_net: command=create name=br_nat
# List available networks
1.6. Module Index 671
Ansible 1.2 Documentation, Release 0.01
- virt_net: command=list_nets
# Get XML data of a specified network- virt_net: command=get_xml name=br_nat
# Stop a network- virt_net: command=destroy name=br_nat
# Undefine a network- virt_net: command=undefine name=br_nat
# Gather facts about networks# Facts will be available as 'ansible_libvirt_networks'- virt_net: command=facts
# Gather information about network managed by 'libvirt' remotely using uri- virt_net: command=info uri='{{ item }}'with_items: libvirt_urisregister: networks
# Ensure that a network is active (needs to be defined and built first)- virt_net: state=active name=br_nat
# Ensure that a network is inactive- virt_net: state=inactive name=br_nat
# Ensure that a given network will be started at boot- virt_net: autostart=yes name=br_nat
# Disable autostart for a given network- virt_net: autostart=no name=br_nat
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
virt_pool - Manage libvirt storage pools
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
672 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Synopsis
Manage libvirt storage pools.
Requirements
• python >= 2.6
• python-libvirt
• python-lxml
Options
Examples
# Define a new storage pool- virt_pool: command=define name=vms xml='{{ lookup("template", "pool/dir.→˓xml.j2") }}'
# Build a storage pool if it does not exist- virt_pool: command=build name=vms
# Start a storage pool- virt_pool: command=create name=vms
# List available pools- virt_pool: command=list_pools
# Get XML data of a specified pool- virt_pool: command=get_xml name=vms
# Stop a storage pool- virt_pool: command=destroy name=vms
# Delete a storage pool (destroys contents)- virt_pool: command=delete name=vms
# Undefine a storage pool- virt_pool: command=undefine name=vms
# Gather facts about storage pools# Facts will be available as 'ansible_libvirt_pools'- virt_pool: command=facts
# Gather information about pools managed by 'libvirt' remotely using uri- virt_pool: command=info uri='{{ item }}'with_items: libvirt_urisregister: storage_pools
# Ensure that a pool is active (needs to be defined and built first)- virt_pool: state=active name=vms
# Ensure that a pool is inactive- virt_pool: state=inactive name=vms
1.6. Module Index 673
Ansible 1.2 Documentation, Release 0.01
# Ensure that a given pool will be started at boot- virt_pool: autostart=yes name=vms
# Disable autostart for a given pool- virt_pool: autostart=no name=vms
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vmware_cluster - Create VMware vSphere Cluster
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Create VMware vSphere Cluster
Requirements
• Tested on ESXi 5.5
• PyVmomi installed
Options
Examples
# Example vmware_cluster command from Ansible Playbooks- name: Create Cluster
local_action: >vmware_clusterhostname="{{ ansible_ssh_host }}" username=root password=vmwaredatacenter_name="datacenter"cluster_name="cluster"enable_ha=True
674 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
enable_drs=Trueenable_vsan=True
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vmware_datacenter - Manage VMware vSphere Datacenters
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manage VMware vSphere Datacenters
Requirements
• python >= 2.6
• PyVmomi
Options
Examples
# Example vmware_datacenter command from Ansible Playbooks- name: Create Datacenter
local_action: >vmware_datacenterhostname="{{ ansible_ssh_host }}" username=root password=vmwaredatacenter_name="datacenter"
1.6. Module Index 675
Ansible 1.2 Documentation, Release 0.01
Notes
Note: Tested on vSphere 5.5
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vmware_dns_config - Manage VMware ESXi DNS Configuration
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Manage VMware ESXi DNS Configuration
Requirements
• python >= 2.6
• PyVmomi
Options
Examples
# Example vmware_dns_config command from Ansible Playbooks- name: Configure ESXi hostname and DNS serverslocal_action:
module: vmware_dns_confighostname: esxi_hostnameusername: rootpassword: your_password
676 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
change_hostname_to: esx01domainname: foo.orgdns_servers:
- 8.8.8.8- 8.8.4.4
Notes
Note: Tested on vSphere 5.5
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vmware_dvs_host - Add or remove a host from distributed virtual switch
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Add or remove a host from distributed virtual switch
Requirements
• python >= 2.6
• PyVmomi
Options
1.6. Module Index 677
Ansible 1.2 Documentation, Release 0.01
Examples
# Example vmware_dvs_host command from Ansible Playbooks- name: Add Host to dVSlocal_action:
module: vmware_dvs_hosthostname: vcenter_ip_or_hostnameusername: vcenter_usernamepassword: vcenter_passwordesxi_hostname: esxi_hostname_as_listed_in_vcenterswitch_name: dvSwitchvmnics:
- vmnic0- vmnic1
state: present
Notes
Note: Tested on vSphere 5.5
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vmware_dvs_portgroup - Create or remove a Distributed vSwitch portgroup
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Create or remove a Distributed vSwitch portgroup
678 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Requirements
• python >= 2.6
• PyVmomi
Options
Examples
- name: Create Management portgrouplocal_action:
module: vmware_dvs_portgrouphostname: vcenter_ip_or_hostnameusername: vcenter_usernamepassword: vcenter_passwordportgroup_name: Managementswitch_name: dvSwitchvlan_id: 123num_ports: 120portgroup_type: earlyBindingstate: present
Notes
Note: Tested on vSphere 5.5
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vmware_dvswitch - Create or remove a distributed vSwitch
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
1.6. Module Index 679
Ansible 1.2 Documentation, Release 0.01
Synopsis
Create or remove a distributed vSwitch
Requirements
• python >= 2.6
• PyVmomi
Options
Examples
- name: Create dvswitchlocal_action:
module: vmware_dvswitchhostname: vcenter_ip_or_hostnameusername: vcenter_usernamepassword: vcenter_passworddatacenter_name: datacenterswitch_name: dvSwitchmtu: 9000uplink_quantity: 2discovery_proto: lldpdiscovery_operation: bothstate: present
Notes
Note: Tested on vSphere 5.5
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vmware_host - Add/remove ESXi host to/from vCenter
New in version 2.0.
• Synopsis
• Requirements
680 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
This module can be used to add/remove an ESXi host to/from vCenter
Requirements
• python >= 2.6
• PyVmomi
Options
Examples
Example from Ansible playbook
- name: Add ESXi Host to VCSAlocal_action:module: vmware_hosthostname: vcsa_hostusername: vcsa_userpassword: vcsa_passdatacenter_name: datacenter_namecluster_name: cluster_nameesxi_hostname: esxi_hostnameesxi_username: esxi_usernameesxi_password: esxi_passwordstate: present
Notes
Note: Tested on vSphere 5.5
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 681
Ansible 1.2 Documentation, Release 0.01
vmware_migrate_vmk - Migrate a VMK interface from VSS to VDS
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Migrate a VMK interface from VSS to VDS
Requirements
• python >= 2.6
• PyVmomi
Options
Examples
Example from Ansible playbook
- name: Migrate Management vmklocal_action:module: vmware_migrate_vmkhostname: vcsa_hostusername: vcsa_userpassword: vcsa_passesxi_hostname: esxi_hostnamedevice: vmk1current_switch_name: temp_vswitchcurrent_portgroup_name: esx-mgmtmigrate_switch_name: dvSwitchmigrate_portgroup_name: Management
Notes
Note: Tested on vSphere 5.5
682 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vmware_portgroup - Create a VMware portgroup
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Create a VMware portgroup
Requirements
• python >= 2.6
• PyVmomi
Options
Examples
Example from Ansible playbook
- name: Add Management Network VM Portgrouplocal_action:module: vmware_portgrouphostname: esxi_hostnameusername: esxi_usernamepassword: esxi_passwordswitch_name: vswitch_nameportgroup_name: portgroup_namevlan_id: vlan_id
1.6. Module Index 683
Ansible 1.2 Documentation, Release 0.01
Notes
Note: Tested on vSphere 5.5
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vmware_target_canonical_facts - Return canonical (NAA) from an ESXi host
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Return canonical (NAA) from an ESXi host based on SCSI target ID
Requirements
• Tested on vSphere 5.5
• PyVmomi installed
Options
Examples
# Example vmware_target_canonical_facts command from Ansible Playbooks- name: Get Canonical name
local_action: >vmware_target_canonical_factshostname="{{ ansible_ssh_host }}" username=root password=vmwaretarget_id=7
684 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vmware_vm_facts - Return basic facts pertaining to a vSphere virtual machine guest
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Return basic facts pertaining to a vSphere virtual machine guest
Requirements
• python >= 2.6
• PyVmomi
Options
Examples
- name: Gather all registered virtual machineslocal_action:
module: vmware_vm_factshostname: esxi_or_vcenter_ip_or_hostnameusername: usernamepassword: password
Notes
Note: Tested on vSphere 5.5
1.6. Module Index 685
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vmware_vm_vss_dvs_migrate - Migrates a virtual machine from a standard vswitch to distributed
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Migrates a virtual machine from a standard vswitch to distributed
Requirements
• python >= 2.6
• PyVmomi
Options
Examples
- name: Migrate VCSA to vDSlocal_action:
module: vmware_vm_vss_dvs_migratehostname: vcenter_ip_or_hostnameusername: vcenter_usernamepassword: vcenter_passwordvm_name: virtual_machine_namedvportgroup_name: distributed_portgroup_name
Notes
686 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: Tested on vSphere 5.5
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vmware_vmkernel - Create a VMware VMkernel Interface
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Create a VMware VMkernel Interface
Requirements
• python >= 2.6
• PyVmomi
Options
Examples
# Example command from Ansible Playbook
- name: Add Management vmkernel port (vmk1)local_action:
module: vmware_vmkernelhostname: esxi_hostnameusername: esxi_usernamepassword: esxi_passwordvswitch_name: vswitch_nameportgroup_name: portgroup_name
1.6. Module Index 687
Ansible 1.2 Documentation, Release 0.01
vlan_id: vlan_idip_address: ip_addresssubnet_mask: subnet_maskenable_mgmt: True
Notes
Note: Tested on vSphere 5.5
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vmware_vmkernel_ip_config - Configure the VMkernel IP Address
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Configure the VMkernel IP Address
Requirements
• python >= 2.6
• PyVmomi
Options
688 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
# Example command from Ansible Playbook
- name: Configure IP address on ESX hostlocal_action:
module: vmware_vmkernel_ip_confighostname: esxi_hostnameusername: esxi_usernamepassword: esxi_passwordvmk_name: vmk0ip_address: 10.0.0.10subnet_mask: 255.255.255.0
Notes
Note: Tested on vSphere 5.5
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vmware_vsan_cluster - Configure VSAN clustering on an ESXi host
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
This module can be used to configure VSAN clustering on an ESXi host
Requirements
• python >= 2.6
1.6. Module Index 689
Ansible 1.2 Documentation, Release 0.01
• PyVmomi
Options
Examples
# Example command from Ansible Playbook
- name: Configure VMware VSAN Clusterhosts: deploy_nodegather_facts: Falsetags:
- vsantasks:
- name: Configure VSAN on first hostvmware_vsan_cluster:
hostname: "{{ groups['esxi'][0] }}"username: "{{ esxi_username }}"password: "{{ site_password }}"
register: vsan_cluster
- name: Configure VSAN on remaining hostsvmware_vsan_cluster:
hostname: "{{ item }}"username: "{{ esxi_username }}"password: "{{ site_password }}"cluster_uuid: "{{ vsan_cluster.cluster_uuid }}"
with_items: groups['esxi'][1:]
Notes
Note: Tested on vSphere 5.5
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vmware_vswitch - Add a VMware Standard Switch to an ESXi host
New in version 2.0.
• Synopsis
• Requirements
• Options
690 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Examples
• Notes
• This is an Extras Module
Synopsis
Add a VMware Standard Switch to an ESXi host
Requirements
• python >= 2.6
• PyVmomi
Options
Examples
Example from Ansible playbook
- name: Add a VMware vSwitchlocal_action:module: vmware_vswitchhostname: esxi_hostnameusername: esxi_usernamepassword: esxi_passwordswitch_name: vswitch_namenic_name: vmnic_namemtu: 9000
Notes
Note: Tested on vSphere 5.5
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vsphere_copy - Copy a file to a vCenter datastore
New in version 2.0.
1.6. Module Index 691
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Upload files to a vCenter datastore
Options
Examples
- vsphere_copy: host=vhost login=vuser password=vpass src=/some/local/file→˓datacenter='DC1 Someplace' datastore=datastore1 path=some/remote/filetransport: local
- vsphere_copy: host=vhost login=vuser password=vpass src=/other/local/file→˓datacenter='DC2 Someplace' datastore=datastore2 path=other/remote/filedelegate_to: other_system
Notes
Note: This module ought to be run from a system that can access vCenter directly and has the file to transfer. It canbe the normal remote target or you can change it either by using transport: local or using delegate_to.
Note: Tested on vSphere 5.5
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
vsphere_guest - Create/delete/manage a guest VM through VMware vSphere.
New in version 1.6.
692 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Create/delete/reconfigure a guest VM through VMware vSphere. This module has a dependency on pysphere >= 1.7
Requirements
• python >= 2.6
• pysphere
Options
Examples
# Create a new VM on an ESX server# Returns changed = False when the VM already exists# Returns changed = True and a adds ansible_facts from the new VM# State will set the power status of a guest upon creation. Use powered_on→˓to create and boot.# Options ['state', 'vm_extra_config', 'vm_disk', 'vm_nic', 'vm_hardware',→˓'esxi'] are required together# Note: vm_floppy support added in 2.0
- vsphere_guest:vcenter_hostname: vcenter.mydomain.localusername: myuserpassword: mypassguest: newvm001state: powered_onvm_extra_config:vcpu.hotadd: yesmem.hotadd: yesnotes: This is a test VM
vm_disk:disk1:size_gb: 10type: thindatastore: storage001
vm_nic:nic1:type: vmxnet3network: VM Network
1.6. Module Index 693
Ansible 1.2 Documentation, Release 0.01
network_type: standardnic2:type: vmxnet3network: dvSwitch Networknetwork_type: dvs
vm_hardware:memory_mb: 2048num_cpus: 2osid: centos64Guestscsi: paravirtualvm_cdrom:type: "iso"iso_path: "DatastoreName/cd-image.iso"
vm_floppy:type: "image"image_path: "DatastoreName/floppy-image.flp"
esxi:datacenter: MyDatacenterhostname: esx001.mydomain.local
# Reconfigure the CPU and Memory on the newly created VM# Will return the changes made
- vsphere_guest:vcenter_hostname: vcenter.mydomain.localusername: myuserpassword: mypassguest: newvm001state: reconfiguredvm_extra_config:
vcpu.hotadd: yesmem.hotadd: yesnotes: This is a test VM
vm_disk:disk1:size_gb: 10type: thindatastore: storage001
vm_nic:nic1:type: vmxnet3network: VM Networknetwork_type: standard
vm_hardware:memory_mb: 4096num_cpus: 4osid: centos64Guestscsi: paravirtual
esxi:datacenter: MyDatacenterhostname: esx001.mydomain.local
# Deploy a guest from a template- vsphere_guest:
vcenter_hostname: vcenter.mydomain.localusername: myuserpassword: mypassguest: newvm001
694 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
from_template: yestemplate_src: centosTemplatecluster: MainClusterresource_pool: "/Resources"
# Task to gather facts from a vSphere cluster only if the system is a VMWare→˓guest
- vsphere_guest:vcenter_hostname: vcenter.mydomain.localusername: myuserpassword: mypassguest: newvm001vmware_guest_facts: yes
# Typical output of a vsphere_facts run on a guest# If vmware tools is not installed, ipadresses with return None
- hw_eth0:- addresstype: "assigned"
label: "Network adapter 1"macaddress: "00:22:33:33:44:55"macaddress_dash: "00-22-33-33-44-55"ipaddresses: ['192.0.2.100', '2001:DB8:56ff:feac:4d8a']summary: "VM Network"
hw_guest_full_name: "newvm001"hw_guest_id: "rhel6_64Guest"hw_memtotal_mb: 2048hw_name: "centos64Guest"hw_processor_count: 2hw_product_uuid: "ef50bac8-2845-40ff-81d9-675315501dac"
# Remove a vm from vSphere# The VM must be powered_off or you need to use force to force a shutdown
- vsphere_guest:vcenter_hostname: vcenter.mydomain.localusername: myuserpassword: mypassguest: newvm001state: absentforce: yes
Notes
Note: This module should run from a system that can access vSphere directly. Either by using local_action, or usingdelegate_to.
This is a Core Module
For more information on what this means please read Core Modules
1.6. Module Index 695
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
wait_for - Waits for a condition before continuing.
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
You can wait for a set amount of time timeout, this is the default if nothing is specified. Waiting for a port to becomeavailable is useful for when services are not immediately available after their init scripts return which is true of certainJava application servers. It is also useful when starting guests with the virt module and needing to pause until theyare ready. This module can also be used to wait for a regex match a string to be present in a file. In 1.6 and later, thismodule can also be used to wait for a file to be available or absent on the filesystem. In 1.8 and later, this module canalso be used to wait for active connections to be closed before continuing, useful if a node is being rotated out of aload balancer pool.
Options
Examples
# wait 300 seconds for port 8000 to become open on the host, don't start→˓checking for 10 seconds- wait_for: port=8000 delay=10
# wait 300 seconds for port 8000 of any IP to close active connections, don→˓'t start checking for 10 seconds- wait_for: host=0.0.0.0 port=8000 delay=10 state=drained
# wait 300 seconds for port 8000 of any IP to close active connections,→˓ignoring connections for specified hosts- wait_for: host=0.0.0.0 port=8000 state=drained exclude_hosts=10.2.1.2,10.2.→˓1.3
# wait until the file /tmp/foo is present before continuing- wait_for: path=/tmp/foo
# wait until the string "completed" is in the file /tmp/foo before continuing- wait_for: path=/tmp/foo search_regex=completed
# wait until the lock file is removed- wait_for: path=/var/lock/file.lock state=absent
# wait until the process is finished and pid was destroyed
696 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- wait_for: path=/proc/3466/status state=absent
# wait 300 seconds for port 22 to become open and contain "OpenSSH", don't→˓assume the inventory_hostname is resolvable# and don't start checking for 10 seconds- local_action: wait_for port=22 host="{{ ansible_ssh_host |→˓default(inventory_hostname) }}" search_regex=OpenSSH delay=10
Notes
Note: The ability to use search_regex with a port connection was added in 1.7.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
webfaction_app - Add or remove applications on a Webfaction host
New in version 2.0.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Add or remove applications on a Webfaction host. Further documentation at http://github.com/quentinsf/ansible-webfaction.
Options
Examples
- name: Create a test appwebfaction_app:
name="my_wsgi_app1"state=presenttype=mod_wsgi35-python27
1.6. Module Index 697
Ansible 1.2 Documentation, Release 0.01
login_name={{webfaction_user}}login_password={{webfaction_passwd}}machine={{webfaction_machine}}
Notes
Note: You can run playbooks that use this on a local machine, or on a Webfaction host, or elsewhere, since thescripts use the remote webfaction API - the location is not important. However, running them on multiple hostssimultaneously is best avoided. If you don’t specify localhost as your host, you may want to add serial: 1 to theplays.
Note: See the webfaction API for more info.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
webfaction_db - Add or remove a database on Webfaction
New in version 2.0.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Add or remove a database on a Webfaction host. Further documentation at http://github.com/quentinsf/ansible-webfaction.
Options
Examples
698 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# This will also create a default DB user with the same# name as the database, and the specified password.
- name: Create a databasewebfaction_db:
name: "{{webfaction_user}}_db1"password: mytestsqltype: mysqllogin_name: "{{webfaction_user}}"login_password: "{{webfaction_passwd}}"machine: "{{webfaction_machine}}"
# Note that, for symmetry's sake, deleting a database using# 'state: absent' will also delete the matching user.
Notes
Note: You can run playbooks that use this on a local machine, or on a Webfaction host, or elsewhere, since thescripts use the remote webfaction API - the location is not important. However, running them on multiple hostssimultaneously is best avoided. If you don’t specify localhost as your host, you may want to add serial: 1 to theplays.
Note: See the webfaction API for more info.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
webfaction_domain - Add or remove domains and subdomains on Webfaction
New in version 2.0.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
1.6. Module Index 699
Ansible 1.2 Documentation, Release 0.01
Synopsis
Add or remove domains or subdomains on a Webfaction host. Further documentation at http://github.com/quentinsf/ansible-webfaction.
Options
Examples
- name: Create a test domainwebfaction_domain:
name: mydomain.comstate: presentsubdomains:- www- blog
login_name: "{{webfaction_user}}"login_password: "{{webfaction_passwd}}"
- name: Delete test domain and any subdomainswebfaction_domain:
name: mydomain.comstate: absentlogin_name: "{{webfaction_user}}"login_password: "{{webfaction_passwd}}"
Notes
Note: If you are deleting domains by using state=absent, then note that if you specify subdomains, just thoseparticular subdomains will be deleted. If you don’t specify subdomains, the domain will be deleted.
Note: You can run playbooks that use this on a local machine, or on a Webfaction host, or elsewhere, since thescripts use the remote webfaction API - the location is not important. However, running them on multiple hostssimultaneously is best avoided. If you don’t specify localhost as your host, you may want to add serial: 1 to theplays.
Note: See the webfaction API for more info.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
700 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
webfaction_mailbox - Add or remove mailboxes on Webfaction
New in version 2.0.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Add or remove mailboxes on a Webfaction account. Further documentation at http://github.com/quentinsf/ansible-webfaction.
Options
Examples
- name: Create a mailboxwebfaction_mailbox:
mailbox_name="mybox"mailbox_password="myboxpw"state=presentlogin_name={{webfaction_user}}login_password={{webfaction_passwd}}
Notes
Note: You can run playbooks that use this on a local machine, or on a Webfaction host, or elsewhere, since thescripts use the remote webfaction API - the location is not important. However, running them on multiple hostssimultaneously is best avoided. If you don’t specify localhost as your host, you may want to add serial: 1 to theplays.
Note: See the webfaction API for more info.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 701
Ansible 1.2 Documentation, Release 0.01
webfaction_site - Add or remove a website on a Webfaction host
New in version 2.0.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Add or remove a website on a Webfaction host. Further documentation at http://github.com/quentinsf/ansible-webfaction.
Options
Examples
- name: create websitewebfaction_site:
name: testsite1state: presenthost: myhost.webfaction.comsubdomains:
- 'testsite1.my_domain.org'site_apps:
- ['testapp1', '/']https: nologin_name: "{{webfaction_user}}"login_password: "{{webfaction_passwd}}"
Notes
Note: Sadly, you do need to know your webfaction hostname for the host parameter. But at least, unlike the API,you don’t need to know the IP address - you can use a DNS name.
Note: If a site of the same name exists in the account but on a different host, the operation will exit.
Note: You can run playbooks that use this on a local machine, or on a Webfaction host, or elsewhere, since thescripts use the remote webfaction API - the location is not important. However, running them on multiple hosts
702 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
simultaneously is best avoided. If you don’t specify localhost as your host, you may want to add serial: 1 to theplays.
Note: See the webfaction API for more info.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_acl - Set file/directory permissions for a system user or group.
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Add or remove rights/permissions for a given user or group for the specified src file or folder.
Options
Examples
# Restrict write,execute access to User Fed-Phil$ ansible -i hosts -m win_acl -a "user=Fed-Phil path=C:\Important\Executable.→˓exe type=deny rights='ExecuteFile,Write'" all
# Playbook example# Add access rule to allow IIS_IUSRS FullControl to MySite---- name: Add IIS_IUSRS allow rightswin_acl:
path: 'C:\inetpub\wwwroot\MySite'user: 'IIS_IUSRS'rights: 'FullControl'type: 'allow'state: 'present'inherit: 'ContainerInherit, ObjectInherit'propagation: 'None'
1.6. Module Index 703
Ansible 1.2 Documentation, Release 0.01
# Remove previously added rule for IIS_IUSRS- name: Remove FullControl AccessRule for IIS_IUSRS
path: 'C:\inetpub\wwwroot\MySite'user: 'IIS_IUSRS'rights: 'FullControl'type: 'allow'state: 'absent'inherit: 'ContainerInherit, ObjectInherit'propagation: 'None'
# Deny Intern- name: Deny Deny
path: 'C:\Administrator\Documents'user: 'Intern'rights: 'Read,Write,Modify,FullControl,Delete'type: 'deny'state: 'present'
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_chocolatey - Installs packages using chocolatey
New in version 1.9.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Installs packages using Chocolatey (http://chocolatey.org/). If Chocolatey is missing from the system, the module willinstall it. List of packages can be found at http://chocolatey.org/packages
Options
Examples
# Install gitwin_chocolatey:name: git
704 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# Install notepadplusplus version 6.6win_chocolatey:name: notepadplusplus.installversion: 6.6
# Uninstall gitwin_chocolatey:name: gitstate: absent
# Install git from specified repositorywin_chocolatey:name: gitsource: https://someserver/api/v2/
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_copy - Copies files to remote locations on windows hosts.
New in version 1.9.2.
• Synopsis
• Options
• Examples
• Return Values
• Notes
• This is a Core Module
Synopsis
The win_copy module copies a file on the local box to remote windows locations.
Options
Examples
# Copy a single file- win_copy: src=/srv/myfiles/foo.conf dest=c:\TEMP\foo.conf
# Copy the contents of files/temp_files dir into c: emp\. Includes any sub→˓dirs under files/temp_files
1.6. Module Index 705
Ansible 1.2 Documentation, Release 0.01
# Note the use of unix style path in the dest.# This is necessary because \ is yaml escape sequence- win_copy: src=files/temp_files/ dest=c:/temp/
# Copy the files/temp_files dir and any files or sub dirs into c: emp# Copies the folder because there is no trailing / on 'files/temp_files'- win_copy: src=files/temp_files dest=c:/temp/
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: The “win_copy” module is best used for small files only. This module should not be used for files bigger than3Mb as this will result in a 500 response from the winrm host and it will not be possible to connect via winrm againuntil the windows remote management service has been restarted on the windows host. Files larger than 1Mb will takeminutes to transfer. The recommended way to transfer large files is using win_get_url or collecting from a windowsfile share folder.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_dotnet_ngen - Runs ngen to recompile DLLs after .NET updates
New in version 2.0.
• Synopsis
• Examples
• Notes
• This is an Extras Module
Synopsis
After .NET framework is installed/updated, Windows will probably want to recompile things to optimise for the host.This happens via scheduled task, usually at some inopportune time. This module allows you to run this task on yourown schedule, so you incur the CPU hit at some more convenient and controlled time. http://blogs.msdn.com/b/dotnet/archive/2013/08/06/wondering-why-mscorsvw-exe-has-high-cpu-usage-you-can-speed-it-up.aspx
706 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
# Run ngen taskswin_dotnet_ngen:
Notes
Note: there are in fact two scheduled tasks for ngen but they have no triggers so aren’t a problem
Note: there’s no way to test if they’ve been completed (?)
Note: the stdout is quite likely to be several megabytes
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_environment - Modifies environment variables on windows hosts.
New in version 2.0.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Uses .net Environment to set or remove environment variables and can set at User, Machine or Process level. Userlevel environment variables will be set, but not available until the user has logged off and on again.
Options
1.6. Module Index 707
Ansible 1.2 Documentation, Release 0.01
Examples
# Set an environment variable for all userswin_environment:state: presentname: TestVariablevalue: "Test value"level: machine
# Remove an environment variable for the current userswin_environment:state: absentname: TestVariablelevel: user
Notes
Note: This module does not broadcast change events. This means that the minority of windows applications whichcan have their environment changed without restarting will not be notified and therefore will need restarting to pick upnew environment settings. User level environment variables will require the user to log out and in again before theybecome available.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_feature - Installs and uninstalls Windows Features
New in version 1.7.
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
Installs or uninstalls Windows Roles or Features
Options
708 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
# This installs IIS.# The names of features available for install can be run by running the→˓following Powershell Command:# PS C:\Users\Administrator> Import-Module ServerManager; Get-WindowsFeature$ ansible -i hosts -m win_feature -a "name=Web-Server" all$ ansible -i hosts -m win_feature -a "name=Web-Server,Web-Common-Http" all
# Playbook example---- name: Install IIShosts: allgather_facts: falsetasks:
- name: Install IISwin_feature:name: "Web-Server"state: presentrestart: yesinclude_sub_features: yesinclude_management_tools: yes
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_file - Creates, touches or removes files or directories.
New in version 1.9.2.
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Creates (empty) files, updates file modification stamps of existing files, and can create or remove directories. Unlikefile, does not modify ownership, permissions or manipulate links.
Options
1.6. Module Index 709
Ansible 1.2 Documentation, Release 0.01
Examples
# create a file- win_file: path=C:\temp\foo.conf
# touch a file (creates if not present, updates modification time if present)- win_file: path=C:\temp\foo.conf state=touch
# remove a file, if present- win_file: path=C:\temp\foo.conf state=absent
# create directory structure- win_file: path=C:\temp\folder\subfolder state=directory
# remove directory structure- win_file: path=C:\temp state=absent
Notes
Note: See also win_copy, win_template, copy, template, assemble
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_firewall_rule - Windows firewall automation
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
allows you to create/remove/update firewall rules
Options
710 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Examples
- name: Firewall rule to allow smtp on TCP port 25action: win_firewall_ruleargs:
name: smtpenabled: yesstate: presentlocalport: 25action: allowprotocol: TCP
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_get_url - Fetches a file from a given URL
New in version 1.7.
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
Fetches a file from a URL and saves to locally
Options
Examples
# Downloading a JPEG and saving it to a file with the ansible command.# Note the "dest" is quoted rather instead of escaping the backslashes$ ansible -i hosts -c winrm -m win_get_url -a "url=http://www.example.com/→˓earthrise.jpg dest='C:\Users\Administrator\earthrise.jpg'" all
# Playbook example- name: Download earthrise.jpg to 'C:\Users\RandomUser\earthrise.jpg'win_get_url:
url: 'http://www.example.com/earthrise.jpg'dest: 'C:\Users\RandomUser\earthrise.jpg'
1.6. Module Index 711
Ansible 1.2 Documentation, Release 0.01
- name: Download earthrise.jpg to 'C:\Users\RandomUser\earthrise.jpg' only→˓if modifiedwin_get_url:
url: 'http://www.example.com/earthrise.jpg'dest: 'C:\Users\RandomUser\earthrise.jpg'force: no
- name: Download earthrise.jpg to 'C:\Users\RandomUser\earthrise.jpg'→˓through a proxy server.win_get_url:
url: 'http://www.example.com/earthrise.jpg'dest: 'C:\Users\RandomUser\earthrise.jpg'proxy_url: 'http://10.0.0.1:8080'proxy_username: 'username'proxy_password: 'password'
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_group - Add and remove local groups
New in version 1.7.
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
Add and remove local groups
Options
Examples
# Create a new groupwin_group:name: deploydescription: Deploy Groupstate: present
# Remove a group
712 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
win_group:name: deploystate: absent
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_iis_virtualdirectory - Configures a virtual directory in IIS.
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Creates, Removes and configures a virtual directory in IIS.
Options
Examples
# This creates a virtual directory if it doesn't exist.$ ansible -i hosts -m win_iis_virtualdirectory -a "name='somedirectory'→˓site=somesite state=present physical_path=c:\virtualdirectory\some" host
# This removes a virtual directory if it exists.$ ansible -i hosts -m win_iis_virtualdirectory -a "name='somedirectory'→˓site=somesite state=absent" host
# This creates a virtual directory on an application if it doesn't exist.$ ansible -i hosts -m win_iis_virtualdirectory -a "name='somedirectory'→˓site=somesite application=someapp state=present physical_→˓path=c:\virtualdirectory\some" host
This is an Extras Module
For more information on what this means please read Extras Modules
1.6. Module Index 713
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_iis_webapplication - Configures a IIS Web application.
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Creates, Removes and configures a IIS Web applications
Options
Examples
$ ansible -i hosts -m win_iis_webapplication -a "name=api site=acme physical_→˓path=c:\apps\acme\api" host
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_iis_webapppool - Configures a IIS Web Application Pool.
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Creates, Removes and configures a IIS Web Application Pool
714 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Options
Examples
# This return information about an existing application pool$ansible -i inventory -m win_iis_webapppool -a "name='DefaultAppPool'"→˓windowshost | success >> {
"attributes": {},"changed": false,"info": {
"attributes": {"CLRConfigFile": "","applicationPoolSid": "S-1-5-82-3006700770-424185619-1745488364-
→˓794895919-4004696415","autoStart": true,"enable32BitAppOnWin64": false,"enableConfigurationOverride": true,"managedPipelineMode": 0,"managedRuntimeLoader": "webengine4.dll","managedRuntimeVersion": "v4.0","name": "DefaultAppPool","passAnonymousToken": true,"queueLength": 1000,"startMode": 0,"state": 1
},"name": "DefaultAppPool","state": "Started"
}}
# This creates a new application pool in 'Started' state$ ansible -i inventory -m win_iis_webapppool -a "name='AppPool'→˓state=started" windows
# This stoppes an application pool$ ansible -i inventory -m win_iis_webapppool -a "name='AppPool'→˓state=stopped" windows
# This restarts an application pool$ ansible -i inventory -m win_iis_webapppool -a "name='AppPool'→˓state=restart" windows
# This restarts an application pool$ ansible -i inventory -m win_iis_webapppool -a "name='AppPool'→˓state=restart" windows
# This change application pool attributes without touching state$ ansible -i inventory -m win_iis_webapppool -a "name='AppPool' attributes=→˓'managedRuntimeVersion:v4.0|autoStart:false'" windows
# This creates an application pool and sets attributes$ ansible -i inventory -m win_iis_webapppool -a "name='AnotherAppPool'→˓state=started attributes='managedRuntimeVersion:v4.0|autoStart:false'"→˓windows
1.6. Module Index 715
Ansible 1.2 Documentation, Release 0.01
# Playbook example---
- name: App Pool with .NET 4.0win_iis_webapppool:
name: 'AppPool'state: startedattributes: managedRuntimeVersion:v4.0
register: webapppool
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_iis_webbinding - Configures a IIS Web site.
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Creates, Removes and configures a binding to an existing IIS Web site
Options
Examples
# This will return binding information for an existing host$ ansible -i vagrant-inventory -m win_iis_webbinding -a "name='Default Web→˓Site'" windowshost | success >> {
"added": [],"changed": false,"matched": [
{"bindingInformation": "*:80:","certificateHash": "","certificateStoreName": "","isDsMapperEnabled": false,
716 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
"protocol": "http","sslFlags": 0
}],"parameters": {
"Name": "Default Web Site"},"removed": []
}
# This will return the HTTPS binding information for an existing host$ ansible -i vagrant-inventory -m win_iis_webbinding -a "name='Default Web→˓Site' protocol=https" windows
# This will return the HTTPS binding information for an existing host$ ansible -i vagrant-inventory -m win_iis_webbinding -a "name='Default Web→˓Site' port:9090 state=present" windows
# This will add a HTTP binding on port 9090$ ansible -i vagrant-inventory -m win_iis_webbinding -a "name='Default Web→˓Site' port=9090 state=present" windows
# This will remove the HTTP binding on port 9090$ ansible -i vagrant-inventory -m win_iis_webbinding -a "name='Default Web→˓Site' port=9090 state=present" windows
# This will add a HTTPS binding$ ansible -i vagrant-inventory -m win_iis_webbinding -a "name='Default Web→˓Site' protocol=https state=present" windows
# This will add a HTTPS binding and select certificate to use# ansible -i vagrant-inventory -m win_iis_webbinding -a "name='Default Web→˓Site' protocol=https certificate_hash=→˓B0D0FA8408FC67B230338FCA584D03792DA73F4C" windows
# Playbook example---
- name: Website http/https bidingswin_iis_webbinding:
name: "Default Web Site"protocol: httpsport: 443certificate_hash: "D1A3AF8988FD32D1A3AF8988FD323792DA73F4C"state: present
when: monitor_use_https
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
1.6. Module Index 717
Ansible 1.2 Documentation, Release 0.01
win_iis_website - Configures a IIS Web site.
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Creates, Removes and configures a IIS Web site
Options
Examples
# This return information about an existing host$ ansible -i vagrant-inventory -m win_iis_website -a "name='Default Web Site'→˓" windowhost | success >> {
"changed": false,"site": {
"ApplicationPool": "DefaultAppPool","Bindings": [
"*:80:"],"ID": 1,"Name": "Default Web Site","PhysicalPath": "%SystemDrive%\inetpub\wwwroot","State": "Stopped"
}}
# This stops an existing site.$ ansible -i hosts -m win_iis_website -a "name='Default Web Site'→˓state=stopped" host
# This creates a new site.$ ansible -i hosts -m win_iis_website -a "name=acme physical_→˓path=c:\sites\acme" host
# Change logfile .$ ansible -i hosts -m win_iis_website -a "name=acme physical_→˓path=c:\sites\acme" host
# Playbook example---
- name: Acme IIS site
718 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
win_iis_website:name: "Acme"state: startedport: 80ip: 127.0.0.1hostname: acme.localapplication_pool: "acme"physical_path: 'c:\sites\acme'parameters: 'logfile.directory:c:\sites\logs'
register: website
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_lineinfile - Ensure a particular line is in a file, or replace an existing line using a back-referencedregular expression.
New in version 2.0.
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
This module will search a file for a line, and ensure that it is present or absent. This is primarily useful when you wantto change a single line in a file only.
Options
Examples
- win_lineinfile: dest=C:\temp\example.conf regexp=^name= line="name=JohnDoe"
- win_lineinfile: dest=C:\temp\example.conf state=absent regexp="^name="
- win_lineinfile: dest=C:\temp\example.conf regexp='^127\.0\.0\.1' line='127.→˓0.0.1 localhost'
- win_lineinfile: dest=C:\temp\httpd.conf regexp="^Listen " insertafter="^→˓#Listen " line="Listen 8080"
1.6. Module Index 719
Ansible 1.2 Documentation, Release 0.01
- win_lineinfile: dest=C:\temp\services regexp="^# port for http"→˓insertbefore="^www.*80/tcp" line="# port for http by default"
# Create file if it doesnt exist with a specific encoding- win_lineinfile: dest=C:\temp\utf16.txt create="yes" encoding="utf-16" line=→˓"This is a utf-16 encoded file"
# Add a line to a file and ensure the resulting file uses unix line→˓separators- win_lineinfile: dest=C:\temp\testfile.txt line="Line added to file"→˓newline="unix"
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_msi - Installs and uninstalls Windows MSI files
New in version 1.7.
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
Installs or uninstalls a Windows MSI file that is already located on the target server
Options
Examples
# Install an MSI file- win_msi: path=C:\\7z920-x64.msi
# Uninstall an MSI file- win_msi: path=C:\\7z920-x64.msi state=absent
This is a Core Module
For more information on what this means please read Core Modules
720 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_nssm - NSSM - the Non-Sucking Service Manager
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
nssm is a service helper which doesn’t suck. See https://nssm.cc/ for more information.
Requirements
• nssm >= 2.24.0 # (install via win_chocolatey) win_chocolatey: name=nssm
Options
Examples
# Install and start the foo service- win_nssm:
name: fooapplication: C:\windows\foo.exe
# Install and start the foo service with a key-value pair argument# This will yield the following command: C:\windows\foo.exe bar "true"- win_nssm:
name: fooapplication: C:\windows\foo.exeapp_parameters:
bar: true
# Install and start the foo service with a key-value pair argument, where→˓the argument needs to start with a dash# This will yield the following command: C:\windows\foo.exe -bar "true"- win_nssm:
name: fooapplication: C:\windows\foo.exeapp_parameters:
"-bar": true
1.6. Module Index 721
Ansible 1.2 Documentation, Release 0.01
# Install and start the foo service with a single parameter# This will yield the following command: C:\windows\foo.exe bar- win_nssm:
name: fooapplication: C:\windows\foo.exeapp_parameters:
_: bar
# Install and start the foo service with a mix of single params, and key→˓value pairs# This will yield the following command: C:\windows\foo.exe bar -file output.→˓bat- win_nssm:
name: fooapplication: C:\windows\foo.exeapp_parameters:
_: bar"-file": "output.bat"
# Install and start the foo service, redirecting stdout and stderr to the→˓same file- win_nssm:
name: fooapplication: C:\windows\foo.exestdout_file: C:\windows\foo.logstderr_file: C:\windows\foo.log
# Install and start the foo service, but wait for dependencies tcpip and adf- win_nssm:
name: fooapplication: C:\windows\foo.exedependencies: 'adf,tcpip'
# Install and start the foo service with dedicated user- win_nssm:
name: fooapplication: C:\windows\foo.exeuser: foouserpassword: secret
# Install the foo service but do not start it automatically- win_nssm:
name: fooapplication: C:\windows\foo.exestate: presentstart_mode: manual
# Remove the foo service- win_nssm:
name: foostate: absent
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,
722 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Helping Testing PRs and Developing Modules.
win_package - Installs/Uninstalls a installable package, either from local file system or url
New in version 1.7.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Installs or uninstalls a package
Options
Examples
# Playbook example- name: Install the vc thingy
win_package:name="Microsoft Visual C thingy"path="http://download.microsoft.com/download/1/6/B/16B06F60-3B20-4FF2-
→˓B699-5E9B7962F9AE/VSU_4/vcredist_x64.exe"Product_Id="{CF2BEA3C-26EA-32F8-AA9B-331F7E34BA97}"Arguments="/install /passive /norestart"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_ping - A windows version of the classic ping module.
New in version 1.7.
• Synopsis
• Options
• Examples
• This is a Core Module
1.6. Module Index 723
Ansible 1.2 Documentation, Release 0.01
Synopsis
Checks management connectivity of a windows host
Options
Examples
# Test connectivity to a windows hostansible winserver -m win_ping
# Example from an Ansible Playbook- action: win_ping
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_regedit - Add, Edit, or Remove Registry Keys and Values
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Add, Edit, or Remove Registry Keys and Values using ItemProperties Cmdlets
Options
Examples
# Creates Registry Key called MyCompany.win_regedit:key: HKCU:\Software\MyCompany
# Creates Registry Key called MyCompany,# a value within MyCompany Key called "hello", and# data for the value "hello" containing "world".
724 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
win_regedit:key: HKCU:\Software\MyCompanyvalue: hellodata: world
# Creates Registry Key called MyCompany,# a value within MyCompany Key called "hello", and# data for the value "hello" containing "1337" as type "dword".win_regedit:key: HKCU:\Software\MyCompanyvalue: hellodata: 1337datatype: dword
# Delete Registry Key MyCompany# NOTE: Not specifying a value will delete the root key which means# all values will be deletedwin_regedit:key: HKCU:\Software\MyCompanystate: absent
# Delete Registry Value "hello" from MyCompany Keywin_regedit:key: HKCU:\Software\MyCompanyvalue: hellostate: absent
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_scheduled_task - Manage scheduled tasks
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manage scheduled tasks
Options
1.6. Module Index 725
Ansible 1.2 Documentation, Release 0.01
Examples
# Create a scheduled task to open a command promptwin_scheduled_task: name="TaskName" execute="cmd" frequency="daily" time="9am→˓" description="open command prompt" path="example" enable=yes→˓state=present user=SYSTEM
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_service - Manages Windows services
New in version 1.7.
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
Manages Windows services
Options
Examples
# Restart a servicewin_service:name: spoolerstate: restarted
# Set service startup mode to auto and ensure it is startedwin_service:name: spoolerstart_mode: autostate: started
This is a Core Module
For more information on what this means please read Core Modules
726 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_stat - returns information about a Windows file
New in version 1.7.
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
Returns information about a Windows file
Options
Examples
# Obtain information about a file
- win_stat: path=C:\foo.iniregister: file_info
- debug: var=file_info
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_template - Templates a file out to a remote server.
New in version 1.9.2.
• Synopsis
• Options
• Examples
• Notes
• This is a Core Module
1.6. Module Index 727
Ansible 1.2 Documentation, Release 0.01
Synopsis
Templates are processed by the Jinja2 templating language (http://jinja.pocoo.org/docs/) - documentation on the tem-plate formatting can be found in the Template Designer Documentation (http://jinja.pocoo.org/docs/templates/). Sixadditional variables can be used in templates: ansible_managed (configurable via the defaults section ofansible.cfg) contains a string which can be used to describe the template name, host, modification time of the tem-plate file and the owner uid, template_host contains the node name of the template’s machine, template_uidthe owner, template_path the absolute path of the template, template_fullpath is the absolute path of thetemplate, and template_run_date is the date that the template was rendered. Note that including a string thatuses a date in the template will result in the template being marked ‘changed’ each time.
Options
Examples
# Playbook Example (win_template can only be run inside a playbook)- win_template: src=/mytemplates/file.conf.j2 dest=C:\temp\file.conf
Notes
Note: templates are loaded with trim_blocks=True.
Note: By default, windows line endings are not created in the generated file.
Note: In order to ensure windows line endings are in the generated file, add the following header as the first line ofyour template: #jinja2: newline_sequence:’\r\n’ and ensure each line of the template ends with \r\n
Note: Beware fetching files from windows machines when creating templates because certain tools, such as Pow-ershell ISE, and regedit’s export facility add a Byte Order Mark as the first character of the file, which can causetracebacks.
Note: Use “od -cx” to examine your templates for Byte Order Marks.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
728 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
win_unzip - Unzips compressed files and archives on the Windows node
New in version 2.0.
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Unzips compressed files and archives. For extracting any compression types other than .zip, the PowerShellCommu-nityExtensions (PSCX) Module is required. This module (in conjunction with PSCX) has the ability to recursivelyunzip files within the src zip file provided and also functionality for many other compression types. If the destinationdirectory does not exist, it will be created before unzipping the file. Specifying rm parameter will force removal of thesrc file after extraction.
Options
Examples
# This unzips a library that was downloaded with win_get_url, and removes→˓the file after extraction$ ansible -i hosts -m win_unzip -a "src=C:\LibraryToUnzip.zip dest=C:\Lib→˓rm=true" all# Playbook example
# Simple unzip---- name: Unzip a bz2 (BZip) filewin_unzip:
src: "C:\Users\Phil\Logs.bz2"dest: "C:\Users\Phil\OldLogs"creates: "C:\Users\Phil\OldLogs"
# This playbook example unzips a .zip file and recursively decompresses the→˓contained .gz files and removes all unneeded compressed files after→˓completion.---- name: Unzip ApplicationLogs.zip and decompress all GZipped log fileshosts: allgather_facts: falsetasks:
- name: Recursively decompress GZ files in ApplicationLogs.zipwin_unzip:src: C:\Downloads\ApplicationLogs.zipdest: C:\Application\Logsrecurse: yesrm: true
1.6. Module Index 729
Ansible 1.2 Documentation, Release 0.01
# Install PSCX to use for extracting a gz file- name: Grab PSCX msi
win_get_url:url: 'http://download-codeplex.sec.s-msft.com/Download/Release?
→˓ProjectName=pscx&DownloadId=923562&FileTime=130585918034470000&Build=20959'dest: 'C:\pscx.msi'
- name: Install PSCXwin_msi:
path: 'C:\pscx.msi'- name: Unzip gz log
win_unzip:src: "C:\Logs\application-error-logs.gz"dest: "C:\ExtractedLogs\application-error-logs"
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_updates - Download and install Windows updates
New in version 2.0.
• Synopsis
• Options
• Examples
• Return Values
• Notes
• This is an Extras Module
Synopsis
Searches, downloads, and installs Windows updates synchronously by automating the Windows Update client
Options
Examples
# Install all security, critical, and rollup updateswin_updates:
category_names: ['SecurityUpdates','CriticalUpdates','UpdateRollups']
# Install only security updateswin_updates: category_names=SecurityUpdates
730 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# Search-only, return list of found updates (if any), log to c:nsible_wu.txtwin_updates: category_names=SecurityUpdates status=searched log_path=c:/→˓ansible_wu.txt
Return Values
Common return values are documented here Common Return Values, the following are the fields unique to this module:
Notes
Note: win_updates must be run by a user with membership in the local Administrators group
Note: win_updates will use the default update service configured for the machine (Windows Update, MicrosoftUpdate, WSUS, etc)
Note: win_updates does not manage reboots, but will signal when a reboot is required with the reboot_required returnvalue.
Note: win_updates can take a significant amount of time to complete (hours, in some cases). Performance dependson many factors, including OS version, number of updates, system load, and update server load.
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_user - Manages local Windows user accounts
New in version 1.7.
• Synopsis
• Options
• Examples
• This is a Core Module
1.6. Module Index 731
Ansible 1.2 Documentation, Release 0.01
Synopsis
Manages local Windows user accounts
Options
Examples
# Ad-hoc example$ ansible -i hosts -m win_user -a "name=bob password=Password12345→˓groups=Users" all$ ansible -i hosts -m win_user -a "name=bob state=absent" all
# Playbook example---- name: Add a userhosts: allgather_facts: falsetasks:
- name: Add Userwin_user:name: ansiblepassword: "@ns1bl3"groups: ["Users"]
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
win_webpicmd - Installs packages using Web Platform Installer command-line
New in version 2.0.
• Synopsis
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
Installs packages using Web Platform Installer command-line (http://www.iis.net/learn/install/web-platform-installer/web-platform-installer-v4-command-line-webpicmdexe-rtw-release). Must be installed and present in PATH (see
732 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
win_chocolatey module; ‘webpicmd’ is the package name, and you must install ‘lessmsi’ first too) Install IIS first (seewin_feature module)
Options
Examples
# Install URLRewrite2.win_webpicmd:name: URLRewrite2
Notes
Note: accepts EULAs and suppresses reboot - you will need to check manage reboots yourself (see win_rebootmodule)
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
xattr - set/retrieve extended attributes
New in version 1.3.
• Synopsis
• Options
• Examples
• This is a Core Module
Synopsis
Manages filesystem user defined extended attributes, requires that they are enabled on the target filesystem and thatthe setfattr/getfattr utilities are present.
Options
1.6. Module Index 733
Ansible 1.2 Documentation, Release 0.01
Examples
# Obtain the extended attributes of /etc/foo.conf- xattr: name=/etc/foo.conf
# Sets the key 'foo' to value 'bar'- xattr: path=/etc/foo.conf key=user.foo value=bar
# Removes the key 'foo'- xattr: name=/etc/foo.conf key=user.foo state=absent
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
xenserver_facts - get facts reported on xenserver
New in version 2.0.
• Synopsis
• Examples
• This is an Extras Module
Synopsis
Reads data out of XenAPI, can be used instead of multiple xe commands.
Examples
- name: Gather facts from xenserverxenserver:
- name: Print running VMsdebug: msg="{{ item }}"with_items: xs_vms.keys()when: xs_vms[item]['power_state'] == "Running"
TASK: [Print running VMs]→˓***********************************************************skipping: [10.13.0.22] => (item=CentOS 4.7 (32-bit))ok: [10.13.0.22] => (item=Control domain on host: 10.0.13.22) => {
"item": "Control domain on host: 10.0.13.22","msg": "Control domain on host: 10.0.13.22"
}
734 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
yum - Manages packages with the yum package manager
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is a Core Module
Synopsis
Installs, upgrade, removes, and lists packages and groups with the yum package manager.
Requirements
• yum
Options
Examples
- name: install the latest version of Apacheyum: name=httpd state=latest
- name: remove the Apache packageyum: name=httpd state=absent
- name: install the latest version of Apache from the testing repoyum: name=httpd enablerepo=testing state=present
- name: install one specific version of Apacheyum: name=httpd-2.2.29-1.4.amzn1 state=present
- name: upgrade all packagesyum: name=* state=latest
- name: install the nginx rpm from a remote repoyum: name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-
→˓centos-6-0.el6.ngx.noarch.rpm state=present
1.6. Module Index 735
Ansible 1.2 Documentation, Release 0.01
- name: install nginx rpm from a local fileyum: name=/usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm
→˓state=present
- name: install the 'Development tools' package groupyum: name="@Development tools" state=present
- name: install the 'Gnome desktop' environment groupyum: name="@^gnome-desktop-environment" state=present
Notes
Note: When used with a loop of package names in a playbook, ansible optimizes the call to the yum module. Insteadof calling the module with a single package each time through the loop, ansible calls the module once with all of thepackage names from the loop.
Note: In versions prior to 1.9.2 this module installed and removed each package given to the yum module separately.This caused problems when packages specified by filename or url had to be installed or removed together. In 1.9.2this was fixed so that packages are installed in one yum transaction. However, if one of the packages adds a newyum repository that the other packages come from (such as epel-release) then that package needs to be installed in aseparate task. This mimics yum’s command line behaviour.
Note: Yum itself has two types of groups. “Package groups” are specified in the rpm itself while “environmentgroups” are specified in a separate file (usually by the distribution). Unfortunately, this division becomes apparent toansible users because ansible needs to operate on the group of packages in a single transaction and yum requires groupsto be specified in different ways when used in that way. Package groups are specified as “@development-tools” andenvironment groups are “@^gnome-desktop-environment”. Use the “yum group list” command to see which categoryof group the group you want to install falls into.
This is a Core Module
For more information on what this means please read Core Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
zabbix_group - Zabbix host groups creates/deletes
New in version 1.8.
• Synopsis
• Requirements
• Options
736 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Examples
• Notes
• This is an Extras Module
Synopsis
Create host groups if they do not exist. Delete existing host groups if they exist.
Requirements
• python >= 2.6
• zabbix-api
Options
Examples
# Base create host groups example- name: Create host groupslocal_action:
module: zabbix_groupserver_url: http://monitor.example.comlogin_user: usernamelogin_password: passwordstate: presenthost_groups:
- Example group1- Example group2
# Limit the Zabbix group creations to one host since Zabbix can return an→˓error when doing concurent updates- name: Create host groupslocal_action:
module: zabbix_groupserver_url: http://monitor.example.comlogin_user: usernamelogin_password: passwordstate: presenthost_groups:- Example group1- Example group2
when: inventory_hostname==groups['group_name'][0]
Notes
Note: Too many concurrent updates to the same group may cause Zabbix to return errors, see examples for aworkaround if needed.
1.6. Module Index 737
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
zabbix_host - Zabbix host creates/updates/deletes
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
This module allows you to create, modify and delete Zabbix host entries and associated group and template data.
Requirements
• python >= 2.6
• zabbix-api
Options
Examples
- name: Create a new host or update an existing host's infolocal_action:
module: zabbix_hostserver_url: http://monitor.example.comlogin_user: usernamelogin_password: passwordhost_name: ExampleHosthost_groups:
- Example group1- Example group2
link_templates:- Example template1- Example template2
status: enabledstate: presentinterfaces:
- type: 1
738 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
main: 1useip: 1ip: 10.xx.xx.xxdns: ""port: 10050
- type: 4main: 1useip: 1ip: 10.xx.xx.xxdns: ""port: 12345
proxy: a.zabbix.proxy
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
zabbix_hostmacro - Zabbix host macro creates/updates/deletes
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
manages Zabbix host macros, it can create, update or delete them.
Requirements
• python >= 2.6
• zabbix-api
Options
Examples
1.6. Module Index 739
Ansible 1.2 Documentation, Release 0.01
- name: Create a new host macro or update an existing macro's valuelocal_action:
module: zabbix_hostmacroserver_url: http://monitor.example.comlogin_user: usernamelogin_password: passwordhost_name: ExampleHostmacro_name:Example macromacro_value:Example valuestate: present
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
zabbix_maintenance - Create Zabbix maintenance windows
New in version 1.8.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
This module will let you create Zabbix maintenance windows.
Requirements
• python >= 2.6
• zabbix-api
Options
Examples
740 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
# Create maintenance window named "Update of www1"# for host www1.example.com for 90 minutes- zabbix_maintenance: name="Update of www1"
host_name=www1.example.comstate=presentminutes=90server_url=https://monitoring.example.comlogin_user=ansiblelogin_password=pAsSwOrD
# Create maintenance window named "Mass update"# for host www1.example.com and host groups Office and Dev- zabbix_maintenance: name="Update of www1"
host_name=www1.example.comhost_groups=Office,Devstate=presentserver_url=https://monitoring.example.comlogin_user=ansiblelogin_password=pAsSwOrD
# Create maintenance window named "update"# for hosts www1.example.com and db1.example.com and without data collection.- zabbix_maintenance: name=update
host_names=www1.example.com,db1.example.comstate=presentcollect_data=falseserver_url=https://monitoring.example.comlogin_user=ansiblelogin_password=pAsSwOrD
# Remove maintenance window named "Test1"- zabbix_maintenance: name=Test1
state=absentserver_url=https://monitoring.example.comlogin_user=ansiblelogin_password=pAsSwOrD
Notes
Note: Useful for setting hosts in maintenance mode before big update, and removing maintenance window afterupdate.
Note: Module creates maintenance window from now() to now() + minutes, so if Zabbix server’s time and host’stime are not synchronized, you will get strange results.
Note: Install required module with ‘pip install zabbix-api’ command.
Note: Checks existance only by maintenance name.
1.6. Module Index 741
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
zabbix_screen - Zabbix screen creates/updates/deletes
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• Notes
• This is an Extras Module
Synopsis
This module allows you to create, modify and delete Zabbix screens and associated graph data.
Requirements
• python >= 2.6
• zabbix-api
Options
Examples
# Create/update a screen.- name: Create a new screen or update an existing screen's itemslocal_action:
module: zabbix_screenserver_url: http://monitor.example.comlogin_user: usernamelogin_password: passwordscreens:
- screen_name: ExampleScreen1host_group: Example group1state: presentgraph_names:- Example graph1- Example graph2
graph_width: 200
742 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
graph_height: 100
# Create/update multi-screen- name: Create two of new screens or update the existing screens' itemslocal_action:
module: zabbix_screenserver_url: http://monitor.example.comlogin_user: usernamelogin_password: passwordscreens:
- screen_name: ExampleScreen1host_group: Example group1state: presentgraph_names:- Example graph1- Example graph2
graph_width: 200graph_height: 100
- screen_name: ExampleScreen2host_group: Example group2state: presentgraph_names:- Example graph1- Example graph2
graph_width: 200graph_height: 100
# Limit the Zabbix screen creations to one host since Zabbix can return an→˓error when doing concurent updates- name: Create a new screen or update an existing screen's itemslocal_action:
module: zabbix_screenserver_url: http://monitor.example.comlogin_user: usernamelogin_password: passwordstate: presentscreens:- screen_name: ExampleScreenhost_group: Example groupstate: presentgraph_names:- Example graph1- Example graph2
graph_width: 200graph_height: 100
when: inventory_hostname==groups['group_name'][0]
Notes
Note: Too many concurrent updates to the same screen may cause Zabbix to return errors, see examples for aworkaround if needed.
1.6. Module Index 743
Ansible 1.2 Documentation, Release 0.01
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
zfs - Manage zfs
• Synopsis
• Options
• Examples
• This is an Extras Module
Synopsis
Manages ZFS file systems on Solaris and FreeBSD. Can manage file systems, volumes and snapshots. See zfs(1M)for more information about the properties.
Options
Examples
# Create a new file system called myfs in pool rpool- zfs: name=rpool/myfs state=present
# Create a new volume called myvol in pool rpool.- zfs: name=rpool/myvol state=present volsize=10M
# Create a snapshot of rpool/myfs file system.- zfs: name=rpool/myfs@mysnapshot state=present
# Create a new file system called myfs2 with snapdir enabled- zfs: name=rpool/myfs2 state=present snapdir=enabled
# Create a new file system by cloning a snapshot- zfs: name=rpool/cloned_fs state=present origin=rpool/myfs@mysnapshot
# Destroy a filesystem- zfs: name=rpool/myfs state=absent
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
744 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
znode - Create, delete, retrieve, and update znodes using ZooKeeper.
New in version 2.0.
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Requirements
• kazoo >= 2.1
• python >= 2.6
Options
Examples
# Creating or updating a znode with a given value- action: znode hosts=localhost:2181 name=/mypath value=myvalue state=present
# Getting the value and stat structure for a znode- action: znode hosts=localhost:2181 name=/mypath op=get
# Listing a particular znode's children- action: znode hosts=localhost:2181 name=/zookeeper op=list
# Waiting 20 seconds for a znode to appear at path /mypath- action: znode hosts=localhost:2181 name=/mypath op=wait timeout=20
# Deleting a znode at path /mypath- action: znode hosts=localhost:2181 name=/mypath state=absent
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
zypper - Manage packages on SUSE and openSUSE
1.6. Module Index 745
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Manage packages on SUSE and openSUSE using the zypper and rpm tools.
Requirements
• zypper
• rpm
Options
Examples
# Install "nmap"- zypper: name=nmap state=present
# Install apache2 with recommended packages- zypper: name=apache2 state=present disable_recommends=no
# Remove the "nmap" package- zypper: name=nmap state=absent
# Install the nginx rpm from a remote repo- zypper: name=http://nginx.org/packages/sles/12/x86_64/RPMS/nginx-1.8.0-1.→˓sles12.ngx.x86_64.rpm state=present
# Install local rpm file- zypper: name=/tmp/fancy-software.rpm state=present
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
zypper_repository - Add and remove Zypper repositories
New in version 1.4.
746 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• Synopsis
• Requirements
• Options
• Examples
• This is an Extras Module
Synopsis
Add or remove Zypper repositories on SUSE and openSUSE
Requirements
• zypper
Options
Examples
# Add NVIDIA repository for graphics drivers- zypper_repository: name=nvidia-repo repo='ftp://download.nvidia.com/→˓opensuse/12.2' state=present
# Remove NVIDIA repository- zypper_repository: name=nvidia-repo repo='ftp://download.nvidia.com/→˓opensuse/12.2' state=absent
# Add python development repository- zypper_repository: repo=http://download.opensuse.org/repositories/devel:/→˓languages:/python/SLE_11_SP3/devel:languages:python.repo
This is an Extras Module
For more information on what this means please read Extras Modules
For help in developing on modules, should you be so inclined, please read Community Information & Contributing,Helping Testing PRs and Developing Modules.
Note:
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
1.6. Module Index 747
Ansible 1.2 Documentation, Release 0.01
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
Cloud Modules
Amazon
Azure
Centurylink
Cloudstack
Digital Ocean
Docker
Linode
Lxc
Misc
Openstack
Profitbricks
Rackspace
Vmware
Webfaction
Note:
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
748 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Clustering Modules
Note:
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
Commands Modules
Note:
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
Database Modules
Misc
Mysql
Postgresql
Vertica
Note:
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
1.6. Module Index 749
Ansible 1.2 Documentation, Release 0.01
Files Modules
Note:
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
Inventory Modules
Note:
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
Messaging Modules
Note:
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
Monitoring Modules
Note:
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
750 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
Network Modules
A10
Basics
Citrix
F5
Note:
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
Notification Modules
Note:
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
Packaging Modules
Language
Os
1.6. Module Index 751
Ansible 1.2 Documentation, Release 0.01
Note:
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
Source Control Modules
Note:
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
System Modules
Note:
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
Utilities Modules
Helper
Logic
Note:
752 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
Web Infrastructure Modules
Note:
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
Windows Modules
Note:
• (D): This marks a module as deprecated, which means a module is kept for backwards compatibility but usageis discouraged. The module documentation details page may explain more about this rationale.
• (E): This marks a module as ‘extras’, which means it ships with ansible but may be a newer module and possibly(but not necessarily) less actively maintained than ‘core’ modules.
• Tickets filed on modules are filed to different repos than those on the main open source project. Core moduletickets should be filed at ansible/ansible-modules-core on GitHub, extras tickets to ansible/ansible-modules-extras on GitHub
Detailed Guides
This section is new and evolving. The idea here is explore particular use cases in greater depth and provide a more“top down” explanation of some basic features.
Amazon Web Services Guide
Introduction
Ansible contains a number of modules for controlling Amazon Web Services (AWS). The purpose of this section is toexplain how to put Ansible modules together (and use inventory scripts) to use Ansible in AWS context.
1.7. Detailed Guides 753
Ansible 1.2 Documentation, Release 0.01
Requirements for the AWS modules are minimal.
All of the modules require and are tested against recent versions of boto. You’ll need this Python module installed onyour control machine. Boto can be installed from your OS distribution or python’s “pip install boto”.
Whereas classically ansible will execute tasks in its host loop against multiple remote machines, most cloud-controlsteps occur on your local machine with reference to the regions to control.
In your playbook steps we’ll typically be using the following pattern for provisioning steps:
- hosts: localhostconnection: localgather_facts: Falsetasks:- ...
Authentication
Authentication with the AWS-related modules is handled by either specifying your access and secret key as ENVvariables or module arguments.
For environment variables:
export AWS_ACCESS_KEY_ID='AK123'export AWS_SECRET_ACCESS_KEY='abc123'
For storing these in a vars_file, ideally encrypted with ansible-vault:
---ec2_access_key: "--REMOVED--"ec2_secret_key: "--REMOVED--"
Provisioning
The ec2 module provisions and de-provisions instances within EC2.
An example of making sure there are only 5 instances tagged ‘Demo’ in EC2 follows.
In the example below, the “exact_count” of instances is set to 5. This means if there are 0 instances already existing,then 5 new instances would be created. If there were 2 instances, only 3 would be created, and if there were 8 instances,3 instances would be terminated.
What is being counted is specified by the “count_tag” parameter. The parameter “instance_tags” is used to apply tagsto the newly created instance.:
# demo_setup.yml
- hosts: localhostconnection: localgather_facts: False
tasks:
- name: Provision a set of instancesec2:
key_name: my_keygroup: test
754 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
instance_type: t2.microimage: "{{ ami_id }}"wait: trueexact_count: 5count_tag:
Name: Demoinstance_tags:
Name: Demoregister: ec2
The data about what instances are created is being saved by the “register” keyword in the variable named “ec2”.
From this, we’ll use the add_host module to dynamically create a host group consisting of these new instances. Thisfacilitates performing configuration actions on the hosts immediately in a subsequent task.:
# demo_setup.yml
- hosts: localhostconnection: localgather_facts: False
tasks:
- name: Provision a set of instancesec2:
key_name: my_keygroup: testinstance_type: t2.microimage: "{{ ami_id }}"wait: trueexact_count: 5count_tag:
Name: Demoinstance_tags:
Name: Demoregister: ec2
- name: Add all instance public IPs to host groupadd_host: hostname={{ item.public_ip }} groups=ec2hostswith_items: ec2.instances
With the host group now created, a second play at the bottom of the the same provisioning playbook file might nowhave some configuration steps:
# demo_setup.yml
- name: Provision a set of instanceshosts: localhost# ... AS ABOVE ...
- hosts: ec2hostsname: configuration playuser: ec2-usergather_facts: true
tasks:
- name: Check NTP service
1.7. Detailed Guides 755
Ansible 1.2 Documentation, Release 0.01
service: name=ntpd state=started
Host Inventory
Once your nodes are spun up, you’ll probably want to talk to them again. With a cloud setup, it’s best to not maintaina static list of cloud hostnames in text files. Rather, the best way to handle this is to use the ec2 dynamic inventoryscript. See Dynamic Inventory.
This will also dynamically select nodes that were even created outside of Ansible, and allow Ansible to manage them.
See Dynamic Inventory for how to use this, then flip back over to this chapter.
Tags And Groups And Variables
When using the ec2 inventory script, hosts automatically appear in groups based on how they are tagged in EC2.
For instance, if a host is given the “class” tag with the value of “webserver”, it will be automatically discoverable viaa dynamic group like so:
- hosts: tag_class_webservertasks:- ping
Using this philosophy can be a great way to keep systems separated by the function they perform.
In this example, if we wanted to define variables that are automatically applied to each machine tagged with the ‘class’of ‘webserver’, ‘group_vars’ in ansible can be used. See Splitting Out Host and Group Specific Data.
Similar groups are available for regions and other classifications, and can be similarly assigned variables using thesame mechanism.
Autoscaling with Ansible Pull
Amazon Autoscaling features automatically increase or decrease capacity based on load. There are also Ansiblemodules shown in the cloud documentation that can configure autoscaling policy.
When nodes come online, it may not be sufficient to wait for the next cycle of an ansible command to come along andconfigure that node.
To do this, pre-bake machine images which contain the necessary ansible-pull invocation. Ansible-pull is a commandline tool that fetches a playbook from a git server and runs it locally.
One of the challenges of this approach is that there needs to be a centralized way to store data about the results of pullcommands in an autoscaling context. For this reason, the autoscaling solution provided below in the next section canbe a better approach.
Read Ansible-Pull for more information on pull-mode playbooks.
Autoscaling with Ansible Tower
Ansible Tower also contains a very nice feature for auto-scaling use cases. In this mode, a simple curl script can call adefined URL and the server will “dial out” to the requester and configure an instance that is spinning up. This can bea great way to reconfigure ephemeral nodes. See the Tower install and product documentation for more details.
A benefit of using the callback in Tower over pull mode is that job results are still centrally recorded and less informa-tion has to be shared with remote hosts.
756 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Ansible With (And Versus) CloudFormation
CloudFormation is a Amazon technology for defining a cloud stack as a JSON document.
Ansible modules provide an easier to use interface than CloudFormation in many examples, without defining a com-plex JSON document. This is recommended for most users.
However, for users that have decided to use CloudFormation, there is an Ansible module that can be used to apply aCloudFormation template to Amazon.
When using Ansible with CloudFormation, typically Ansible will be used with a tool like Packer to build images, andCloudFormation will launch those images, or ansible will be invoked through user data once the image comes online,or a combination of the two.
Please see the examples in the Ansible CloudFormation module for more details.
AWS Image Building With Ansible
Many users may want to have images boot to a more complete configuration rather than configuring them entirelyafter instantiation. To do this, one of many programs can be used with Ansible playbooks to define and upload a baseimage, which will then get its own AMI ID for usage with the ec2 module or other Ansible AWS modules such asec2_asg or the cloudformation module. Possible tools include Packer, aminator, and Ansible’s ec2_ami module.
Generally speaking, we find most users using Packer.
Documentation for the Ansible Packer provisioner can be found here.
If you do not want to adopt Packer at this time, configuring a base-image with Ansible after provisioning (as shownabove) is acceptable.
Next Steps: Explore Modules
Ansible ships with lots of modules for configuring a wide array of EC2 services. Browse the “Cloud” category of themodule documentation for a full list with examples.
See also:
About Modules All the documentation for Ansible modules
Playbooks An introduction to playbooks
Delegation, Rolling Updates, and Local Actions Delegation, useful for working with loud balancers, clouds, and lo-cally executed steps.
User Mailing List Have a question? Stop by the google group!
irc.freenode.net #ansible IRC chat channel
Rackspace Cloud Guide
Introduction
Note: This section of the documentation is under construction. We are in the process of adding more examples aboutthe Rackspace modules and how they work together. Once complete, there will also be examples for Rackspace Cloudin ansible-examples.
1.7. Detailed Guides 757
Ansible 1.2 Documentation, Release 0.01
Ansible contains a number of core modules for interacting with Rackspace Cloud.
The purpose of this section is to explain how to put Ansible modules together (and use inventory scripts) to use Ansiblein a Rackspace Cloud context.
Prerequisites for using the rax modules are minimal. In addition to ansible itself, all of the modules require and aretested against pyrax 1.5 or higher. You’ll need this Python module installed on the execution host.
pyrax is not currently available in many operating system package repositories, so you will likely need to install it viapip:
$ pip install pyrax
The following steps will often execute from the control machine against the Rackspace Cloud API, so it makes senseto add localhost to the inventory file. (Ansible may not require this manual step in the future):
[localhost]localhost ansible_connection=local
In playbook steps, we’ll typically be using the following pattern:
- hosts: localhostconnection: localgather_facts: Falsetasks:
Credentials File
The rax.py inventory script and all rax modules support a standard pyrax credentials file that looks like:
[rackspace_cloud]username = myraxusernameapi_key = d41d8cd98f00b204e9800998ecf8427e
Setting the environment parameter RAX_CREDS_FILE to the path of this file will help Ansible find how to load thisinformation.
More information about this credentials file can be found at https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
Running from a Python Virtual Environment (Optional)
Most users will not be using virtualenv, but some users, particularly Python developers sometimes like to.
There are special considerations when Ansible is installed to a Python virtualenv, rather than the default of installingat a global scope. Ansible assumes, unless otherwise instructed, that the python binary will live at /usr/bin/python.This is done via the interpreter line in modules, however when instructed by setting the inventory variable ‘ansi-ble_python_interpreter’, Ansible will use this specified path instead to find Python. This can be a cause of confusionas one may assume that modules running on ‘localhost’, or perhaps running via ‘local_action’, are using the virtualenvPython interpreter. By setting this line in the inventory, the modules will execute in the virtualenv interpreter andhave available the virtualenv packages, specifically pyrax. If using virtualenv, you may wish to modify your localhostinventory definition to find this location as follows:
[localhost]localhost ansible_connection=local ansible_python_interpreter=/path/to/ansible_venv/→˓bin/python
758 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: pyrax may be installed in the global Python package scope or in a virtual environment. There are no specialconsiderations to keep in mind when installing pyrax.
Provisioning
Now for the fun parts.
The ‘rax’ module provides the ability to provision instances within Rackspace Cloud. Typically the provisioning taskwill be performed from your Ansible control server (in our example, localhost) against the Rackspace cloud API. Thisis done for several reasons:
• Avoiding installing the pyrax library on remote nodes
• No need to encrypt and distribute credentials to remote nodes
• Speed and simplicity
Note: Authentication with the Rackspace-related modules is handled by either specifying your username and APIkey as environment variables or passing them as module arguments, or by specifying the location of a credentials file.
Here is a basic example of provisioning an instance in ad-hoc mode:
$ ansible localhost -m rax -a "name=awx flavor=4 image=ubuntu-1204-lts-precise-→˓pangolin wait=yes" -c local
Here’s what it would look like in a playbook, assuming the parameters were defined in variables:
tasks:- name: Provision a set of instanceslocal_action:
module: raxname: "{{ rax_name }}"flavor: "{{ rax_flavor }}"image: "{{ rax_image }}"count: "{{ rax_count }}"group: "{{ group }}"wait: yes
register: rax
The rax module returns data about the nodes it creates, like IP addresses, hostnames, and login passwords. By reg-istering the return value of the step, it is possible used this data to dynamically add the resulting hosts to inventory(temporarily, in memory). This facilitates performing configuration actions on the hosts in a follow-on task. In thefollowing example, the servers that were successfully created using the above task are dynamically added to a groupcalled “raxhosts”, with each nodes hostname, IP address, and root password being added to the inventory.
Note: Ansible 2.0 has deprecated the “ssh” from ansible_ssh_user, ansible_ssh_host, andansible_ssh_port to become ansible_user, ansible_host, and ansible_port. If you are usinga version of Ansible prior to 2.0, you should continue using the older style variables (ansible_ssh_*). Theseshorter variables are ignored, without warning, in older versions of Ansible.
- name: Add the instances we created (by public IP) to the group 'raxhosts'local_action:
1.7. Detailed Guides 759
Ansible 1.2 Documentation, Release 0.01
module: add_hosthostname: "{{ item.name }}"ansible_host: "{{ item.rax_accessipv4 }}"ansible_ssh_pass: "{{ item.rax_adminpass }}"groups: raxhosts
with_items: rax.successwhen: rax.action == 'create'
With the host group now created, the next play in this playbook could now configure servers belonging to the raxhostsgroup.
- name: Configuration playhosts: raxhostsuser: rootroles:- ntp- webserver
The method above ties the configuration of a host with the provisioning step. This isn’t always what you want, andleads us to the next section.
Host Inventory
Once your nodes are spun up, you’ll probably want to talk to them again. The best way to handle his is to use the “rax”inventory plugin, which dynamically queries Rackspace Cloud and tells Ansible what nodes you have to manage.You might want to use this even if you are spinning up Ansible via other tools, including the Rackspace Cloud userinterface. The inventory plugin can be used to group resources by metadata, region, OS, etc. Utilizing metadata ishighly recommended in “rax” and can provide an easy way to sort between host groups and roles. If you don’t wantto use the rax.py dynamic inventory script, you could also still choose to manually manage your INI inventory file,though this is less recommended.
In Ansible it is quite possible to use multiple dynamic inventory plugins along with INI file data. Just put them in acommon directory and be sure the scripts are chmod +x, and the INI-based ones are not.
rax.py
To use the rackspace dynamic inventory script, copy rax.py into your inventory directory and make it executable.You can specify a credentials file for rax.py utilizing the RAX_CREDS_FILE environment variable.
Note: Dynamic inventory scripts (like rax.py) are saved in /usr/share/ansible/inventory if Ansiblehas been installed globally. If installed to a virtualenv, the inventory scripts are installed to $VIRTUALENV/share/inventory.
Note: Users of Ansible Tower will note that dynamic inventory is natively supported by Tower, and all you have todo is associate a group with your Rackspace Cloud credentials, and it will easily synchronize without going throughthese steps:
$ RAX_CREDS_FILE=~/.raxpub ansible all -i rax.py -m setup
rax.py also accepts a RAX_REGION environment variable, which can contain an individual region, or a commaseparated list of regions.
760 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
When using rax.py, you will not have a ‘localhost’ defined in the inventory.
As mentioned previously, you will often be running most of these modules outside of the host loop, and will need‘localhost’ defined. The recommended way to do this, would be to create an inventory directory, and place boththe rax.py script and a file containing localhost in it.
Executing ansible or ansible-playbook and specifying the inventory directory instead of an individualfile, will cause ansible to evaluate each file in that directory for inventory.
Let’s test our inventory script to see if it can talk to Rackspace Cloud.
$ RAX_CREDS_FILE=~/.raxpub ansible all -i inventory/ -m setup
Assuming things are properly configured, the rax.py inventory script will output information similar to the followinginformation, which will be utilized for inventory and variables.
{"ORD": [
"test"],"_meta": {
"hostvars": {"test": {
"ansible_host": "1.1.1.1","rax_accessipv4": "1.1.1.1","rax_accessipv6": "2607:f0d0:1002:51::4","rax_addresses": {
"private": [{
"addr": "2.2.2.2","version": 4
}],"public": [
{"addr": "1.1.1.1","version": 4
},{
"addr": "2607:f0d0:1002:51::4","version": 6
}]
},"rax_config_drive": "","rax_created": "2013-11-14T20:48:22Z","rax_flavor": {
"id": "performance1-1","links": [
{"href": "https://ord.servers.api.rackspacecloud.com/
→˓111111/flavors/performance1-1","rel": "bookmark"
}]
},"rax_hostid":
→˓"e7b6961a9bd943ee82b13816426f1563bfda6846aad84d52af45a4904660cde0","rax_human_id": "test",
1.7. Detailed Guides 761
Ansible 1.2 Documentation, Release 0.01
"rax_id": "099a447b-a644-471f-87b9-a7f580eb0c2a","rax_image": {
"id": "b211c7bf-b5b4-4ede-a8de-a4368750c653","links": [
{"href": "https://ord.servers.api.rackspacecloud.com/
→˓111111/images/b211c7bf-b5b4-4ede-a8de-a4368750c653","rel": "bookmark"
}]
},"rax_key_name": null,"rax_links": [
{"href": "https://ord.servers.api.rackspacecloud.com/v2/111111/
→˓servers/099a447b-a644-471f-87b9-a7f580eb0c2a","rel": "self"
},{
"href": "https://ord.servers.api.rackspacecloud.com/111111/→˓servers/099a447b-a644-471f-87b9-a7f580eb0c2a",
"rel": "bookmark"}
],"rax_metadata": {
"foo": "bar"},"rax_name": "test","rax_name_attr": "name","rax_networks": {
"private": ["2.2.2.2"
],"public": [
"1.1.1.1","2607:f0d0:1002:51::4"
]},"rax_os-dcf_diskconfig": "AUTO","rax_os-ext-sts_power_state": 1,"rax_os-ext-sts_task_state": null,"rax_os-ext-sts_vm_state": "active","rax_progress": 100,"rax_status": "ACTIVE","rax_tenant_id": "111111","rax_updated": "2013-11-14T20:49:27Z","rax_user_id": "22222"
}}
}}
Standard Inventory
When utilizing a standard ini formatted inventory file (as opposed to the inventory plugin), it may still be advantageousto retrieve discoverable hostvar information from the Rackspace API.
762 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
This can be achieved with the rax_facts module and an inventory file similar to the following:
[test_servers]hostname1 rax_region=ORDhostname2 rax_region=ORD
- name: Gather info about servershosts: test_serversgather_facts: Falsetasks:- name: Get facts about servers
local_action:module: rax_factscredentials: ~/.raxpubname: "{{ inventory_hostname }}"region: "{{ rax_region }}"
- name: Map some factsset_fact:
ansible_host: "{{ rax_accessipv4 }}"
While you don’t need to know how it works, it may be interesting to know what kind of variables are returned.
The rax_facts module provides facts as followings, which match the rax.py inventory script:
{"ansible_facts": {
"rax_accessipv4": "1.1.1.1","rax_accessipv6": "2607:f0d0:1002:51::4","rax_addresses": {
"private": [{
"addr": "2.2.2.2","version": 4
}],"public": [
{"addr": "1.1.1.1","version": 4
},{
"addr": "2607:f0d0:1002:51::4","version": 6
}]
},"rax_config_drive": "","rax_created": "2013-11-14T20:48:22Z","rax_flavor": {
"id": "performance1-1","links": [
{"href": "https://ord.servers.api.rackspacecloud.com/111111/
→˓flavors/performance1-1","rel": "bookmark"
}]
},"rax_hostid":
→˓"e7b6961a9bd943ee82b13816426f1563bfda6846aad84d52af45a4904660cde0",
1.7. Detailed Guides 763
Ansible 1.2 Documentation, Release 0.01
"rax_human_id": "test","rax_id": "099a447b-a644-471f-87b9-a7f580eb0c2a","rax_image": {
"id": "b211c7bf-b5b4-4ede-a8de-a4368750c653","links": [
{"href": "https://ord.servers.api.rackspacecloud.com/111111/images/
→˓b211c7bf-b5b4-4ede-a8de-a4368750c653","rel": "bookmark"
}]
},"rax_key_name": null,"rax_links": [
{"href": "https://ord.servers.api.rackspacecloud.com/v2/111111/servers/
→˓099a447b-a644-471f-87b9-a7f580eb0c2a","rel": "self"
},{
"href": "https://ord.servers.api.rackspacecloud.com/111111/servers/→˓099a447b-a644-471f-87b9-a7f580eb0c2a",
"rel": "bookmark"}
],"rax_metadata": {
"foo": "bar"},"rax_name": "test","rax_name_attr": "name","rax_networks": {
"private": ["2.2.2.2"
],"public": [
"1.1.1.1","2607:f0d0:1002:51::4"
]},"rax_os-dcf_diskconfig": "AUTO","rax_os-ext-sts_power_state": 1,"rax_os-ext-sts_task_state": null,"rax_os-ext-sts_vm_state": "active","rax_progress": 100,"rax_status": "ACTIVE","rax_tenant_id": "111111","rax_updated": "2013-11-14T20:49:27Z","rax_user_id": "22222"
},"changed": false
}
Use Cases
This section covers some additional usage examples built around a specific use case.
764 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Network and Server
Create an isolated cloud network and build a server
- name: Build Servers on an Isolated Networkhosts: localhostconnection: localgather_facts: Falsetasks:- name: Network create request
local_action:module: rax_networkcredentials: ~/.raxpublabel: my-netcidr: 192.168.3.0/24region: IADstate: present
- name: Server create requestlocal_action:
module: raxcredentials: ~/.raxpubname: web%04d.example.orgflavor: 2image: ubuntu-1204-lts-precise-pangolindisk_config: manualnetworks:- public- my-net
region: IADstate: presentcount: 5exact_count: yesgroup: webwait: yeswait_timeout: 360
register: rax
Complete Environment
Build a complete webserver environment with servers, custom networks and load balancers, install nginx and create acustom index.html
---- name: Build environment
hosts: localhostconnection: localgather_facts: Falsetasks:- name: Load Balancer create request
local_action:module: rax_clbcredentials: ~/.raxpubname: my-lbport: 80protocol: HTTP
1.7. Detailed Guides 765
Ansible 1.2 Documentation, Release 0.01
algorithm: ROUND_ROBINtype: PUBLICtimeout: 30region: IADwait: yesstate: presentmeta:app: my-cool-app
register: clb
- name: Network create requestlocal_action:
module: rax_networkcredentials: ~/.raxpublabel: my-netcidr: 192.168.3.0/24state: presentregion: IAD
register: network
- name: Server create requestlocal_action:
module: raxcredentials: ~/.raxpubname: web%04d.example.orgflavor: performance1-1image: ubuntu-1204-lts-precise-pangolindisk_config: manualnetworks:- public- private- my-net
region: IADstate: presentcount: 5exact_count: yesgroup: webwait: yes
register: rax
- name: Add servers to web host grouplocal_action:
module: add_hosthostname: "{{ item.name }}"ansible_host: "{{ item.rax_accessipv4 }}"ansible_ssh_pass: "{{ item.rax_adminpass }}"ansible_user: rootgroups: web
with_items: rax.successwhen: rax.action == 'create'
- name: Add servers to Load balancerlocal_action:
module: rax_clb_nodescredentials: ~/.raxpubload_balancer_id: "{{ clb.balancer.id }}"address: "{{ item.rax_networks.private|first }}"port: 80
766 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
condition: enabledtype: primarywait: yesregion: IAD
with_items: rax.successwhen: rax.action == 'create'
- name: Configure servershosts: webhandlers:- name: restart nginx
service: name=nginx state=restarted
tasks:- name: Install nginx
apt: pkg=nginx state=latest update_cache=yes cache_valid_time=86400notify:
- restart nginx
- name: Ensure nginx starts on bootservice: name=nginx state=started enabled=yes
- name: Create custom index.htmlcopy: content="{{ inventory_hostname }}" dest=/usr/share/nginx/www/index.html
owner=root group=root mode=0644
RackConnect and Managed Cloud
When using RackConnect version 2 or Rackspace Managed Cloud there are Rackspace automation tasks that are exe-cuted on the servers you create after they are successfully built. If your automation executes before the RackConnector Managed Cloud automation, you can cause failures and un-usable servers.
These examples show creating servers, and ensuring that the Rackspace automation has completed before Ansiblecontinues onwards.
For simplicity, these examples are joined, however both are only needed when using RackConnect. When only usingManaged Cloud, the RackConnect portion can be ignored.
The RackConnect portions only apply to RackConnect version 2.
Using a Control Machine
- name: Create an exact count of servershosts: localhostconnection: localgather_facts: Falsetasks:- name: Server build requests
local_action:module: raxcredentials: ~/.raxpubname: web%03d.example.orgflavor: performance1-1image: ubuntu-1204-lts-precise-pangolindisk_config: manual
1.7. Detailed Guides 767
Ansible 1.2 Documentation, Release 0.01
region: DFWstate: presentcount: 1exact_count: yesgroup: webwait: yes
register: rax
- name: Add servers to in memory groupslocal_action:
module: add_hosthostname: "{{ item.name }}"ansible_host: "{{ item.rax_accessipv4 }}"ansible_ssh_pass: "{{ item.rax_adminpass }}"ansible_user: rootrax_id: "{{ item.rax_id }}"groups: web,new_web
with_items: rax.successwhen: rax.action == 'create'
- name: Wait for rackconnect and managed cloud automation to completehosts: new_webgather_facts: falsetasks:- name: Wait for rackconnnect automation to complete
local_action:module: rax_factscredentials: ~/.raxpubid: "{{ rax_id }}"region: DFW
register: rax_factsuntil: rax_facts.ansible_facts['rax_metadata']['rackconnect_automation_status
→˓']|default('') == 'DEPLOYED'retries: 30delay: 10
- name: Wait for managed cloud automation to completelocal_action:
module: rax_factscredentials: ~/.raxpubid: "{{ rax_id }}"region: DFW
register: rax_factsuntil: rax_facts.ansible_facts['rax_metadata']['rax_service_level_automation
→˓']|default('') == 'Complete'retries: 30delay: 10
- name: Base Configure Servershosts: webroles:- role: users
- role: opensshopensshd_PermitRootLogin: "no"
- role: ntp
768 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Using Ansible Pull
---- name: Ensure Rackconnect and Managed Cloud Automation is complete
hosts: allconnection: localtasks:- name: Check for completed bootstrap
stat:path: /etc/bootstrap_complete
register: bootstrap
- name: Get regioncommand: xenstore-read vm-data/provider_data/regionregister: rax_regionwhen: bootstrap.stat.exists != True
- name: Wait for rackconnect automation to completeuri:
url: "https://{{ rax_region.stdout|trim }}.api.rackconnect.rackspace.com/v1/→˓automation_status?format=json"
return_content: yesregister: automation_statuswhen: bootstrap.stat.exists != Trueuntil: automation_status['automation_status']|default('') == 'DEPLOYED'retries: 30delay: 10
- name: Wait for managed cloud automation to completewait_for:
path: /tmp/rs_managed_cloud_automation_completedelay: 10
when: bootstrap.stat.exists != True
- name: Set bootstrap completedfile:
path: /etc/bootstrap_completestate: touchowner: rootgroup: rootmode: 0400
- name: Base Configure Servershosts: allconnection: localroles:- role: users
- role: opensshopensshd_PermitRootLogin: "no"
- role: ntp
1.7. Detailed Guides 769
Ansible 1.2 Documentation, Release 0.01
Using Ansible Pull with XenStore
---- name: Ensure Rackconnect and Managed Cloud Automation is complete
hosts: allconnection: localtasks:- name: Check for completed bootstrap
stat:path: /etc/bootstrap_complete
register: bootstrap
- name: Wait for rackconnect_automation_status xenstore key to existcommand: xenstore-exists vm-data/user-metadata/rackconnect_automation_statusregister: rcas_existswhen: bootstrap.stat.exists != Truefailed_when: rcas_exists.rc|int > 1until: rcas_exists.rc|int == 0retries: 30delay: 10
- name: Wait for rackconnect automation to completecommand: xenstore-read vm-data/user-metadata/rackconnect_automation_statusregister: rcaswhen: bootstrap.stat.exists != Trueuntil: rcas.stdout|replace('"', '') == 'DEPLOYED'retries: 30delay: 10
- name: Wait for rax_service_level_automation xenstore key to existcommand: xenstore-exists vm-data/user-metadata/rax_service_level_automationregister: rsla_existswhen: bootstrap.stat.exists != Truefailed_when: rsla_exists.rc|int > 1until: rsla_exists.rc|int == 0retries: 30delay: 10
- name: Wait for managed cloud automation to completecommand: xenstore-read vm-data/user-metadata/rackconnect_automation_statusregister: rslawhen: bootstrap.stat.exists != Trueuntil: rsla.stdout|replace('"', '') == 'DEPLOYED'retries: 30delay: 10
- name: Set bootstrap completedfile:
path: /etc/bootstrap_completestate: touchowner: rootgroup: rootmode: 0400
- name: Base Configure Servershosts: allconnection: localroles:
770 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- role: users
- role: opensshopensshd_PermitRootLogin: "no"
- role: ntp
Advanced Usage
Autoscaling with Tower
Ansible Tower also contains a very nice feature for auto-scaling use cases. In this mode, a simple curl script can call adefined URL and the server will “dial out” to the requester and configure an instance that is spinning up. This can bea great way to reconfigure ephemeral nodes. See the Tower documentation for more details.
A benefit of using the callback in Tower over pull mode is that job results are still centrally recorded and less informa-tion has to be shared with remote hosts.
Orchestration in the Rackspace Cloud
Ansible is a powerful orchestration tool, and rax modules allow you the opportunity to orchestrate complex tasks,deployments, and configurations. The key here is to automate provisioning of infrastructure, like any other pieceof software in an environment. Complex deployments might have previously required manual manipulation of loadbalancers, or manual provisioning of servers. Utilizing the rax modules included with Ansible, one can make thedeployment of additional nodes contingent on the current number of running nodes, or the configuration of a clusteredapplication dependent on the number of nodes with common metadata. One could automate the following scenarios,for example:
• Servers that are removed from a Cloud Load Balancer one-by-one, updated, verified, and returned to the loadbalancer pool
• Expansion of an already-online environment, where nodes are provisioned, bootstrapped, configured, and soft-ware installed
• A procedure where app log files are uploaded to a central location, like Cloud Files, before a node is decommis-sioned
• Servers and load balancers that have DNS records created and destroyed on creation and decommissioning,respectively
Google Cloud Platform Guide
Introduction
Note: This section of the documentation is under construction. We are in the process of adding more examples aboutall of the GCE modules and how they work together. Upgrades via github pull requests are welcomed!
Ansible contains modules for managing Google Compute Engine resources, including creating instances, controllingnetwork access, working with persistent disks, and managing load balancers. Additionally, there is an inventory pluginthat can automatically suck down all of your GCE instances into Ansible dynamic inventory, and create groups by tagand other properties.
1.7. Detailed Guides 771
Ansible 1.2 Documentation, Release 0.01
The GCE modules all require the apache-libcloud module, which you can install from pip:
$ pip install apache-libcloud
Note: If you’re using Ansible on Mac OS X, libcloud also needs to access a CA cert chain. You’ll need to downloadone (you can get one for here.)
Credentials
To work with the GCE modules, you’ll first need to get some credentials. You can create new one from the consoleby going to the “APIs and Auth” section and choosing to create a new client ID for a service account. Once you’vecreated a new client ID and downloaded (you must click Generate new P12 Key) the generated private key (in thepkcs12 format), you’ll need to convert the key by running the following command:
$ openssl pkcs12 -in pkey.pkcs12 -passin pass:notasecret -nodes -nocerts | openssl→˓rsa -out pkey.pem
There are two different ways to provide credentials to Ansible so that it can talk with Google Cloud for provisioningand configuration actions:
• by providing to the modules directly
• by populating a secrets.py file
Calling Modules By Passing Credentials
For the GCE modules you can specify the credentials as arguments:
• service_account_email: email associated with the project
• pem_file: path to the pem file
• project_id: id of the project
For example, to create a new instance using the cloud module, you can use the following configuration:
- name: Create instance(s)hosts: localhostconnection: localgather_facts: no
vars:service_account_email: [email protected]_file: /path/to/project.pemproject_id: project-idmachine_type: n1-standard-1image: debian-7
tasks:
- name: Launch instancesgce:
instance_names: devmachine_type: "{{ machine_type }}"image: "{{ image }}"service_account_email: "{{ service_account_email }}"
772 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
pem_file: "{{ pem_file }}"project_id: "{{ project_id }}"
Calling Modules with secrets.py
Create a file secrets.py looking like following, and put it in some folder which is in your $PYTHONPATH:
GCE_PARAMS = ('[email protected]', '/path/to/project.pem')GCE_KEYWORD_PARAMS = {'project': 'project_id'}
Ensure to enter the email address from the created services account and not the one from your main account.
Now the modules can be used as above, but the account information can be omitted.
GCE Dynamic Inventory
The best way to interact with your hosts is to use the gce inventory plugin, which dynamically queries GCE and tellsAnsible what nodes can be managed.
Note that when using the inventory script gce.py, you also need to populate the gce.ini file that you can find inthe contrib/inventory directory of the ansible checkout.
To use the GCE dynamic inventory script, copy gce.py from contrib/inventory into your inventory directoryand make it executable. You can specify credentials for gce.py using the GCE_INI_PATH environment variable –the default is to look for gce.ini in the same directory as the inventory script.
Let’s see if inventory is working:
$ ./gce.py --list
You should see output describing the hosts you have, if any, running in Google Compute Engine.
Now let’s see if we can use the inventory script to talk to Google.
$ GCE_INI_PATH=~/.gce.ini ansible all -i gce.py -m setuphostname | success >> {
"ansible_facts": {"ansible_all_ipv4_addresses": [
"x.x.x.x"],
As with all dynamic inventory scripts in Ansible, you can configure the inventory path in ansible.cfg. The recom-mended way to use the inventory is to create an inventory directory, and place both the gce.py script and a filecontaining localhost in it. This can allow for cloud inventory to be used alongside local inventory (such as aphysical datacenter) or machines running in different providers.
Executing ansible or ansible-playbook and specifying the inventory directory instead of an individualfile will cause ansible to evaluate each file in that directory for inventory.
Let’s once again use our inventory script to see if it can talk to Google Cloud:
$ ansible all -i inventory/ -m setuphostname | success >> {
"ansible_facts": {"ansible_all_ipv4_addresses": [
"x.x.x.x"],
1.7. Detailed Guides 773
Ansible 1.2 Documentation, Release 0.01
The output should be similar to the previous command. If you’re wanting less output and just want to check for SSHconnectivity, use “-m” ping instead.
Use Cases
For the following use case, let’s use this small shell script as a wrapper.
#!/usr/bin/env bashPLAYBOOK="$1"
if [[ -z $PLAYBOOK ]]; thenecho "You need to pass a playbook as argument to this script."exit 1
fi
export SSL_CERT_FILE=$(pwd)/cacert.cerexport ANSIBLE_HOST_KEY_CHECKING=False
if [[ ! -f "$SSL_CERT_FILE" ]]; thencurl -O http://curl.haxx.se/ca/cacert.pem
fi
ansible-playbook -v -i inventory/ "$PLAYBOOK"
Create an instance
The GCE module provides the ability to provision instances within Google Compute Engine. The provisioning task istypically performed from your Ansible control server against Google Cloud’s API.
A playbook would looks like this:
- name: Create instance(s)hosts: localhostgather_facts: noconnection: local
vars:machine_type: n1-standard-1 # defaultimage: debian-7service_account_email: [email protected]_file: /path/to/project.pemproject_id: project-id
tasks:- name: Launch instances
gce:instance_names: devmachine_type: "{{ machine_type }}"image: "{{ image }}"service_account_email: "{{ service_account_email }}"pem_file: "{{ pem_file }}"project_id: "{{ project_id }}"tags: webserver
register: gce
- name: Wait for SSH to come up
774 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
wait_for: host={{ item.public_ip }} port=22 delay=10 timeout=60with_items: gce.instance_data
- name: Add host to groupnameadd_host: hostname={{ item.public_ip }} groupname=new_instanceswith_items: gce.instance_data
- name: Manage new instanceshosts: new_instancesconnection: sshsudo: Trueroles:- base_configuration- production_server
Note that use of the “add_host” module above creates a temporary, in-memory group. This means that a play inthe same playbook can then manage machines in the ‘new_instances’ group, if so desired. Any sort of arbitraryconfiguration is possible at this point.
Configuring instances in a group
All of the created instances in GCE are grouped by tag. Since this is a cloud, it’s probably best to ignore hostnamesand just focus on group management.
Normally we’d also use roles here, but the following example is a simple one. Here we will also use the “gce_net”module to open up access to port 80 on these nodes.
The variables in the ‘vars’ section could also be kept in a ‘vars_files’ file or something encrypted with Ansible-vault,if you so choose. This is just a basic example of what is possible:
- name: Setup web servershosts: tag_webservergather_facts: no
vars:machine_type: n1-standard-1 # defaultimage: debian-7service_account_email: [email protected]_file: /path/to/project.pemproject_id: project-id
roles:
- name: Install lighttpdapt: pkg=lighttpd state=installedsudo: True
- name: Allow HTTPlocal_action: gce_netargs:
fwname: "all-http"name: "default"allowed: "tcp:80"state: "present"service_account_email: "{{ service_account_email }}"pem_file: "{{ pem_file }}"project_id: "{{ project_id }}"
1.7. Detailed Guides 775
Ansible 1.2 Documentation, Release 0.01
By pointing your browser to the IP of the server, you should see a page welcoming you.
Upgrades to this documentation are welcome, hit the github link at the top right of this page if you would like to makeadditions!
CloudStack Cloud Guide
Introduction
The purpose of this section is to explain how to put Ansible modules together to use Ansible in a CloudStack context.You will find more usage examples in the details section of each module.
Ansible contains a number of extra modules for interacting with CloudStack based clouds. All modules support checkmode and are designed to use idempotence and have been created, tested and are maintained by the community.
Note: Some of the modules will require domain admin or root admin privileges.
Prerequisites
Prerequisites for using the CloudStack modules are minimal. In addition to ansible itself, all of the modules requirethe python library cs https://pypi.python.org/pypi/cs.
You’ll need this Python module installed on the execution host, usually your workstation.
$ pip install cs
Note: cs also includes a command line interface for ad-hoc interaction with the CloudStack API e.g. $ cslistVirtualMachines state=Running.
Credentials File
You can pass credentials and the endpoint of your cloud as module arguments, however in most cases it is a far lesswork to store your credentials in the cloudstack.ini file.
The python library cs looks for the credentials file in the following order (last one wins):
• A .cloudstack.ini (note the dot) file in the home directory.
• A CLOUDSTACK_CONFIG environment variable pointing to an .ini file.
• A cloudstack.ini (without the dot) file in the current working directory, same directory as your playbooksare located.
The structure of the ini file must look like this:
$ cat $HOME/.cloudstack.ini[cloudstack]endpoint = https://cloud.example.com/client/apikey = api keysecret = api secret
776 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Note: The section [cloudstack] is the default section. CLOUDSTACK_REGION environment variable can beused to define the default section.
Regions
If you use more than one CloudStack region, you can define as many sections as you want and name them as you like,e.g.:
$ cat $HOME/.cloudstack.ini[exoscale]endpoint = https://api.exoscale.ch/computekey = api keysecret = api secret
[exmaple_cloud_one]endpoint = https://cloud-one.example.com/client/apikey = api keysecret = api secret
[exmaple_cloud_two]endpoint = https://cloud-two.example.com/client/apikey = api keysecret = api secret
Hint: Sections can also be used to for login into the same region using different accounts.
By passing the argument api_region with the CloudStack modules, the region wanted will be selected.
- name: ensure my ssh public key exists on Exoscalelocal_action: cs_sshkeypairname: my-ssh-keypublic_key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"api_region: exoscale
Or by looping over a regions list if you want to do the task in every region:
- name: ensure my ssh public key exists in all CloudStack regionslocal_action: cs_sshkeypairname: my-ssh-keypublic_key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"api_region: "{{ item }}"with_items:
- exoscale- exmaple_cloud_one- exmaple_cloud_two
Use Cases
The following should give you some ideas how to use the modules to provision VMs to the cloud. As always, thereisn’t only one way to do it. But as always: keep it simple for the beginning is always a good start.
1.7. Detailed Guides 777
Ansible 1.2 Documentation, Release 0.01
Use Case: Provisioning in a Advanced Networking CloudStack setup
Our CloudStack cloud has an advanced networking setup, we would like to provision web servers, which get a staticNAT and open firewall ports 80 and 443. Further we provision database servers, to which we do not give any accessto. For accessing the VMs by SSH we use a SSH jump host.
This is how our inventory looks like:
[cloud-vm:children]webserverdb-serverjumphost
[webserver]web-01.example.com public_ip=1.2.3.4web-02.example.com public_ip=1.2.3.5
[db-server]db-01.example.comdb-02.example.com
[jumphost]jump.example.com public_ip=1.2.3.6
As you can see, the public IPs for our web servers and jumphost has been assigned as variable public_ip directlyin the inventory.
The configure the jumphost, web servers and database servers, we use group_vars. The group_vars directorycontains 4 files for configuration of the groups: cloud-vm, jumphost, webserver and db-server. The cloud-vm is therefor specifing the defaults of our cloud infrastructure.
# file: group_vars/cloud-vm---cs_offering: Smallcs_firewall: []
Our database servers should get more CPU and RAM, so we define to use a Large offering for them.
# file: group_vars/db-server---cs_offering: Large
The web servers should get a Small offering as we would scale them horizontally, which is also our default offering.We also ensure the known web ports are opened for the world.
# file: group_vars/webserver---cs_firewall:
- { port: 80 }- { port: 443 }
Further we provision a jump host which has only port 22 opened for accessing the VMs from our office IPv4 network.
# file: group_vars/jumphost---cs_firewall:
- { port: 22, cidr: "17.17.17.0/24" }
778 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Now to the fun part. We create a playbook to create our infrastructure we call it infra.yml:
# file: infra.yaml---- name: provision our VMs
hosts: cloud-vmconnection: localtasks:- name: ensure VMs are created and running
cs_instance:name: "{{ inventory_hostname_short }}"template: Linux Debian 7 64-bit 20GB Diskservice_offering: "{{ cs_offering }}"state: running
- name: ensure firewall ports openedcs_firewall:
ip_address: "{{ public_ip }}"port: "{{ item.port }}"cidr: "{{ item.cidr | default('0.0.0.0/0') }}"
with_items: cs_firewallwhen: public_ip is defined
- name: ensure static NATscs_staticnat: vm="{{ inventory_hostname_short }}" ip_address="{{ public_ip }}"when: public_ip is defined
In the above play we defined 3 tasks and use the group cloud-vm as target to handle all VMs in the cloud but insteadSSH to these VMs, we use connetion=local to execute the API calls locally from our workstation.
In the first task, we ensure we have a running VM created with the Debian template. If the VM is already created butstopped, it would just start it. If you like to change the offering on an exisiting VM, you must add force: yes tothe task, which would stop the VM, change the offering and start the VM again.
In the second task we ensure the ports are opened if we give a public IP to the VM.
In the third task we add static NAT to the VMs having a public IP defined.
Note: The public IP addresses must have been acquired in advance, also see cs_ip_address
Note: For some modules, e.g. cs_sshkeypair you usually want this to be executed only once, not for every VM.Therefore you would make a separate play for it targeting localhost. You find an example in the use cases below.
Use Case: Provisioning on a Basic Networking CloudStack setup
A basic networking CloudStack setup is slightly different: Every VM gets a public IP directly assigned and securitygroups are used for access restriction policy.
This is how our inventory looks like:
[cloud-vm:children]webserver
[webserver]
1.7. Detailed Guides 779
Ansible 1.2 Documentation, Release 0.01
web-01.example.comweb-02.example.com
The default for your VMs looks like this:
# file: group_vars/cloud-vm---cs_offering: Smallcs_securitygroups: [ 'default']
Our webserver will also be in security group web:
# file: group_vars/webserver---cs_securitygroups: [ 'default', 'web' ]
The playbook looks like the following:
# file: infra.yaml---- name: cloud base setup
hosts: localhostconnection: localtasks:- name: upload ssh public keycs_sshkeypair:
name: defaultkeypublic_key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"
- name: ensure security groups existcs_securitygroup:
name: "{{ item }}"with_items:
- default- web
- name: add inbound SSH to security group defaultcs_securitygroup_rule:
security_group: defaultstart_port: "{{ item }}"end_port: "{{ item }}"
with_items:- 22
- name: add inbound TCP rules to security group webcs_securitygroup_rule:
security_group: webstart_port: "{{ item }}"end_port: "{{ item }}"
with_items:- 80- 443
- name: install VMs in the cloudhosts: cloud-vmconnection: localtasks:- name: create and run VMs on CloudStack
780 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
cs_instance:name: "{{ inventory_hostname_short }}"template: Linux Debian 7 64-bit 20GB Diskservice_offering: "{{ cs_offering }}"security_groups: "{{ cs_securitygroups }}"ssh_key: defaultkeystate: Running
register: vm
- name: show VM IPdebug: msg="VM {{ inventory_hostname }} {{ vm.default_ip }}"
- name: assing IP to the inventoryset_fact: ansible_ssh_host={{ vm.default_ip }}
- name: waiting for SSH to come upwait_for: port=22 host={{ vm.default_ip }} delay=5
In the first play we setup the security groups, in the second play the VMs will created be assigned to these groups.Further you see, that we assign the public IP returned from the modules to the host inventory. This is needed as wedo not know the IPs we will get in advance. In a next step you would configure the DNS servers with these IPs foraccassing the VMs with their DNS name.
In the last task we wait for SSH to be accessible, so any later play would be able to access the VM by SSH withoutfailure.
Using Vagrant and Ansible
Introduction
Vagrant is a tool to manage virtual machine environments, and allows you to configure and use reproducible workenvironments on top of various virtualization and cloud platforms. It also has integration with Ansible as a provisionerfor these virtual machines, and the two tools work together well.
This guide will describe how to use Vagrant 1.7+ and Ansible together.
If you’re not familiar with Vagrant, you should visit the documentation.
This guide assumes that you already have Ansible installed and working. Running from a Git checkout is fine. Followthe Installation guide for more information.
Vagrant Setup
The first step once you’ve installed Vagrant is to create a Vagrantfile and customize it to suit your needs. This iscovered in detail in the Vagrant documentation, but here is a quick example that includes a section to use the Ansibleprovisioner to manage a single machine:
# This guide is optimized for Vagrant 1.7 and above.# Although versions 1.6.x should behave very similarly, it is recommended# to upgrade instead of disabling the requirement below.Vagrant.require_version ">= 1.7.0"
Vagrant.configure(2) do |config|
config.vm.box = "ubuntu/trusty64"
1.7. Detailed Guides 781
Ansible 1.2 Documentation, Release 0.01
# Disable the new default behavior introduced in Vagrant 1.7, to# ensure that all Vagrant machines will use the same SSH key pair.# See https://github.com/mitchellh/vagrant/issues/5005config.ssh.insert_key = false
config.vm.provision "ansible" do |ansible|ansible.verbose = "v"ansible.playbook = "playbook.yml"
endend
Notice the config.vm.provision section that refers to an Ansible playbook called playbook.yml in the samedirectory as the Vagrantfile. Vagrant runs the provisioner once the virtual machine has booted and is ready forSSH access.
There are a lot of Ansible options you can configure in your Vagrantfile. Visit the Ansible Provisioner documen-tation for more information.
$ vagrant up
This will start the VM, and run the provisioning playbook (on the first VM startup).
To re-run a playbook on an existing VM, just run:
$ vagrant provision
This will re-run the playbook against the existing VM.
Note that having the ansible.verbose option enabled will instruct Vagrant to show the fullansible-playbook command used behind the scene, as illustrated by this example:
$ PYTHONUNBUFFERED=1 ANSIBLE_FORCE_COLOR=true ANSIBLE_HOST_KEY_CHECKING=false ANSIBLE_→˓SSH_ARGS='-o UserKnownHostsFile=/dev/null -o ControlMaster=auto -o→˓ControlPersist=60s' ansible-playbook --private-key=/home/someone/.vagrant.d/→˓insecure_private_key --user=vagrant --connection=ssh --limit='machine1' --inventory-→˓file=/home/someone/coding-in-a-project/.vagrant/provisioners/ansible/inventory/→˓vagrant_ansible_inventory playbook.yml
This information can be quite useful to debug integration issues and can also be used to manually execute Ansiblefrom a shell, as explained in the next section.
Running Ansible Manually
Sometimes you may want to run Ansible manually against the machines. This is faster than kicking vagrantprovision and pretty easy to do.
With our Vagrantfile example, Vagrant automatically creates an Ansible inventory file in .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory. This inventory is configured ac-cording to the SSH tunnel that Vagrant automatically creates. A typical automatically-created inventory file for asingle machine environment may look something like this:
# Generated by Vagrant
default ansible_ssh_host=127.0.0.1 ansible_ssh_port=2222
If you want to run Ansible manually, you will want to make sure to pass ansible or ansible-playbook com-mands the correct arguments, at least for the username, the SSH private key and the inventory.
782 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Here is an example using the Vagrant global insecure key (config.ssh.insert_key must be set to false inyour Vagrantfile):
$ ansible-playbook --private-key=~/.vagrant.d/insecure_private_key -u vagrant -i .→˓vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory playbook.yml
Here is a second example using the random private key that Vagrant 1.7+ automatically configures for each new VM(each key is stored in a path like .vagrant/machines/[machine name]/[provider]/private_key):
$ ansible-playbook --private-key=.vagrant/machines/default/virtualbox/private_key -u→˓vagrant -i .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory→˓playbook.yml
Advanced Usages
The “Tips and Tricks” chapter of the Ansible Provisioner documentation provides detailed information about moreadvanced Ansible features like:
• how to parallely execute a playbook in a multi-machine environment
• how to integrate a local ansible.cfg configuration file
See also:
Vagrant Home The Vagrant homepage with downloads
Vagrant Documentation Vagrant Documentation
Ansible Provisioner The Vagrant documentation for the Ansible provisioner
Vagrant Issue Tracker The open issues for the Ansible provisioner in the Vagrant project
Playbooks An introduction to playbooks
Continuous Delivery and Rolling Upgrades
Introduction
Continuous Delivery is the concept of frequently delivering updates to your software application.
The idea is that by updating more often, you do not have to wait for a specific timed period, and your organization getsbetter at the process of responding to change.
Some Ansible users are deploying updates to their end users on an hourly or even more frequent basis – sometimesevery time there is an approved code change. To achieve this, you need tools to be able to quickly apply those updatesin a zero-downtime way.
This document describes in detail how to achieve this goal, using one of Ansible’s most complete example playbooksas a template: lamp_haproxy. This example uses a lot of Ansible features: roles, templates, and group variables, andit also comes with an orchestration playbook that can do zero-downtime rolling upgrades of the web application stack.
Note: Click here for the latest playbooks for this example.
The playbooks deploy Apache, PHP, MySQL, Nagios, and HAProxy to a CentOS-based set of servers.
We’re not going to cover how to run these playbooks here. Read the included README in the github project alongwith the example for that information. Instead, we’re going to take a close look at every part of the playbook anddescribe what it does.
1.7. Detailed Guides 783
Ansible 1.2 Documentation, Release 0.01
Site Deployment
Let’s start with site.yml. This is our site-wide deployment playbook. It can be used to initially deploy the site, aswell as push updates to all of the servers:
---# This playbook deploys the whole application stack in this site.
# Apply common configuration to all hosts- hosts: all
roles:- common
# Configure and deploy database servers.- hosts: dbservers
roles:- db
# Configure and deploy the web servers. Note that we include two roles# here, the 'base-apache' role which simply sets up Apache, and 'web'# which includes our example web application.
- hosts: webservers
roles:- base-apache- web
# Configure and deploy the load balancer(s).- hosts: lbservers
roles:- haproxy
# Configure and deploy the Nagios monitoring node(s).- hosts: monitoring
roles:- base-apache- nagios
Note: If you’re not familiar with terms like playbooks and plays, you should review Playbooks.
In this playbook we have 5 plays. The first one targets all hosts and applies the common role to all of the hosts. Thisis for site-wide things like yum repository configuration, firewall configuration, and anything else that needs to applyto all of the servers.
The next four plays run against specific host groups and apply specific roles to those servers. Along with the roles forNagios monitoring, the database, and the web application, we’ve implemented a base-apache role that installs andconfigures a basic Apache setup. This is used by both the sample web application and the Nagios hosts.
784 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Reusable Content: Roles
By now you should have a bit of understanding about roles and how they work in Ansible. Roles are a way to organizecontent: tasks, handlers, templates, and files, into reusable components.
This example has six roles: common, base-apache, db, haproxy, nagios, and web. How you organize yourroles is up to you and your application, but most sites will have one or more common roles that are applied to allsystems, and then a series of application-specific roles that install and configure particular parts of the site.
Roles can have variables and dependencies, and you can pass in parameters to roles to modify their behavior. You canread more about roles in the Playbook Roles and Include Statements section.
Configuration: Group Variables
Group variables are variables that are applied to groups of servers. They can be used in templates and in playbooksto customize behavior and to provide easily-changed settings and parameters. They are stored in a directory calledgroup_vars in the same location as your inventory. Here is lamp_haproxy’s group_vars/all file. As youmight expect, these variables are applied to all of the machines in your inventory:
---httpd_port: 80ntpserver: 192.168.1.2
This is a YAML file, and you can create lists and dictionaries for more complex variable structures. In this case, weare just setting two variables, one for the port for the web server, and one for the NTP server that our machines shoulduse for time synchronization.
Here’s another group variables file. This is group_vars/dbservers which applies to the hosts in thedbservers group:
---mysqlservice: mysqldmysql_port: 3306dbuser: rootdbname: foodbupassword: usersecret
If you look in the example, there are group variables for the webservers group and the lbservers group, simi-larly.
These variables are used in a variety of places. You can use them in playbooks, like this, in roles/db/tasks/main.yml:
- name: Create Application Databasemysql_db: name={{ dbname }} state=present
- name: Create Application DB Usermysql_user: name={{ dbuser }} password={{ upassword }}
priv=*.*:ALL host='%' state=present
You can also use these variables in templates, like this, in roles/common/templates/ntp.conf.j2:
driftfile /var/lib/ntp/drift
restrict 127.0.0.1restrict -6 ::1
1.7. Detailed Guides 785
Ansible 1.2 Documentation, Release 0.01
server {{ ntpserver }}
includefile /etc/ntp/crypto/pw
keys /etc/ntp/keys
You can see that the variable substitution syntax of {{ and }} is the same for both templates and variables. Thesyntax inside the curly braces is Jinja2, and you can do all sorts of operations and apply different filters to the datainside. In templates, you can also use for loops and if statements to handle more complex situations, like this, inroles/common/templates/iptables.j2:
{% if inventory_hostname in groups['dbservers'] %}-A INPUT -p tcp --dport 3306 -j ACCEPT{% endif %}
This is testing to see if the inventory name of the machine we’re currently operating on (inventory_hostname)exists in the inventory group dbservers. If so, that machine will get an iptables ACCEPT line for port 3306.
Here’s another example, from the same template:
{% for host in groups['monitoring'] %}-A INPUT -p tcp -s {{ hostvars[host].ansible_default_ipv4.address }} --dport 5666 -j→˓ACCEPT{% endfor %}
This loops over all of the hosts in the group called monitoring, and adds an ACCEPT line for each monitoringhosts’ default IPV4 address to the current machine’s iptables configuration, so that Nagios can monitor those hosts.
You can learn a lot more about Jinja2 and its capabilities here, and you can read more about Ansible variables ingeneral in the Variables section.
The Rolling Upgrade
Now you have a fully-deployed site with web servers, a load balancer, and monitoring. How do you update it? This iswhere Ansible’s orchestration features come into play. While some applications use the term ‘orchestration’ to meanbasic ordering or command-blasting, Ansible refers to orchestration as ‘conducting machines like an orchestra’, andhas a pretty sophisticated engine for it.
Ansible has the capability to do operations on multi-tier applications in a coordinated way, making it easy to orchestratea sophisticated zero-downtime rolling upgrade of our web application. This is implemented in a separate playbook,called rolling_upgrade.yml.
Looking at the playbook, you can see it is made up of two plays. The first play is very simple and looks like this:
- hosts: monitoringtasks: []
What’s going on here, and why are there no tasks? You might know that Ansible gathers “facts” from the serversbefore operating upon them. These facts are useful for all sorts of things: networking information, OS/distributionversions, etc. In our case, we need to know something about all of the monitoring servers in our environment beforewe perform the update, so this simple play forces a fact-gathering step on our monitoring servers. You will see thispattern sometimes, and it’s a useful trick to know.
The next part is the update play. The first part looks like this:
786 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- hosts: webserversuser: rootserial: 1
This is just a normal play definition, operating on the webservers group. The serial keyword tells Ansible howmany servers to operate on at once. If it’s not specified, Ansible will parallelize these operations up to the default“forks” limit specified in the configuration file. But for a zero-downtime rolling upgrade, you may not want to operateon that many hosts at once. If you had just a handful of webservers, you may want to set serial to 1, for one host ata time. If you have 100, maybe you could set serial to 10, for ten at a time.
Here is the next part of the update play:
pre_tasks:- name: disable nagios alerts for this host webserver service
nagios: action=disable_alerts host={{ inventory_hostname }} services=webserverdelegate_to: "{{ item }}"with_items: groups.monitoring
- name: disable the server in haproxyshell: echo "disable server myapplb/{{ inventory_hostname }}" | socat stdio /var/
→˓lib/haproxy/statsdelegate_to: "{{ item }}"with_items: groups.lbservers
The pre_tasks keyword just lets you list tasks to run before the roles are called. This will make more sense in aminute. If you look at the names of these tasks, you can see that we are disabling Nagios alerts and then removing thewebserver that we are currently updating from the HAProxy load balancing pool.
The delegate_to and with_items arguments, used together, cause Ansible to loop over each monitoring serverand load balancer, and perform that operation (delegate that operation) on the monitoring or load balancing server, “onbehalf” of the webserver. In programming terms, the outer loop is the list of web servers, and the inner loop is the listof monitoring servers.
Note that the HAProxy step looks a little complicated. We’re using HAProxy in this example because it’s freelyavailable, though if you have (for instance) an F5 or Netscaler in your infrastructure (or maybe you have an AWSElastic IP setup?), you can use modules included in core Ansible to communicate with them instead. You might alsowish to use other monitoring modules instead of nagios, but this just shows the main goal of the ‘pre tasks’ section –take the server out of monitoring, and take it out of rotation.
The next step simply re-applies the proper roles to the web servers. This will cause any configuration managementdeclarations in web and base-apache roles to be applied to the web servers, including an update of the webapplication code itself. We don’t have to do it this way–we could instead just purely update the web application, butthis is a good example of how roles can be used to reuse tasks:
roles:- common- base-apache- web
Finally, in the post_tasks section, we reverse the changes to the Nagios configuration and put the web server backin the load balancing pool:
post_tasks:- name: Enable the server in haproxy
shell: echo "enable server myapplb/{{ inventory_hostname }}" | socat stdio /var/lib/→˓haproxy/statsdelegate_to: "{{ item }}"with_items: groups.lbservers
1.7. Detailed Guides 787
Ansible 1.2 Documentation, Release 0.01
- name: re-enable nagios alertsnagios: action=enable_alerts host={{ inventory_hostname }} services=webserverdelegate_to: "{{ item }}"with_items: groups.monitoring
Again, if you were using a Netscaler or F5 or Elastic Load Balancer, you would just substitute in the appropriatemodules instead.
Managing Other Load Balancers
In this example, we use the simple HAProxy load balancer to front-end the web servers. It’s easy to configure andeasy to manage. As we have mentioned, Ansible has built-in support for a variety of other load balancers like CitrixNetScaler, F5 BigIP, Amazon Elastic Load Balancers, and more. See the About Modules documentation for moreinformation.
For other load balancers, you may need to send shell commands to them (like we do for HAProxy above), or call anAPI, if your load balancer exposes one. For the load balancers for which Ansible has modules, you may want to runthem as a local_action if they contact an API. You can read more about local actions in the Delegation, RollingUpdates, and Local Actions section. Should you develop anything interesting for some hardware where there is not acore module, it might make for a good module for core inclusion!
Continuous Delivery End-To-End
Now that you have an automated way to deploy updates to your application, how do you tie it all together? A lot oforganizations use a continuous integration tool like Jenkins or Atlassian Bamboo to tie the development, test, release,and deploy steps together. You may also want to use a tool like Gerrit to add a code review step to commits to eitherthe application code itself, or to your Ansible playbooks, or both.
Depending on your environment, you might be deploying continuously to a test environment, running an integrationtest battery against that environment, and then deploying automatically into production. Or you could keep it simpleand just use the rolling-update for on-demand deployment into test or production specifically. This is all up to you.
For integration with Continuous Integration systems, you can easily trigger playbook runs using theansible-playbook command line tool, or, if you’re using Ansible Tower, the tower-cli or the built-in RESTAPI. (The tower-cli command ‘joblaunch’ will spawn a remote job over the REST API and is pretty slick).
This should give you a good idea of how to structure a multi-tier application with Ansible, and orchestrate operationsupon that app, with the eventual goal of continuous delivery to your customers. You could extend the idea of therolling upgrade to lots of different parts of the app; maybe add front-end web servers along with application servers,for instance, or replace the SQL database with something like MongoDB or Riak. Ansible gives you the capability toeasily manage complicated environments and automate common operations.
See also:
lamp_haproxy example The lamp_haproxy example discussed here.
Playbooks An introduction to playbooks
Playbook Roles and Include Statements An introduction to playbook roles
Variables An introduction to Ansible variables
Ansible.com: Continuous Delivery An introduction to Continuous Delivery with Ansible
Pending topics may include: Docker, Jenkins, Google Compute Engine, Linode/DigitalOcean, Continuous Deploy-ment, and more.
788 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Developer Information
Learn how to build modules of your own in any language, and also how to extend Ansible through several kinds ofplugins. Explore Ansible’s Python API and write Python plugins to integrate with other solutions in your environment.
Python API
Topics
• Python API
– Python API 2.0
– Python API pre 2.0
* Detailed API Example
There are several interesting ways to use Ansible from an API perspective. You can use the Ansible python API tocontrol nodes, you can extend Ansible to respond to various python events, you can write various plugins, and youcan plug in inventory data from external data sources. This document covers the Runner and Playbook API at a basiclevel.
If you are looking to use Ansible programmatically from something other than Python, trigger events asynchronously,or have access control and logging demands, take a look at Ansible Tower as it has a very nice REST API that providesall of these things at a higher level.
Ansible is written in its own API so you have a considerable amount of power across the board. This chapter discussesthe Python API. The Python API is very powerful, and is how the ansible CLI and ansible-playbook are implemented.In version 2.0 the core ansible got rewritten and the API was mostly rewritten.
Python API 2.0
In 2.0 things get a bit more complicated to start, but you end up with much more discrete and readable classes:
#!/usr/bin/python2
from collections import namedtuplefrom ansible.parsing.dataloader import DataLoaderfrom ansible.vars import VariableManagerfrom ansible.inventory import Inventoryfrom ansible.playbook.play import Playfrom ansible.executor.task_queue_manager import TaskQueueManager
Options = namedtuple('Options', ['connection','module_path', 'forks', 'remote_user',→˓'private_key_file', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args', 'scp_→˓extra_args', 'become', 'become_method', 'become_user', 'verbosity', 'check'])# initialize needed objectsvariable_manager = VariableManager()loader = DataLoader()options = Options(connection='local', module_path='/path/to/mymodules', forks=100,→˓remote_user=None, private_key_file=None, ssh_common_args=None, ssh_extra_args=None,→˓sftp_extra_args=None, scp_extra_args=None, become=None, become_method=None, become_→˓user=None, verbosity=None, check=False)passwords = dict(vault_pass='secret')
1.8. Developer Information 789
Ansible 1.2 Documentation, Release 0.01
# create inventory and pass to var managerinventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=→˓'localhost')variable_manager.set_inventory(inventory)
# create play with tasksplay_source = dict(
name = "Ansible Play",hosts = 'localhost',gather_facts = 'no',tasks = [ dict(action=dict(module='debug', args=(msg='Hello Galaxy!'))) ]
)play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
# actually run ittqm = Nonetry:
tqm = TaskQueueManager(inventory=inventory,variable_manager=variable_manager,loader=loader,options=options,passwords=passwords,stdout_callback='default',
)result = tqm.run(play)
finally:if tqm is not None:
tqm.cleanup()
Python API pre 2.0
It’s pretty simple:
import ansible.runner
runner = ansible.runner.Runner(module_name='ping',module_args='',pattern='web*',forks=10
)datastructure = runner.run()
The run method returns results per host, grouped by whether they could be contacted or not. Return types are modulespecific, as expressed in the About Modules documentation.:
{"dark" : {
"web1.example.com" : "failure message"},"contacted" : {
"web2.example.com" : 1}
}
790 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
A module can return any type of JSON data it wants, so Ansible can be used as a framework to rapidly build powerfulapplications and scripts.
Detailed API Example
The following script prints out the uptime information for all hosts:
#!/usr/bin/python
import ansible.runnerimport sys
# construct the ansible runner and execute on all hostsresults = ansible.runner.Runner(
pattern='*', forks=10,module_name='command', module_args='/usr/bin/uptime',
).run()
if results is None:print "No hosts found"sys.exit(1)
print "UP ***********"for (hostname, result) in results['contacted'].items():
if not 'failed' in result:print "%s >>> %s" % (hostname, result['stdout'])
print "FAILED *******"for (hostname, result) in results['contacted'].items():
if 'failed' in result:print "%s >>> %s" % (hostname, result['msg'])
print "DOWN *********"for (hostname, result) in results['dark'].items():
print "%s >>> %s" % (hostname, result)
Advanced programmers may also wish to read the source to ansible itself, for it uses the API (with all availableoptions) to implement the ansible command line tools (lib/ansible/cli/).
See also:
Developing Dynamic Inventory Sources Developing dynamic inventory integrations
Developing Modules How to develop modules
Developing Plugins How to develop plugins
Development Mailing List Mailing list for development topics
irc.freenode.net #ansible IRC chat channel
Developing Dynamic Inventory Sources
Topics
• Script Conventions
1.8. Developer Information 791
Ansible 1.2 Documentation, Release 0.01
• Tuning the External Inventory Script
As described in Dynamic Inventory, ansible can pull inventory information from dynamic sources, including cloudsources.
How do we write a new one?
Simple! We just create a script or program that can return JSON in the right format when fed the proper arguments.You can do this in any language.
Script Conventions
When the external node script is called with the single argument --list, the script must return a JSONhash/dictionary of all the groups to be managed. Each group’s value should be either a hash/dictionary containinga list of each host/IP, potential child groups, and potential group variables, or simply a list of host/IP addresses, likeso:
{"databases" : {
"hosts" : [ "host1.example.com", "host2.example.com" ],"vars" : {
"a" : true}
},"webservers" : [ "host2.example.com", "host3.example.com" ],"atlanta" : {
"hosts" : [ "host1.example.com", "host4.example.com", "host5.example.com" ],"vars" : {
"b" : false},"children": [ "marietta", "5points" ]
},"marietta" : [ "host6.example.com" ],"5points" : [ "host7.example.com" ]
}
New in version 1.0.
Before version 1.0, each group could only have a list of hostnames/IP addresses, like the webservers, marietta, and5points groups above.
When called with the arguments --host <hostname> (where <hostname> is a host from above), the script mustreturn either an empty JSON hash/dictionary, or a hash/dictionary of variables to make available to templates andplaybooks. Returning variables is optional, if the script does not wish to do this, returning an empty hash/dictionary isthe way to go:
{"favcolor" : "red","ntpserver" : "wolf.example.com","monitoring" : "pack.example.com"
}
Tuning the External Inventory Script
New in version 1.3.
792 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
The stock inventory script system detailed above works for all versions of Ansible, but calling --host for every hostcan be rather expensive, especially if it involves expensive API calls to a remote subsystem. In Ansible 1.3 or later, ifthe inventory script returns a top level element called “_meta”, it is possible to return all of the host variables in oneinventory script call. When this meta element contains a value for “hostvars”, the inventory script will not be invokedwith --host for each host. This results in a significant performance increase for large numbers of hosts, and alsomakes client side caching easier to implement for the inventory script.
The data to be added to the top level JSON dictionary looks like this:
{
# results of inventory script as above go here# ...
"_meta" : {"hostvars" : {
"moocow.example.com" : { "asdf" : 1234 },"llama.example.com" : { "asdf" : 5678 },
}}
}
See also:
Python API Python API to Playbooks and Ad Hoc Task Execution
Developing Modules How to develop modules
Developing Plugins How to develop plugins
Ansible Tower REST API endpoint and GUI for Ansible, syncs with dynamic inventory
Development Mailing List Mailing list for development topics
irc.freenode.net #ansible IRC chat channel
Developing Modules
Topics
• Developing Modules
– Tutorial
– Testing Modules
– Reading Input
– Module Provided ‘Facts’
– Common Module Boilerplate
– Check Mode
– Common Pitfalls
– Conventions/Recommendations
– Documenting Your Module
1.8. Developer Information 793
Ansible 1.2 Documentation, Release 0.01
* Example
* Building & Testing
– Module Paths
– Getting Your Module Into Ansible
– Module checklist
– Windows modules checklist
– Deprecating and making module aliases
Ansible modules are reusable units of magic that can be used by the Ansible API, or by the ansible or ansible-playbookprograms.
See About Modules for a list of various ones developed in core.
Modules can be written in any language and are found in the path specified by ANSIBLE_LIBRARY or the--module-path command line option.
By default, everything that ships with ansible is pulled from its source tree, but additional paths can be added.
The directory ”./library”, alongside your top level playbooks, is also automatically added as a search directory.
Should you develop an interesting Ansible module, consider sending a pull request to the modules-extras project.There’s also a core repo for more established and widely used modules. “Extras” modules may be promoted to coreperiodically, but there’s no fundamental difference in the end - both ship with ansible, all in one package, regardlessof how you acquire ansible.
Tutorial
Let’s build a very-basic module to get and set the system time. For starters, let’s build a module that just outputs thecurrent time.
We are going to use Python here but any language is possible. Only File I/O and outputting to standard out are required.So, bash, C++, clojure, Python, Ruby, whatever you want is fine.
Now Python Ansible modules contain some extremely powerful shortcuts (that all the core modules use) but first weare going to build a module the very hard way. The reason we do this is because modules written in any languageOTHER than Python are going to have to do exactly this. We’ll show the easy way later.
So, here’s an example. You would never really need to build a module to set the system time, the ‘command’ modulecould already be used to do this. Though we’re going to make one.
Reading the modules that come with ansible (linked above) is a great way to learn how to write modules. Keep inmind, though, that some modules in ansible’s source tree are internalisms, so look at service or yum, and don’t staretoo close into things like async_wrapper or you’ll turn to stone. Nobody ever executes async_wrapper directly.
Ok, let’s get going with an example. We’ll use Python. For starters, save this as a file named timetest.py:
#!/usr/bin/python
import datetimeimport json
date = str(datetime.datetime.now())print json.dumps({
"time" : date})
794 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Testing Modules
There’s a useful test script in the source checkout for ansible:
git clone git://github.com/ansible/ansible.git --recursivesource ansible/hacking/env-setupchmod +x ansible/hacking/test-module
Let’s run the script you just wrote with that:
ansible/hacking/test-module -m ./timetest.py
You should see output that looks something like this:
{u'time': u'2012-03-14 22:13:48.539183'}
If you did not, you might have a typo in your module, so recheck it and try again.
Reading Input
Let’s modify the module to allow setting the current time. We’ll do this by seeing if a key value pair in the formtime=<string> is passed in to the module.
Ansible internally saves arguments to an arguments file. So we must read the file and parse it. The arguments file isjust a string, so any form of arguments are legal. Here we’ll do some basic parsing to treat the input as key=value.
The example usage we are trying to achieve to set the time is:
time time="March 14 22:10"
If no time parameter is set, we’ll just leave the time as is and return the current time.
Note: This is obviously an unrealistic idea for a module. You’d most likely just use the shell module. However, itprobably makes a decent tutorial.
Let’s look at the code. Read the comments as we’ll explain as we go. Note that this is highly verbose because it’sintended as an educational example. You can write modules a lot shorter than this:
#!/usr/bin/python
# import some python modules that we'll use. These are all# available in Python's core
import datetimeimport sysimport jsonimport osimport shlex
# read the argument string from the arguments fileargs_file = sys.argv[1]args_data = file(args_file).read()
# for this module, we're going to do key=value style arguments# this is up to each module to decide what it wants, but all# core modules besides 'command' and 'shell' take key=value
1.8. Developer Information 795
Ansible 1.2 Documentation, Release 0.01
# so this is highly recommended
arguments = shlex.split(args_data)for arg in arguments:
# ignore any arguments without an equals in itif "=" in arg:
(key, value) = arg.split("=")
# if setting the time, the key 'time'# will contain the value we want to set the time to
if key == "time":
# now we'll affect the change. Many modules# will strive to be 'idempotent', meaning they# will only make changes when the desired state# expressed to the module does not match# the current state. Look at 'service'# or 'yum' in the main git tree for an example# of how that might look.
rc = os.system("date -s \"%s\"" % value)
# always handle all possible errors## when returning a failure, include 'failed'# in the return data, and explain the failure# in 'msg'. Both of these conventions are# required however additional keys and values# can be added.
if rc != 0:print json.dumps({
"failed" : True,"msg" : "failed setting the time"
})sys.exit(1)
# when things do not fail, we do not# have any restrictions on what kinds of# data are returned, but it's always a# good idea to include whether or not# a change was made, as that will allow# notifiers to be used in playbooks.
date = str(datetime.datetime.now())print json.dumps({
"time" : date,"changed" : True
})sys.exit(0)
# if no parameters are sent, the module may or# may not error out, this one will just# return the time
796 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
date = str(datetime.datetime.now())print json.dumps({
"time" : date})
Let’s test that module:
ansible/hacking/test-module -m ./time -a "time=\"March 14 12:23\""
This should return something like:
{"changed": true, "time": "2012-03-14 12:23:00.000307"}
Module Provided ‘Facts’
The ‘setup’ module that ships with Ansible provides many variables about a system that can be used in playbooks andtemplates. However, it’s possible to also add your own facts without modifying the system module. To do this, justhave the module return a ansible_facts key, like so, along with other return data:
{"changed" : True,"rc" : 5,"ansible_facts" : {
"leptons" : 5000,"colors" : {
"red" : "FF0000","white" : "FFFFFF"
}}
}
These ‘facts’ will be available to all statements called after that module (but not before) in the playbook. A good ideamight be to make a module called ‘site_facts’ and always call it at the top of each playbook, though we’re always opento improving the selection of core facts in Ansible as well.
Common Module Boilerplate
As mentioned, if you are writing a module in Python, there are some very powerful shortcuts you can use. Modulesare still transferred as one file, but an arguments file is no longer needed, so these are not only shorter in terms of code,they are actually FASTER in terms of execution time.
Rather than mention these here, the best way to learn is to read some of the source of the modules that come withAnsible.
The ‘group’ and ‘user’ modules are reasonably non-trivial and showcase what this looks like.
Key parts include always ending the module file with:
from ansible.module_utils.basic import *if __name__ == '__main__':
main()
And instantiating the module class like:
1.8. Developer Information 797
Ansible 1.2 Documentation, Release 0.01
module = AnsibleModule(argument_spec = dict(
state = dict(default='present', choices=['present', 'absent']),name = dict(required=True),enabled = dict(required=True, choices=BOOLEANS),something = dict(aliases=['whatever'])
))
The AnsibleModule provides lots of common code for handling returns, parses your arguments for you, and allowsyou to check inputs.
Successful returns are made like this:
module.exit_json(changed=True, something_else=12345)
And failures are just as simple (where ‘msg’ is a required parameter to explain the error):
module.fail_json(msg="Something fatal happened")
There are also other useful functions in the module class, such as module.sha1(path). Seelib/ansible/module_common.py in the source checkout for implementation details.
Again, modules developed this way are best tested with the hacking/test-module script in the git source checkout.Because of the magic involved, this is really the only way the scripts can function outside of Ansible.
If submitting a module to ansible’s core code, which we encourage, use of the AnsibleModule class is required.
Check Mode
New in version 1.1.
Modules may optionally support check mode. If the user runs Ansible in check mode, the module should try to predictwhether changes will occur.
For your module to support check mode, you must pass supports_check_mode=True when instantiating theAnsibleModule object. The AnsibleModule.check_mode attribute will evaluate to True when check mode is enabled.For example:
module = AnsibleModule(argument_spec = dict(...),supports_check_mode=True
)
if module.check_mode:# Check if any changes would be made but don't actually make those changesmodule.exit_json(changed=check_if_system_state_would_be_changed())
Remember that, as module developer, you are responsible for ensuring that no system state is altered when the userenables check mode.
If your module does not support check mode, when the user runs Ansible in check mode, your module will simply beskipped.
Common Pitfalls
You should also never do this in a module:
798 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
print "some status message"
Because the output is supposed to be valid JSON.
Modules must not output anything on standard error, because the system will merge standard out with standard errorand prevent the JSON from parsing. Capturing standard error and returning it as a variable in the JSON on standardout is fine, and is, in fact, how the command module is implemented.
If a module returns stderr or otherwise fails to produce valid JSON, the actual output will still be shown in Ansible,but the command will not succeed.
Always use the hacking/test-module script when developing modules and it will warn you about these kind of things.
Conventions/Recommendations
As a reminder from the example code above, here are some basic conventions and guidelines:
• If the module is addressing an object, the parameter for that object should be called ‘name’ whenever possible,or accept ‘name’ as an alias.
• If you have a company module that returns facts specific to your installations, a good name for this module issite_facts.
• Modules accepting boolean status should generally accept ‘yes’, ‘no’, ‘true’, ‘false’, or anything else a usermay likely throw at them. The AnsibleModule common code supports this with “choices=BOOLEANS” and amodule.boolean(value) casting function.
• Include a minimum of dependencies if possible. If there are dependencies, document them at the top of themodule file, and have the module raise JSON error messages when the import fails.
• Modules must be self-contained in one file to be auto-transferred by ansible.
• If packaging modules in an RPM, they only need to be installed on the control machine and should be droppedinto /usr/share/ansible. This is entirely optional and up to you.
• Modules must output valid JSON only. The toplevel return type must be a hash (dictionary) although they can benested. Lists or simple scalar values are not supported, though they can be trivially contained inside a dictionary.
• In the event of failure, a key of ‘failed’ should be included, along with a string explanation in ‘msg’. Mod-ules that raise tracebacks (stacktraces) are generally considered ‘poor’ modules, though Ansible can deal withthese returns and will automatically convert anything unparseable into a failed result. If you are using the An-sibleModule common Python code, the ‘failed’ element will be included for you automatically when you call‘fail_json’.
• Return codes from modules are not actually not significant, but continue on with 0=success and non-zero=failurefor reasons of future proofing.
• As results from many hosts will be aggregated at once, modules should return only relevant output. Returningthe entire contents of a log file is generally bad form.
Documenting Your Module
All modules included in the CORE distribution must have a DOCUMENTATION string. This string MUST be avalid YAML document which conforms to the schema defined below. You may find it easier to start writing yourDOCUMENTATION string in an editor with YAML syntax highlighting before you include it in your Python file.
1.8. Developer Information 799
Ansible 1.2 Documentation, Release 0.01
Example
See an example documentation string in the checkout under examples/DOCUMENTATION.yml.
Include it in your module file like this:
#!/usr/bin/python# Copyright header....
DOCUMENTATION = '''---module: modulenameshort_description: This is a sentence describing the module# ... snip ...'''
The description, and notes fields support formatting with some special macros.
These formatting functions are U(), M(), I(), and C() for URL, module, italic, and constant-width respectively. Itis suggested to use C() for file and option names, and I() when referencing parameters; module names should bespecified as M(module).
Examples (which typically contain colons, quotes, etc.) are difficult to format with YAML, so these must be writtenin plain text in an EXAMPLES string within the module like this:
EXAMPLES = '''- action: modulename opt1=arg1 opt2=arg2'''
The EXAMPLES section, just like the documentation section, is required in all module pull requests for new modules.
The RETURN section documents what the module returns. For each value returned, provide a description, inwhat circumstances the value is returned, the type of the value and a sample. For example, from the copymodule:
RETURN = '''dest:
description: destination file/pathreturned: successtype: stringsample: "/path/to/file.txt"
src:description: source file used for the copy on the target machinereturned: changedtype: stringsample: "/home/httpd/.ansible/tmp/ansible-tmp-1423796390.97-147729857856000/source
→˓"md5sum:
description: md5 checksum of the file after running copyreturned: when supportedtype: stringsample: "2a5aeecc61dc98c4d780b14b330e3282"
...'''
800 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Building & Testing
Put your completed module file into the ‘library’ directory and then run the command: make webdocs. The new‘modules.html’ file will be built and appear in the ‘docsite/’ directory.
Tip: If you’re having a problem with the syntax of your YAML you can validate it on the YAML Lint website.
Tip: You can set the environment variable ANSIBLE_KEEP_REMOTE_FILES=1 on the controlling host to preventansible from deleting the remote files so you can debug your module.
Module Paths
If you are having trouble getting your module “found” by ansible, be sure it is in the ANSIBLE_LIBRARY environ-ment variable.
If you have a fork of one of the ansible module projects, do something like this:
ANSIBLE_LIBRARY=~/ansible-modules-core:~/ansible-modules-extras
And this will make the items in your fork be loaded ahead of what ships with Ansible. Just be sure to make sure you’renot reporting bugs on versions from your fork!
To be safe, if you’re working on a variant on something in Ansible’s normal distribution, it’s not a bad idea to give it anew name while you are working on it, to be sure you know you’re pulling your version.
Getting Your Module Into Ansible
High-quality modules with minimal dependencies can be included in Ansible, but modules (just due to the program-ming preferences of the developers) will need to be implemented in Python and use the AnsibleModule common code,and should generally use consistent arguments with the rest of the program. Stop by the mailing list to inquire aboutrequirements if you like, and submit a github pull request to the extras project. Included modules will ship with an-sible, and also have a chance to be promoted to ‘core’ status, which gives them slightly higher development priority(though they’ll work in exactly the same way).
Module checklist
• The shebang should always be #!/usr/bin/python, this allows ansible_python_interpreter to work
• Documentation: Make sure it exists
– required should always be present, be it true or false
– If required is false you need to document default, even if the default is ‘None’ (which is the default ifno parameter is supplied). Make sure default parameter in docs matches default parameter in code.
– default is not needed for required: true
– Remove unnecessary doc like aliases: [] or choices: []
– The version is not a float number and value the current development version
– Verify that arguments in doc and module spec dict are identical
– For password / secret arguments no_log=True should be set
1.8. Developer Information 801
Ansible 1.2 Documentation, Release 0.01
– Requirements should be documented, using the requirements=[] field
– Author should be set, name and github id at least
– Made use of U() for urls, C() for files and options, I() for params, M() for modules?
– GPL 3 License header
– Does module use check_mode? Could it be modified to use it? Document it
– Examples: make sure they are reproducible
– Return: document the return structure of the module
• Exceptions: The module must handle them. (exceptions are bugs)
– Give out useful messages on what you were doing and you can add the exception message to that.
– Avoid catchall exceptions, they are not very useful unless the underlying API gives very good errormessages pertaining the attempted action.
• The module must not use sys.exit() –> use fail_json() from the module object
• Import custom packages in try/except and handled with fail_json() in main() e.g.:
try:import fooHAS_LIB=True
except:HAS_LIB=False
• The return structure should be consistent, even if NA/None are used for keys normally returned under otheroptions.
• Are module actions idempotent? If not document in the descriptions or the notes
• Import module snippets from ansible.module_utils.basic import * at the bottom, conserves line numbers fordebugging.
• Call your main() from a conditional so that it would be possible to test them in the future example:
if __name__ == '__main__':main()
• Try to normalize parameters with other modules, you can have aliases for when user is more familiar withunderlying API name for the option
• Being pep8 compliant is nice, but not a requirement. Specifically, the 80 column limit now hinders readabilitymore that it improves it
• Avoid ‘action/command‘, they are imperative and not declarative, there are other ways to express the same thing
• Do not add list or info state options to an existing module - create a new _facts module.
• If you are asking ‘how can I have a module execute other modules’ ... you want to write a role
• Return values must be able to be serialized as json via the python stdlib json library. basic python types (strings,int, dicts, lists, etc) are serializable. A common pitfall is to try returning an object via exit_json(). Instead,convert the fields you need from the object into the fields of a dictionary and return the dictionary.
• When fetching URLs, please use either fetch_url or open_url from ansible.module_utils.urls rather than urllib2;urllib2 does not natively verify TLS certificates and so is insecure for https.
802 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Windows modules checklist
• Favour native powershell and .net ways of doing things over calls to COM libraries or calls to native executableswhich may or may not be present in all versions of windows
• modules are in powershell (.ps1 files) but the docs reside in same name python file (.py)
• look at ansible/lib/ansible/module_utils/powershell.ps1 for common code, avoid duplication
• Ansible uses strictmode version 2.0 so be sure to test with that enabled
• start with:
#!powershell
then:: <GPL header>
then:: # WANT_JSON # POWERSHELL_COMMON
then, to parse all arguments into a variable modules generally use:: $params = Parse-Args $args
• Arguments:
– Try and use state present and state absent like other modules
– You need to check that all your mandatory args are present. You can do this using the builtin Get-AnsibleParam function.
– Required arguments:: $package = Get-AnsibleParam -obj $params -name name -failifempty $true
– Required arguments with name validation:: $state = Get-AnsibleParam -obj $params -name“State” -ValidateSet “Present”,”Absent” -resultobj $resultobj -failifempty $true
– Optional arguments with name validation:: $state = Get-AnsibleParam -obj $params -name“State” -default “Present” -ValidateSet “Present”,”Absent”
– the If “FailIfEmpty” is true, the resultobj parameter is used to specify the object returned to fail-json.You can also override the default message using $emptyattributefailmessage (for missing requiredattributes) and $ValidateSetErrorMessage (for attribute validation errors)
– Look at existing modules for more examples of argument checking.
• Results
– The result object should allways contain an attribute called changed set to either $true or $false
– Create your result object like this:
$result = New-Object psobject @{changed = $falseother_result_attribute = $some_value};
If all is well, exit with aExit-Json $result
– Ensure anything you return, including errors can be converted to json.
– Be aware that because exception messages could contain almost anything.
– ConvertTo-Json will fail if it encounters a trailing in a string.
– If all is not well use Fail-Json to exit.
• Have you tested for powershell 3.0 and 4.0 compliance?
1.8. Developer Information 803
Ansible 1.2 Documentation, Release 0.01
Deprecating and making module aliases
Starting in 1.8 you can deprecate modules by renaming them with a preceding _, i.e. old_cloud.py to _old_cloud.py,This will keep the module available but hide it from the primary docs and listing.
You can also rename modules and keep an alias to the old name by using a symlink that starts with _. This exampleallows the stat module to be called with fileinfo, making the following examples equivalent
EXAMPLES = ‘” ln -s stat.py _fileinfo.py ansible -m stat -a “path=/tmp” localhost ansible -m fileinfo -a“path=/tmp” localhost ‘’‘
See also:
About Modules Learn about available modules
Developing Plugins Learn about developing plugins
Python API Learn about the Python API for playbook and task execution
GitHub Core modules directory Browse source of core modules
Github Extras modules directory Browse source of extras modules.
Mailing List Development mailing list
irc.freenode.net #ansible IRC chat channel
Developing Plugins
Topics
• Developing Plugins
– Connection Type Plugins
– Lookup Plugins
– Vars Plugins
– Filter Plugins
– Callbacks
* Examples
* Configuring
* Development
– Distributing Plugins
Ansible is pluggable in a lot of other ways separate from inventory scripts and callbacks. Many of these features arethere to cover fringe use cases and are infrequently needed, and others are pluggable simply because they are there toimplement core features in ansible and were most convenient to be made pluggable.
This section will explore these features, though they are generally not common in terms of things people would lookto extend quite as often.
804 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Connection Type Plugins
By default, ansible ships with a ‘paramiko’ SSH, native ssh (just called ‘ssh’), ‘local’ connection type, and there arealso some minor players like ‘chroot’ and ‘jail’. All of these can be used in playbooks and with /usr/bin/ansible to de-cide how you want to talk to remote machines. The basics of these connection types are covered in the Getting Startedsection. Should you want to extend Ansible to support other transports (SNMP? Message bus? Carrier Pigeon?) it’s assimple as copying the format of one of the existing modules and dropping it into the connection plugins directory. Thevalue 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’.
More documentation on writing connection plugins is pending, though you can jump intolib/ansible/plugins/connection and figure things out pretty easily.
Lookup Plugins
Language constructs like “with_fileglob” and “with_items” are implemented via lookup plugins. Just like other plugintypes, you can write your own.
More documentation on writing lookup plugins is pending, though you can jump into lib/ansible/plugins/lookup andfigure things out pretty easily.
Vars Plugins
Playbook constructs like ‘host_vars’ and ‘group_vars’ work via ‘vars’ plugins. They inject additional variable datainto ansible runs that did not come from an inventory, playbook, or command line. Note that variables can also bereturned from inventory, so in most cases, you won’t need to write or understand vars_plugins.
More documentation on writing vars plugins is pending, though you can jump into lib/ansible/inventory/vars_pluginsand 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.
Filter Plugins
If you want more Jinja2 filters available in a Jinja2 template (filters like to_yaml and to_json are provided by default),they can be extended by writing a filter plugin. Most of the time, when someone comes up with an idea for a new filterthey would like to make available in a playbook, we’ll just include them in ‘core.py’ instead.
Jump into lib/ansible/plugins/filter for details.
Callbacks
Callbacks are one of the more interesting plugin types. Adding additional callback plugins to Ansible allows foradding new behaviors when responding to events.
Examples
Example callbacks are shown in lib/ansible/plugins/callback.
The log_plays callback is an example of how to intercept playbook events to a log file, and the mail callback sendsemail when playbooks complete.
The osx_say callback provided is particularly entertaining – it will respond with computer synthesized speech on OSX in relation to playbook events, and is guaranteed to entertain and/or annoy coworkers.
1.8. Developer Information 805
Ansible 1.2 Documentation, Release 0.01
Configuring
To activate a callback drop it in a callback directory as configured in ansible.cfg.
Development
More information will come later, though see the source of any of the existing callbacks and you should be able to getstarted quickly. They should be reasonably self-explanatory.
Distributing Plugins
Plugins are loaded from both Python’s site_packages (those that ship with ansible) and a configured plugins directory,which defaults to /usr/share/ansible/plugins, in a subfolder for each plugin type:
* action_plugins
* lookup_plugins
* callback_plugins
* connection_plugins
* filter_plugins
* vars_plugins
To change this path, edit the ansible configuration file.
In addition, plugins can be shipped in a subdirectory relative to a top-level playbook, in folders named the same asindicated above.
See also:
About Modules List of built-in modules
Python API Learn about the Python API for task execution
Developing Dynamic Inventory Sources Learn about how to develop dynamic inventory sources
Developing Modules Learn about how to write Ansible modules
Mailing List The development mailing list
irc.freenode.net #ansible IRC chat channel
Helping Testing PRs
If you’re a developer, one of the most valuable things you can do is look at the github issues list and help fix bugs. Wealmost always prioritize bug fixing over feature development, so clearing bugs out of the way is one of the best thingsyou can do.
Even if you’re not a developer, helping test pull requests for bug fixes and features is still immensely valuable.
This goes for testing new features as well as testing bugfixes.
In many cases, code should add tests that prove it works but that’s not ALWAYS possible and tests are not alwayscomprehensive, especially when a user doesn’t have access to a wide variety of platforms, or that is using an API orweb service.
In these cases, live testing against real equipment can be more valuable than automation that runs against simulatedinterfaces. In any case, things should always be tested manually the first time too.
Thankfully helping test ansible is pretty straightforward, assuming you are already used to how ansible works.
806 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Get Started with A Source Checkout
You can do this by checking out ansible, making a test branch off the main one, merging a GitHub issue, testing, andthen commenting on that particular issue on GitHub. Here’s how:
Note: Testing source code from GitHub pull requests sent to us does have some inherent risk, as the source code sentmay have mistakes or malicious code that could have a negative impact on your system. We recommend doing alltesting on a virtual machine, whether a cloud instance, or locally. Some users like Vagrant or Docker for this, but theyare optional. It is also useful to have virtual machines of different Linux or other flavors, since some features (apt vs.yum, for example) are specific to those OS versions.
First, you will need to configure your testing environment with the necessary tools required to run our test suites. Youwill need at least:
gitpython-nosetests (sometimes named python-nose)python-passlibpython-mock
If you want to run the full integration test suite you’ll also need the following packages installed:
svnhgpython-pipgem
Second, if you haven’t already, clone the Ansible source code from GitHub:
git clone https://github.com/ansible/ansible.git --recursivecd ansible/
Note: If you have previously forked the repository on GitHub, you could also clone it from there.
Note: If updating your repo for testing something module related, use “git rebase origin/devel” and then “git sub-module update” to fetch the latest development versions of modules. Skipping the “git submodule update” step willresult in versions that will be stale.
Activating The Source Checkout
The Ansible source includes a script that allows you to use Ansible directly from source without requiring a fullinstallation, that is frequently used by developers on Ansible.
Simply source it (to use the Linux/Unix terminology) to begin using it immediately:
source ./hacking/env-setup
This script modifies the PYTHONPATH enviromnent variables (along with a few other things), which will be tem-porarily set as long as your shell session is open.
If you’d like your testing environment to always use the latest source, you could call the command from startup scripts(for example, .bash_profile).
1.8. Developer Information 807
Ansible 1.2 Documentation, Release 0.01
Finding A Pull Request and Checking It Out On A Branch
Next, find the pull request you’d like to test and make note of the line at the top which describes the source anddestination repositories. It will look something like this:
Someuser wants to merge 1 commit into ansible:devel from someuser:feature_branch_name
Note: It is important that the PR request target be ansible:devel, as we do not accept pull requests into any otherbranch. Dot releases are cherry-picked manually by ansible staff.
The username and branch at the end are the important parts, which will be turned into git commands as follows:
git checkout -b testing_PRXXXX develgit pull https://github.com/someuser/ansible.git feature_branch_name
The first command creates and switches to a new branch named testing_PRXXXX, where the XXXX is the actualissue number associated with the pull request (for example, 1234). This branch is based on the devel branch. Thesecond command pulls the new code from the users feature branch into the newly created branch.
Note: If the GitHub user interface shows that the pull request will not merge cleanly, we do not recommend pro-ceeding if you are not somewhat familiar with git and coding, as you will have to resolve a merge conflict. This is theresponsibility of the original pull request contributor.
Note: Some users do not create feature branches, which can cause problems when they have multiple, un-relatedcommits in their version of devel. If the source looks like someuser:devel, make sure there is only one commit listedon the pull request.
For Those About To Test, We Salute You
At this point, you should be ready to begin testing!
If the PR is a bug-fix pull request, the first things to do are to run the suite of unit and integration tests, to ensure thepull request does not break current functionality:
# Unit Testsmake tests
# Integration Testscd test/integrationmake
Note: Ansible does provide integration tests for cloud-based modules as well, however we do not recommend usingthem for some users due to the associated costs from the cloud providers. As such, typically it’s better to run specificparts of the integration battery and skip these tests.
Integration tests aren’t the end all beat all - in many cases what is fixed might not HAVE a test, so determining if itworks means checking the functionality of the system and making sure it does what it said it would do.
Pull requests for bug-fixes should reference the bug issue number they are fixing.
808 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
We encourage users to provide playbook examples for bugs that show how to reproduce the error, and these playbooksshould be used to verify the bugfix does resolve the issue if available. You may wish to also do your own review topoke the corners of the change.
Since some reproducers can be quite involved, you might wish to create a testing directory with the issue # as a sub-directory to keep things organized:
mkdir -p testing/XXXX # where XXXX is again the issue # for the original issue or PRcd testing/XXXX<create files or git clone example playbook repo>
While it should go without saying, be sure to read any playbooks before you run them. VMs help with runninguntrusted content greatly, though a playbook could still do something to your computing resources that you’d rathernot like.
Once the files are in place, you can run the provided playbook (if there is one) to test the functionality:
ansible-playbook -vvv playbook_name.yml
If there’s not a playbook, you may have to copy and paste playbook snippets or run a ad-hoc command that was pastedin.
Our issue template also included sections for “Expected Output” and “Actual Output”, which should be used to gaugethe output from the provided examples.
If the pull request resolves the issue, please leave a comment on the pull request, showing the following information:
• “Works for me!”
• The output from ansible –version.
In some cases, you may wish to share playbook output from the test run as well.
Example!:
Works for me! Tested on `Ansible 1.7.1`. I verified this on CentOS 6.5 and also→˓Ubuntu 14.04.
If the PR does not resolve the issue, or if you see any failures from the unit/integration tests, just include that outputinstead:
This doesn't work for me.
When I ran this my toaster started making loud noises!
Output from the toaster looked like this:
```BLARGStrackTraceRRRARRGGG```
When you are done testing a feature branch, you can remove it with the following command:
git branch -D someuser-feature_branch_name
We understand some users may be inexperienced with git, or other aspects of the above procedure, so feel free to stopby ansible-devel list for questions and we’d be happy to help answer them.
1.8. Developer Information 809
Ansible 1.2 Documentation, Release 0.01
Developers will also likely be interested in the fully-discoverable in Ansible Tower. It’s great for embedding Ansiblein all manner of applications.
Ansible Tower
Ansible Tower (formerly ‘AWX’) is a web-based solution that makes Ansible even more easy to use for IT teams ofall kinds. It’s designed to be the hub for all of your automation tasks.
Tower allows you to control access to who can access what, even allowing sharing of SSH credentials without someonebeing able to transfer those credentials. Inventory can be graphically managed or synced with a wide variety of cloudsources. It logs all of your jobs, integrates well with LDAP, and has an amazing browsable REST API. Commandline tools are available for easy integration with Jenkins as well. Provisioning callbacks provide great support forautoscaling topologies.
Find out more about Tower features and how to download it on the Ansible Tower webpage. Tower is free for usage forup to 10 nodes, and comes bundled with amazing support from Ansible, Inc. As you would expect, Tower is installedusing Ansible playbooks!
Community Information & Contributing
Ansible is an open source project designed to bring together administrators and developers of all kinds to collaborateon building IT automation solutions that work well for them.
Should you wish to get more involved – whether in terms of just asking a question, helping other users, introducingnew people to Ansible, or helping with the software or documentation, we welcome your contributions to the project.
Topics
• Community Information & Contributing
– Ansible Users
* I’ve Got A Question
* I’d Like To Keep Up With Release Announcements
* I’d Like To Help Share and Promote Ansible
* I’d Like To Help Ansible Move Faster
* I’d Like To Report A Bug
* I’d Like To Help With Documentation
– For Current and Prospective Developers
* I’d Like To Learn How To Develop on Ansible
* Contributing Code (Features or Bugfixes)
– Other Topics
* Ansible Staff
* Mailing List Information
* Release Numbering
810 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
* Tower Support Questions
* IRC Channel
* Notes on Priority Flags
* Community Code of Conduct
* Contributors License Agreement
Ansible Users
I’ve Got A Question
We’re happy to help!
Ansible questions are best asked on the Ansible Google Group Mailing List.
This is a very large high-traffic list for answering questions and sharing tips and tricks. Anyone can join, and emaildelivery is optional if you just want to read the group online. To cut down on spam, your first post is moderated,though posts are approved quickly.
Please be sure to share any relevant commands you ran, output, and detail, indicate the version of Ansible you areusing when asking a question.
Where needed, link to gists or github repos to show examples, rather than sending attachments to the list.
We recommend using Google search to see if a topic has been answered recently, but comments found in older threadsmay no longer apply, depending on the topic.
Before you post, be sure you are running the latest stable version of Ansible. You can check this by comparing theoutput of ‘ansible –version’ with the version indicated on PyPi <https://pypi.python.org/pypi/ansible>.
Alternatively, you can also join our IRC channel - #ansible on irc.freenode.net. It’s a very high traffic channel aswell, if you don’t get an answer you like, please stop by our mailing list, which is more likely to get attention of coredevelopers since it’s asynchronous.
I’d Like To Keep Up With Release Announcements
Release announcements are posted to ansible-project, though if you don’t want to keep up with the very active list,you can join the Ansible Announce Mailing List
This is a low-traffic read-only list, where we’ll share release announcements and occasionally links to major AnsibleEvents around the world.
I’d Like To Help Share and Promote Ansible
You can help share Ansible with others by telling friends and colleagues, writing a blog post, or presenting at usergroups (like DevOps groups or the local LUG).
You are also welcome to share slides on speakerdeck, sign up for a free account and tag it “Ansible”. On Twitter, youcan also share things with #ansible and may wish to follow us.
1.10. Community Information & Contributing 811
Ansible 1.2 Documentation, Release 0.01
I’d Like To Help Ansible Move Faster
If you’re a developer, one of the most valuable things you can do is look at the github issues list and help fix bugs. Wealmost always prioritize bug fixing over feature development, so clearing bugs out of the way is one of the best thingsyou can do.
If you’re not a developer, helping test pull requests for bug fixes and features is still immensely valuable. You cando this by checking out ansible, making a test branch off the main one, merging a GitHub issue, testing, and thencommenting on that particular issue on GitHub.
I’d Like To Report A Bug
Ansible practices responsible disclosure - if this is a security related bug, email [email protected] instead of filinga ticket or posting to the Google Group and you will receive a prompt response.
Bugs related to the core language should be reported to github.com/ansible/ansible after signing up for a free githubaccount. Before reporting a bug, please use the bug/issue search to see if the issue has already been reported.
MODULE related bugs however should go to ansible-modules-core or ansible-modules-extras based on the classifica-tion of the module. This is listed on the bottom of the docs page for any module.
When filing a bug, please use the issue template to provide all relevant information, regardless of what repo you arefiling a ticket against.
Knowing your ansible version and the exact commands you are running, and what you expect, saves time and helpsus help everyone with their issues more quickly.
Do not use the issue tracker for “how do I do this” type questions. These are great candidates for IRC or the mailinglist instead where things are likely to be more of a discussion.
To be respectful of reviewers time and allow us to help everyone efficiently, please provide minimal well-reducedand well-commented examples versus sharing your entire production playbook. Include playbook snippets and outputwhere possible.
When sharing YAML in playbooks, formatting can be preserved by using code blocks.
For multiple-file content, we encourage use of gist.github.com. Online pastebin content can expire, so it’s nice to havethings around for a longer term if they are referenced in a ticket.
If you are not sure if something is a bug yet, you are welcome to ask about something on the mailing list or IRC first.
As we are a very high volume project, if you determine that you do have a bug, please be sure to open the issue yourselfto ensure we have a record of it. Don’t rely on someone else in the community to file the bug report for you.
It may take some time to get to your report, see our information about priority flags below.
I’d Like To Help With Documentation
Ansible documentation is a community project too!
If you would like to help with the documentation, whether correcting a typo or improving a section, or maybe evendocumenting a new feature, submit a github pull request to the code that lives in the “docsite/rst” subdirectory of theproject for most pages, and there is an “Edit on GitHub” link up on those.
Module documentation is generated from a DOCUMENTATION structure embedded in the source code of each mod-ule, which is in either the ansible-modules-core or ansible-modules-extra repos on github, depending on the module.Information about this is always listed on the bottom of the web documentation for each module.
Aside from modules, the main docs are in restructured text format.
812 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
If you aren’t comfortable with restructured text, you can also open a ticket on github about any errors you spot orsections you would like to see added. For more information on creating pull requests, please refer to the github helpguide.
For Current and Prospective Developers
I’d Like To Learn How To Develop on Ansible
If you’re new to Ansible and would like to figure out how to work on things, stop by the ansible-devel mailing list andsay hi, and we can hook you up.
A great way to get started would be reading over some of the development documentation on the module site, and thenfinding a bug to fix or small feature to add.
Modules are some of the easiest places to get started.
Contributing Code (Features or Bugfixes)
The Ansible project keeps its source on github at github.com/ansible/ansible for the core application, and two subrepos github.com/ansible/ansible-modules-core and ansible/ansible-modules-extras for module related items. If youneed to know if a module is in ‘core’ or ‘extras’, consult the web documentation page for that module.
The project takes contributions through github pull requests.
It is usually a good idea to join the ansible-devel list to discuss any large features prior to submission, and this especiallyhelps in avoiding duplicate work or efforts where we decide, upon seeing a pull request for the first time, that revisionsare needed. (This is not usually needed for module development, but can be nice for large changes).
Note that we do keep Ansible to a particular aesthetic, so if you are unclear about whether a feature is a good fit ornot, having the discussion on the development list is often a lot easier than having to modify a pull request later.
When submitting patches, be sure to run the unit tests first “make tests” and always use, these are the same basictests that will automatically run on Travis when creating the PR. There are more in depth tests in the tests/integrationdirectory, classified as destructive and non_destructive, run these if they pertain to your modification. They are setupwith tags so you can run subsets, some of the tests require cloud credentials and will only run if they are provided.When adding new features of fixing bugs it would be nice to add new tests to avoid regressions.
In order to keep the history clean and better audit incoming code, we will require resubmission of pull requests thatcontain merge commits. Use “git pull –rebase” vs “git pull” and “git rebase” vs “git merge”. Also be sure to use topicbranches to keep your additions on different branches, such that they won’t pick up stray commits later.
If you make a mistake you do not need to close your PR, create a clean branch locally and then push to github with –force to overwrite the existing branch (permissible in this case as no one else should be using that branch as reference).Code comments won’t be lost, they just won’t be attached to the existing branch.
We’ll then review your contributions and engage with you about questions and so on.
As we have a very large and active community, so it may take awhile to get your contributions in! See the notes aboutpriorities in a later section for understanding our work queue. Be patient, your request might not get merged rightaway, we also try to keep the devel branch more or less usable so we like to examine Pull requests carefully, whichtakes time.
Patches should always be made against the ‘devel’ branch.
Keep in mind that small and focused requests are easier to examine and accept, having example cases also help usunderstand the utility of a bug fix or a new feature.
1.10. Community Information & Contributing 813
Ansible 1.2 Documentation, Release 0.01
Contributions can be for new features like modules, or to fix bugs you or others have found. If you are interested inwriting new modules to be included in the core Ansible distribution, please refer to the module development docu-mentation.
Ansible’s aesthetic encourages simple, readable code and consistent, conservatively extending, backwards-compatibleimprovements. Code developed for Ansible needs to support Python 2.6+, while code in modules must run underPython 2.4 or higher. Please also use a 4-space indent and no tabs, we do not enforce 80 column lines, we are fine with120-140. We do not take ‘style only’ requests unless the code is nearly unreadable, we are “PEP8ish”, but not strictlycompliant.
You can also contribute by testing and revising other requests, specially if it is one you are interested in using. Pleasekeep your comments clear and to the point, courteous and constructive, tickets are not a good place to start discussions(ansible-devel and IRC exist for this).
Tip: To easily run from a checkout, source ”./hacking/env-setup” and that’s it – no install required. You’re now live!
Other Topics
Ansible Staff
Ansible, Inc is a company supporting Ansible and building additional solutions based on Ansible. We also do servicesand support for those that are interested. We also offer an enterprise web front end to Ansible (see Tower below).
Our most important task however is enabling all the great things that happen in the Ansible community, includingorganizing software releases of Ansible. For more information about any of these things, contact [email protected]
On IRC, you can find us as jimi_c, abadger1999, Tybstar, bcoca, and others. On the mailing list, we post with [email protected] address.
Mailing List Information
Ansible has several mailing lists. Your first post to the mailing list will be moderated (to reduce spam), so please allowa day or less for your first post.
Ansible Project List is for sharing Ansible Tips, answering questions, and general user discussion.
Ansible Development List is for learning how to develop on Ansible, asking about prospective feature design, ordiscussions about extending ansible or features in progress.
Ansible Announce list is a read-only list that shares information about new releases of Ansible, and also rare infrequentevent information, such as announcements about an AnsibleFest coming up, which is our official conference series.
Ansible Lockdown List is for all things related to Ansible Lockdown projects, including DISA STIG automation andCIS Benchmarks.
To subscribe to a group from a non-google account, you can send an email to the subscription address requesting thesubscription. For example: [email protected]
Release Numbering
Releases ending in ”.0” are major releases and this is where all new features land. Releases ending in another integer,like “0.X.1” and “0.X.2” are dot releases, and these are only going to contain bugfixes.
Typically we don’t do dot releases for minor bugfixes (reserving these for larger items), but may occasionally decideto cut dot releases containing a large number of smaller fixes if it’s still a fairly long time before the next release comesout.
Releases are also given code names based on Van Halen songs, that no one really uses.
814 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Tower Support Questions
Ansible Tower is a UI, Server, and REST endpoint for Ansible, produced by Ansible, Inc.
If you have a question about tower, email [email protected] rather than using the IRC channel or the generalproject mailing list.
IRC Channel
Ansible has an IRC channel #ansible on irc.freenode.net.
Notes on Priority Flags
Ansible was one of the top 5 projects with the most OSS contributors on GitHub in 2013, and has over 800 contributorsto the project to date, not to mention a very large user community that has downloaded the application well over amillion times.
As a result, we have a LOT of incoming activity to process.
In the interest of transparency, we’re telling you how we sort incoming requests.
In our bug tracker you’ll notice some labels - P1, P2, P3, P4, and P5. These are our internal priority orders that we useto sort tickets.
With some exceptions for easy merges (like documentation typos for instance), we’re going to spend most of our timeworking on P1 and P2 items first, including pull requests. These usually relate to important bugs or features affectinglarge segments of the userbase. So if you see something categorized “P3 or P4”, and it’s not appearing to get a lot ofimmediate attention, this is why.
These labels don’t really have definition - they are a simple ordering. However something affecting a major module(yum, apt, etc) is likely to be prioritized higher than a module affecting a smaller number of users.
Since we place a strong emphasis on testing and code review, it may take a few months for a minor feature to getmerged.
Don’t worry though – we’ll also take periodic sweeps through the lower priority queues and give them some attentionas well, particularly in the area of new module changes. So it doesn’t necessarily mean that we’ll be exhausting all ofthe higher-priority queues before getting to your ticket.
Every bit of effort helps - if you’re wishing to expedite the inclusion of a P3 feature pull request for instance, the bestthing you can do is help close P2 bug reports.
Community Code of Conduct
Ansible’s community welcomes users of all types, backgrounds, and skill levels. Please treat others as you expect tobe treated, keep discussions positive, and avoid discrimination of all kinds, profanity, allegations of Cthulhu worship,or engaging in controversial debates (except vi vs emacs is cool).
The same expectations apply to community events as they do to online interactions.
Posts to mailing lists should remain focused around Ansible and IT automation. Abuse of these community guidelineswill not be tolerated and may result in banning from community resources.
1.10. Community Information & Contributing 815
Ansible 1.2 Documentation, Release 0.01
Contributors License Agreement
By contributing you agree that these contributions are your own (or approved by your employer) and you grant a full,complete, irrevocable copyright license to all users and developers of the project, present and future, pursuant to thelicense of the project.
Ansible Galaxy
“Ansible Galaxy” can either refer to a website for sharing and downloading Ansible roles, or a command line tool formanaging and creating roles.
Topics
• Ansible Galaxy
– The Website
– The ansible-galaxy command line tool
* Installing Roles
· roles_path
· Installing Multiple Roles From A File
· Advanced Control over Role Requirements Files
* Building Role Scaffolding
* Search for Roles
* Get More Information About a Role
* List Installed Roles
* Remove an Installed Role
* Authenticate with Galaxy
* Import a Role
* Delete a Role
* Setup Travis Integerations
· List Travis Integrations
· Remove Travis Integrations
The Website
The website Ansible Galaxy, is a free site for finding, downloading, and sharing community developed Ansible roles.Downloading roles from Galaxy is a great way to jumpstart your automation projects.
Access the Galaxy web site using GitHub OAuth, and to install roles use the ‘ansible-galaxy’ command line toolincluded in Ansible 1.4.2 and later.
Read the “About” page on the Galaxy site for more information.
816 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
The ansible-galaxy command line tool
The ansible-galaxy command has many different sub-commands for managing roles both locally and atgalaxy.ansible.com.
Note: The search, login, import, delete, and setup commands in the Ansible 2.0 version of ansible-galaxy requireaccess to the 2.0 Beta release of the Galaxy web site available at https://galaxy-qa.ansible.com.
Use the --server option to access the beta site. For example:
$ ansible-galaxy search --server https://galaxy-qa.ansible.com mysql --author→˓geerlingguy
Additionally, you can define a server in ansible.cfg:
[galaxy]server=https://galaxy-qa.ansible.com
Installing Roles
The most obvious use of the ansible-galaxy command is downloading roles from the Ansible Galaxy website:
$ ansible-galaxy install username.rolename
roles_path
You can specify a particular directory where you want the downloaded roles to be placed:
$ ansible-galaxy install username.role -p ~/Code/ansible_roles/
This can be useful if you have a master folder that contains ansible galaxy roles shared across several projects. Thedefault is the roles_path configured in your ansible.cfg file (/etc/ansible/roles if not configured).
Installing Multiple Roles From A File
To install multiple roles, the ansible-galaxy CLI can be fed a requirements file. All versions of ansible allow thefollowing syntax for installing roles from the Ansible Galaxy website:
$ ansible-galaxy install -r requirements.txt
Where the requirements.txt looks like:
username1.foo_roleusername2.bar_role
To request specific versions (tags) of a role, use this syntax in the roles file:
username1.foo_role,versionusername2.bar_role,version
Available versions will be listed on the Ansible Galaxy webpage for that role.
1.11. Ansible Galaxy 817
Ansible 1.2 Documentation, Release 0.01
Advanced Control over Role Requirements Files
For more advanced control over where to download roles from, including support for remote repositories, Ansible 1.8and later support a new YAML format for the role requirements file, which must end in a ‘yml’ extension. It workslike this:
ansible-galaxy install -r requirements.yml
The extension is important. If the .yml extension is left off, the ansible-galaxy CLI will assume the file is in the “basic”format and will be confused.
And here’s an example showing some specific version downloads from multiple sources. In one of the examples wealso override the name of the role and download it as something different:
# from galaxy- src: yatesr.timezone
# from GitHub- src: https://github.com/bennojoy/nginx
# from GitHub installing to a relative path- src: https://github.com/bennojoy/nginxpath: vagrant/roles/
# from GitHub, overriding the name and specifying a specific tag- src: https://github.com/bennojoy/nginxversion: mastername: nginx_role
# from a webserver, where the role is packaged in a tar.gz- src: https://some.webserver.example.com/files/master.tar.gzname: http-role
# from Bitbucket- src: git+http://bitbucket.org/willthames/git-ansible-galaxyversion: v1.4
# from Bitbucket, alternative syntax and caveats- src: http://bitbucket.org/willthames/hg-ansible-galaxyscm: hg
# from GitLab or other git-based scm- src: [email protected]:mygroup/ansible-base.gitscm: gitversion: 0.1.0path: roles/
As you can see in the above, there are a large amount of controls available to customize where roles can be pulledfrom, and what to save roles as.
Roles pulled from galaxy work as with other SCM sourced roles above. To download a role with dependencies, andautomatically install those dependencies, the role must be uploaded to the Ansible Galaxy website.
See also:
Playbook Roles and Include Statements All about ansible roles
Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
irc.freenode.net #ansible IRC chat channel
818 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Building Role Scaffolding
Use the init command to initialize the base structure of a new role, saving time on creating the various directories andmain.yml files a role requires:
$ ansible-galaxy init rolename
The above will create the following directory structure in the current working directory:
README.md.travis.ymldefaults/
main.ymlfiles/handlers/
main.ymlmeta/
main.ymltemplates/tests/
inventorytest.yml
vars/main.yml
Note: .travis.yml and tests/ are new in Ansible 2.0
If a directory matching the name of the role already exists in the current working directory, the init command will resultin an error. To ignore the error use the –force option. Force will create the above subdirectories and files, replacinganything that matches.
Search for Roles
The search command provides for querying the Galaxy database, allowing for searching by tags, platforms, author andmultiple keywords. For example:
$ ansible-galaxy search elasticsearch --author geerlingguy
The search command will return a list of the first 1000 results matching your search:
Found 2 roles matching your search:
Name Description---- -----------geerlingguy.elasticsearch Elasticsearch for Linux.geerlingguy.elasticsearch-curator Elasticsearch curator for Linux.
Note: The format of results pictured here is new in Ansible 2.0.
Get More Information About a Role
Use the info command To view more detail about a specific role:
1.11. Ansible Galaxy 819
Ansible 1.2 Documentation, Release 0.01
$ ansible-galaxy info username.role_name
This returns everything found in Galaxy for the role:
Role: username.rolenamedescription: Installs and configures a thing, a distributed, highly available
→˓NoSQL thing.active: Truecommit: c01947b7bc89ebc0b8a2e298b87ab416aed9dd57commit_message: Adding traviscommit_url: https://github.com/username/repo_name/commit/
→˓c01947b7bc89ebc0b8a2e298b87abcompany: My Company, Inc.created: 2015-12-08T14:17:52.773Zdownload_count: 1forks_count: 0github_branch:github_repo: repo_namegithub_user: usernameid: 6381is_valid: Trueissue_tracker_url:license: Apachemin_ansible_version: 1.4modified: 2015-12-08T18:43:49.085Znamespace: usernameopen_issues_count: 0path: /Users/username/projects/rolesscm: Nonesrc: username.repo_namestargazers_count: 0travis_status_url: https://travis-ci.org/username/repo_name.svg?branch=masterversion:watchers_count: 1
List Installed Roles
The list command shows the name and version of each role installed in roles_path.
$ ansible-galaxy list
- chouseknecht.role-install_mongod, master- chouseknecht.test-role-1, v1.0.2- chrismeyersfsu.role-iptables, master- chrismeyersfsu.role-required_vars, master
Remove an Installed Role
The remove command will delete a role from roles_path:
$ ansible-galaxy remove username.rolename
820 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Authenticate with Galaxy
To use the import, delete and setup commands authentication with Galaxy is required. The login command willauthenticate the user,retrieve a token from Galaxy, and store it in the user’s home directory.
$ ansible-galaxy login
We need your Github login to identify you.This information will not be sent to Galaxy, only to api.github.com.The password will not be displayed.
Use --github-token if you do not want to enter your password.
Github Username: dsmithPassword for dsmith:Succesfully logged into Galaxy as dsmith
As depicted above, the login command prompts for a GitHub username and password. It does NOT send your passwordto Galaxy. It actually authenticates with GitHub and creates a personal access token. It then sends the personal accesstoken to Galaxy, which in turn verifies that you are you and returns a Galaxy access token. After authenticationcompletes the GitHub personal access token is destroyed.
If you do not wish to use your GitHub password, or if you have two-factor authentication enabled with GitHub, usethe –github-token option to pass a personal access token that you create. Log into GitHub, go to Settings and click onPersonal Access Token to create a token.
Note: The login command in Ansible 2.0 requires using the Galaxy 2.0 Beta site. Use the --server option toaccess https://galaxy-qa.ansible.com. You can also add a server definition in the [galaxy] section of your ansible.cfgfile.
Import a Role
Roles can be imported using ansible-galaxy. The import command expects that the user previously authenticated withGalaxy using the login command.
Import any GitHub repo you have access to:
$ ansible-galaxy import github_user github_repo
By default the command will wait for the role to be imported by Galaxy, displaying the results as the import progresses:
Successfully submitted import request 41Starting import 41: role_name=myrole repo=githubuser/ansible-role-repo ref=Retrieving Github repo githubuser/ansible-role-repoAccessing branch: masterParsing and validating meta/main.ymlParsing galaxy_tagsParsing platformsAdding dependenciesParsing and validating README.mdAdding repo tags as role versionsImport completedStatus SUCCESS : warnings=0 errors=0
Use the –branch option to import a specific branch. If not specified, the default branch for the repo will be used.
1.11. Ansible Galaxy 821
Ansible 1.2 Documentation, Release 0.01
If the –no-wait option is present, the command will not wait for results. Results of the most recent import for any ofyour roles is available on the Galaxy web site under My Imports.
Note: The import command in Ansible 2.0 requires using the Galaxy 2.0 Beta site. Use the --server option toaccess https://galaxy-qa.ansible.com. You can also add a server definition in the [galaxy] section of your ansible.cfgfile.
Delete a Role
Remove a role from the Galaxy web site using the delete command. You can delete any role that you have access to inGitHub. The delete command expects that the user previously authenticated with Galaxy using the login command.
$ ansible-galaxy delete github_user github_repo
This only removes the role from Galaxy. It does not impact the actual GitHub repo.
Note: The delete command in Ansible 2.0 requires using the Galaxy 2.0 Beta site. Use the --server option toaccess https://galaxy-qa.ansible.com. You can also add a server definition in the [galaxy] section of your ansible.cfgfile.
Setup Travis Integerations
Using the setup command you can enable notifications from travis. The setup command expects that the user previ-ously authenticated with Galaxy using the login command.
$ ansible-galaxy setup travis github_user github_repo xxxtravistokenxxx
Added integration for travis github_user/github_repo
The setup command requires your Travis token. The Travis token is not stored in Galaxy. It is used along with theGitHub username and repo to create a hash as described in the Travis documentation. The calculated hash is stored inGalaxy and used to verify notifications received from Travis.
The setup command enables Galaxy to respond to notifications. Follow the Travis getting started guide to enable theTravis build process for the role repository.
When you create your .travis.yml file add the following to cause Travis to notify Galaxy when a build completes:
notifications:webhooks: https://galaxy.ansible.com/api/v1/notifications/
Note: The setup command in Ansible 2.0 requires using the Galaxy 2.0 Beta site. Use the --server option toaccess https://galaxy-qa.ansible.com. You can also add a server definition in the [galaxy] section of your ansible.cfgfile.
List Travis Integrations
Use the –list option to display your Travis integrations:
822 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
$ ansible-galaxy setup --list
ID Source Repo---------- ---------- ----------2 travis github_user/github_repo1 travis github_user/github_repo
Remove Travis Integrations
Use the –remove option to disable and remove a Travis integration:
$ ansible-galaxy setup --remove ID
Provide the ID of the integration you want disabled. Use the –list option to get the ID.
Testing Strategies
Integrating Testing With Ansible Playbooks
Many times, people ask, “how can I best integrate testing with Ansible playbooks?” There are many options. Ansibleis actually designed to be a “fail-fast” and ordered system, therefore it makes it easy to embed testing directly inAnsible playbooks. In this chapter, we’ll go into some patterns for integrating tests of infrastructure and discuss theright level of testing that may be appropriate.
Note: This is a chapter about testing the application you are deploying, not the chapter on how to test Ansible modulesduring development. For that content, please hop over to the Development section.
By incorporating a degree of testing into your deployment workflow, there will be fewer surprises when code hitsproduction and, in many cases, tests can be leveraged in production to prevent failed updates from migrating across anentire installation. Since it’s push-based, it’s also very easy to run the steps on the localhost or testing servers. Ansiblelets you insert as many checks and balances into your upgrade workflow as you would like to have.
The Right Level of Testing
Ansible resources are models of desired-state. As such, it should not be necessary to test that services are started,packages are installed, or other such things. Ansible is the system that will ensure these things are declaratively true.Instead, assert these things in your playbooks.
tasks:- service: name=foo state=started enabled=yes
If you think the service may not be started, the best thing to do is request it to be started. If the service fails to start,Ansible will yell appropriately. (This should not be confused with whether the service is doing something functional,which we’ll show more about how to do later).
1.12. Testing Strategies 823
Ansible 1.2 Documentation, Release 0.01
Check Mode As A Drift Test
In the above setup, –check mode in Ansible can be used as a layer of testing as well. If running a deployment playbookagainst an existing system, using the –check flag to the ansible command will report if Ansible thinks it would havehad to have made any changes to bring the system into a desired state.
This can let you know up front if there is any need to deploy onto the given system. Ordinarily scripts and commandsdon’t run in check mode, so if you want certain steps to always execute in check mode, such as calls to the scriptmodule, add the ‘always_run’ flag:
roles:- webserver
tasks:- script: verify.shalways_run: True
Modules That Are Useful for Testing
Certain playbook modules are particularly good for testing. Below is an example that ensures a port is open:
tasks:
- wait_for: host={{ inventory_hostname }} port=22delegate_to: localhost
Here’s an example of using the URI module to make sure a web service returns:
tasks:
- action: uri url=http://www.example.com return_content=yesregister: webpage
- fail: msg='service is not happy'when: "'AWESOME' not in webpage.content"
It’s easy to push an arbitrary script (in any language) on a remote host and the script will automatically fail if it has anon-zero return code:
tasks:
- script: test_script1- script: test_script2 --parameter value --parameter2 value
If using roles (you should be, roles are great!), scripts pushed by the script module can live in the ‘files/’ directory ofa role.
And the assert module makes it very easy to validate various kinds of truth:
tasks:
- shell: /usr/bin/some-command --parameter valueregister: cmd_result
- assert:that:
824 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
- "'not ready' not in cmd_result.stderr"- "'gizmo enabled' in cmd_result.stdout"
Should you feel the need to test for existence of files that are not declaratively set by your Ansible configuration, the‘stat’ module is a great choice:
tasks:
- stat: path=/path/to/somethingregister: p
- assert:that:- p.stat.exists and p.stat.isdir
As mentioned above, there’s no need to check things like the return codes of commands. Ansible is checking themautomatically. Rather than checking for a user to exist, consider using the user module to make it exist.
Ansible is a fail-fast system, so when there is an error creating that user, it will stop the playbook run. You do not haveto check up behind it.
Testing Lifecycle
If writing some degree of basic validation of your application into your playbooks, they will run every time you deploy.
As such, deploying into a local development VM and a staging environment will both validate that things are accordingto plan ahead of your production deploy.
Your workflow may be something like this:
- Use the same playbook all the time with embedded tests in development- Use the playbook to deploy to a staging environment (with the same playbooks) that→˓simulates production- Run an integration test battery written by your QA team against staging- Deploy to production, with the same integrated tests.
Something like an integration test battery should be written by your QA team if you are a production webservice. Thiswould include things like Selenium tests or automated API tests and would usually not be something embedded intoyour Ansible playbooks.
However, it does make sense to include some basic health checks into your playbooks, and in some cases it may bepossible to run a subset of the QA battery against remote nodes. This is what the next section covers.
Integrating Testing With Rolling Updates
If you have read into Delegation, Rolling Updates, and Local Actions it may quickly become apparent that the rollingupdate pattern can be extended, and you can use the success or failure of the playbook run to decide whether to add amachine into a load balancer or not.
This is the great culmination of embedded tests:
---
- hosts: webserversserial: 5
1.12. Testing Strategies 825
Ansible 1.2 Documentation, Release 0.01
pre_tasks:
- name: take out of load balancer poolcommand: /usr/bin/take_out_of_pool {{ inventory_hostname }}delegate_to: 127.0.0.1
roles:
- common- webserver- apply_testing_checks
post_tasks:
- name: add back to load balancer poolcommand: /usr/bin/add_back_to_pool {{ inventory_hostname }}delegate_to: 127.0.0.1
Of course in the above, the “take out of the pool” and “add back” steps would be replaced with a call to a Ansible loadbalancer module or appropriate shell command. You might also have steps that use a monitoring module to start andend an outage window for the machine.
However, what you can see from the above is that tests are used as a gate – if the “apply_testing_checks” step is notperformed, the machine will not go back into the pool.
Read the delegation chapter about “max_fail_percentage” and you can also control how many failing tests will stop arolling update from proceeding.
This above approach can also be modified to run a step from a testing machine remotely against a machine:
---
- hosts: webserversserial: 5
pre_tasks:
- name: take out of load balancer poolcommand: /usr/bin/take_out_of_pool {{ inventory_hostname }}delegate_to: 127.0.0.1
roles:
- common- webserver
tasks:- script: /srv/qa_team/app_testing_script.sh --server {{ inventory_hostname }}
delegate_to: testing_server
post_tasks:
- name: add back to load balancer poolcommand: /usr/bin/add_back_to_pool {{ inventory_hostname }}delegate_to: 127.0.0.1
In the above example, a script is run from the testing server against a remote node prior to bringing it back into thepool.
826 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
In the event of a problem, fix the few servers that fail using Ansible’s automatically generated retry file to repeat thedeploy on just those servers.
Achieving Continuous Deployment
If desired, the above techniques may be extended to enable continuous deployment practices.
The workflow may look like this:
- Write and use automation to deploy local development VMs- Have a CI system like Jenkins deploy to a staging environment on every code change- The deploy job calls testing scripts to pass/fail a build on every deploy- If the deploy job succeeds, it runs the same deploy playbook against production→˓inventory
Some Ansible users use the above approach to deploy a half-dozen or dozen times an hour without taking all of theirinfrastructure offline. A culture of automated QA is vital if you wish to get to this level.
If you are still doing a large amount of manual QA, you should still make the decision on whether to deploy manuallyas well, but it can still help to work in the rolling update patterns of the previous section and incorporate some basichealth checks using modules like ‘script’, ‘stat’, ‘uri’, and ‘assert’.
Conclusion
Ansible believes you should not need another framework to validate basic things of your infrastructure is true. Thisis the case because Ansible is an order-based system that will fail immediately on unhandled errors for a host, andprevent further configuration of that host. This forces errors to the top and shows them in a summary at the end of theAnsible run.
However, as Ansible is designed as a multi-tier orchestration system, it makes it very easy to incorporate tests intothe end of a playbook run, either using loose tasks or roles. When used with rolling updates, testing steps can decidewhether to put a machine back into a load balanced pool or not.
Finally, because Ansible errors propagate all the way up to the return code of the Ansible program itself, and Ansibleby default runs in an easy push-based mode, Ansible is a great step to put into a build environment if you wish to useit to roll out systems as part of a Continuous Integration/Continuous Delivery pipeline, as is covered in sections above.
The focus should not be on infrastructure testing, but on application testing, so we strongly encourage getting togetherwith your QA team and ask what sort of tests would make sense to run every time you deploy development VMs,and which sort of tests they would like to run against the staging environment on every deploy. Obviously at thedevelopment stage, unit tests are great too. But don’t unit test your playbook. Ansible describes states of resourcesdeclaratively, so you don’t have to. If there are cases where you want to be sure of something though, that’s great, andthings like stat/assert are great go-to modules for that purpose.
In all, testing is a very organizational and site-specific thing. Everybody should be doing it, but what makes the mostsense for your environment will vary with what you are deploying and who is using it – but everyone benefits from amore robust and reliable deployment system.
See also:
About Modules All the documentation for Ansible modules
Playbooks An introduction to playbooks
Delegation, Rolling Updates, and Local Actions Delegation, useful for working with loud balancers, clouds, and lo-cally executed steps.
User Mailing List Have a question? Stop by the google group!
1.12. Testing Strategies 827
Ansible 1.2 Documentation, Release 0.01
irc.freenode.net #ansible IRC chat channel
Frequently Asked Questions
Here are some commonly-asked questions and their answers.
How can I set the PATH or any other environment variable for a task or entire play-book?
Setting environment variables can be done with the environment keyword. It can be used at task or play level:
environment:PATH: "{{ ansible_env.PATH }}:/thingy/bin"SOME: value
How do I handle different machines needing different user accounts or ports to login with?
Setting inventory variables in the inventory file is the easiest way.
Note: Ansible 2.0 has deprecated the “ssh” from ansible_ssh_user, ansible_ssh_host, andansible_ssh_port to become ansible_user, ansible_host, and ansible_port. If you are usinga version of Ansible prior to 2.0, you should continue using the older style variables (ansible_ssh_*). Theseshorter variables are ignored, without warning, in older versions of Ansible.
For instance, suppose these hosts have different usernames and ports:
[webservers]asdf.example.com ansible_port=5000 ansible_user=alicejkl.example.com ansible_port=5001 ansible_user=bob
You can also dictate the connection type to be used, if you want:
[testcluster]localhost ansible_connection=local/path/to/chroot1 ansible_connection=chrootfoo.example.combar.example.com
You may also wish to keep these in group variables instead, or file in them in a group_vars/<groupname> file. See therest of the documentation for more information about how to organize variables.
How do I get ansible to reuse connections, enable Kerberized SSH, or have Ansiblepay attention to my local SSH config file?
Switch your default connection type in the configuration file to ‘ssh’, or use ‘-c ssh’ to use Native OpenSSH forconnections instead of the python paramiko library. In Ansible 1.2.1 and later, ‘ssh’ will be used by default if OpenSSHis new enough to support ControlPersist as an option.
828 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Paramiko is great for starting out, but the OpenSSH type offers many advanced options. You will want to run Ansiblefrom a machine new enough to support ControlPersist, if you are using this connection type. You can still manageolder clients. If you are using RHEL 6, CentOS 6, SLES 10 or SLES 11 the version of OpenSSH is still a bit old,so consider managing from a Fedora or openSUSE client even though you are managing older nodes, or just useparamiko.
We keep paramiko as the default as if you are first installing Ansible on an EL box, it offers a better experience fornew users.
How do I configure a jump host to access servers that I have no direct access to?
With Ansible 2, you can set a ProxyCommand in the ansible_ssh_common_args inventory variable. Any argumentsspecified in this variable are added to the sftp/scp/ssh command line when connecting to the relevant host(s). Considerthe following inventory group:
[gatewayed]foo ansible_host=192.0.2.1bar ansible_host=192.0.2.2
You can create group_vars/gatewayed.yml with the following contents:
ansible_ssh_common_args: '-o ProxyCommand="ssh -W %h:%p -q [email protected]"'
Ansible will append these arguments to the command line when trying to connect to any hosts in the group gate-wayed. (These arguments are used in addition to any ssh_args from ansible.cfg, so you do not need to repeat globalControlPersist settings in ansible_ssh_common_args.)
Note that ssh -W is available only with OpenSSH 5.4 or later. With older versions, it’s necessary to execute nc %h:%por some equivalent command on the bastion host.
With earlier versions of Ansible, it was necessary to configure a suitable ProxyCommand for one or more hosts in~/.ssh/config, or globally by setting ssh_args in ansible.cfg.
How do I speed up management inside EC2?
Don’t try to manage a fleet of EC2 machines from your laptop. Connect to a management node inside EC2 first andrun Ansible from there.
How do I handle python pathing not having a Python 2.X in /usr/bin/python on aremote machine?
While you can write ansible modules in any language, most ansible modules are written in Python, and some of theseare important core ones.
By default Ansible assumes it can find a /usr/bin/python on your remote system that is a 2.X version of Python,specifically 2.4 or higher.
Setting of an inventory variable ‘ansible_python_interpreter’ on any host will allow Ansible to auto-replace the in-terpreter used when executing python modules. Thus, you can point to any python you want on the system if/usr/bin/python on your system does not point to a Python 2.X interpreter.
Some Linux operating systems, such as Arch, may only have Python 3 installed by default. This is not sufficient andyou will get syntax errors trying to run modules with Python 3. Python 3 is essentially not the same language as Python2. Ansible modules currently need to support older Pythons for users that still have Enterprise Linux 5 deployed, so
1.13. Frequently Asked Questions 829
Ansible 1.2 Documentation, Release 0.01
they are not yet ported to run under Python 3.0. This is not a problem though as you can just install Python 2 also ona managed host.
Python 3.0 support will likely be addressed at a later point in time when usage becomes more mainstream.
Do not replace the shebang lines of your python modules. Ansible will do this for you automatically at deploy time.
What is the best way to make content reusable/redistributable?
If you have not done so already, read all about “Roles” in the playbooks documentation. This helps you make playbookcontent self-contained, and works well with things like git submodules for sharing content with others.
If some of these plugin types look strange to you, see the API documentation for more details about ways Ansible canbe extended.
Where does the configuration file live and what can I configure in it?
See Configuration file.
How do I disable cowsay?
If cowsay is installed, Ansible takes it upon itself to make your day happier when running playbooks. If you decide thatyou would like to work in a professional cow-free environment, you can either uninstall cowsay, or set an environmentvariable:
export ANSIBLE_NOCOWS=1
How do I see a list of all of the ansible_ variables?
Ansible by default gathers “facts” about the machines under management, and these facts can be accessed in Playbooksand in templates. To see a list of all of the facts that are available about a machine, you can run the “setup” module asan ad-hoc action:
ansible -m setup hostname
This will print out a dictionary of all of the facts that are available for that particular host. You might want to pipe theoutput to a pager.
How do I see all the inventory vars defined for my host?
You can see the resulting vars you define in inventory running the following command:
ansible -m debug -a "var=hostvars['hostname']" localhost
How do I loop over a list of hosts in a group, inside of a template?
A pretty common pattern is to iterate over a list of hosts inside of a host group, perhaps to populate a templateconfiguration file with a list of servers. To do this, you can just access the “$groups” dictionary in your template, likethis:
830 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
{% for host in groups['db_servers'] %}{{ host }}
{% endfor %}
If you need to access facts about these hosts, for instance, the IP address of each hostname, you need to make sure thatthe facts have been populated. For example, make sure you have a play that talks to db_servers:
- hosts: db_serverstasks:- # doesn't matter what you do, just that they were talked to previously.
Then you can use the facts inside your template, like this:
{% for host in groups['db_servers'] %}{{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}
How do I access a variable name programmatically?
An example may come up where we need to get the ipv4 address of an arbitrary interface, where the interface to beused may be supplied via a role parameter or other input. Variable names can be built by adding strings together, likeso:
{{ hostvars[inventory_hostname]['ansible_' + which_interface]['ipv4']['address'] }}
The trick about going through hostvars is necessary because it’s a dictionary of the entire namespace of variables.‘inventory_hostname’ is a magic variable that indicates the current host you are looping over in the host loop.
How do I access a variable of the first host in a group?
What happens if we want the ip address of the first webserver in the webservers group? Well, we can do that too. Notethat if we are using dynamic inventory, which host is the ‘first’ may not be consistent, so you wouldn’t want to do thisunless your inventory was static and predictable. (If you are using Ansible Tower, it will use database order, so thisisn’t a problem even if you are using cloud based inventory scripts).
Anyway, here’s the trick:
{{ hostvars[groups['webservers'][0]]['ansible_eth0']['ipv4']['address'] }}
Notice how we’re pulling out the hostname of the first machine of the webservers group. If you are doing this in atemplate, you could use the Jinja2 ‘#set’ directive to simplify this, or in a playbook, you could also use set_fact:
- set_fact: headnode={{ groups[['webservers'][0]] }}
- debug: msg={{ hostvars[headnode].ansible_eth0.ipv4.address }}
Notice how we interchanged the bracket syntax for dots – that can be done anywhere.
How do I copy files recursively onto a target host?
The “copy” module has a recursive parameter, though if you want to do something more efficient for a large numberof files, take a look at the “synchronize” module instead, which wraps rsync. See the module index for info on both ofthese modules.
1.13. Frequently Asked Questions 831
Ansible 1.2 Documentation, Release 0.01
How do I access shell environment variables?
If you just need to access existing variables, use the ‘env’ lookup plugin. For example, to access the value of theHOME environment variable on management machine:
---# ...
vars:local_home: "{{ lookup('env','HOME') }}"
If you need to set environment variables, see the Advanced Playbooks section about environments.
Ansible 1.4 will also make remote environment variables available via facts in the ‘ansible_env’ variable:
{{ ansible_env.SOME_VARIABLE }}
How do I generate crypted passwords for the user module?
The mkpasswd utility that is available on most Linux systems is a great option:
mkpasswd --method=SHA-512
If this utility is not installed on your system (e.g. you are using OS X) then you can still easily generate these passwordsusing Python. First, ensure that the Passlib password hashing library is installed.
pip install passlib
Once the library is ready, SHA512 password values can then be generated as follows:
python -c "from passlib.hash import sha512_crypt; import getpass; print sha512_crypt.→˓encrypt(getpass.getpass())"
Can I get training on Ansible or find commercial support?
Yes! See our services page for information on our services and training offerings. Support is also included withAnsible Tower. Email [email protected] for further details.
We also offer free web-based training classes on a regular basis. See our webinar page for more info on upcomingwebinars.
Is there a web interface / REST API / etc?
Yes! Ansible, Inc makes a great product that makes Ansible even more powerful and easy to use. See Ansible Tower.
How do I submit a change to the documentation?
Great question! Documentation for Ansible is kept in the main project git repository, and complete instructions forcontributing can be found in the docs README viewable on GitHub. Thanks!
832 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
How do I keep secret data in my playbook?
If you would like to keep secret data in your Ansible content and still share it publicly or keep things in source control,see Vault. In Ansible 1.8 and later, if you have a task that you don’t want to show the results or command given to itwhen using -v (verbose) mode, the following task or playbook attribute can be useful:
- name: secret taskshell: /usr/bin/do_something --value={{ secret_value }}no_log: True
This can be used to keep verbose output but hide sensitive information from others who would otherwise like to beable to see the output.
The no_log attribute can also apply to an entire play:
- hosts: allno_log: True
Though this will make the play somewhat difficult to debug. It’s recommended that this be applied to single tasks only,once a playbook is completed.
I don’t see my question here
Please see the section below for a link to IRC and the Google Group, where you can ask your question there.
See also:
Ansible Documentation The documentation index
Playbooks An introduction to playbooks
Best Practices Best practices advice
User Mailing List Have a question? Stop by the google group!
irc.freenode.net #ansible IRC chat channel
Glossary
The following is a list (and re-explanation) of term definitions used elsewhere in the Ansible documentation.
Consult the documentation home page for the full documentation and to see the terms in context, but this should be agood resource to check your knowledge of Ansible’s components and understand how they fit together. It’s somethingyou might wish to read for review or when a term comes up on the mailing list.
Action
An action is a part of a task that specifies which of the modules to run and the arguments to pass to that module. Eachtask can have only one action, but it may also have other parameters.
Ad Hoc
Refers to running Ansible to perform some quick command, using /usr/bin/ansible, rather than the orchestration lan-guage, which is /usr/bin/ansible-playbook. An example of an ad-hoc command might be rebooting 50 machines in
1.14. Glossary 833
Ansible 1.2 Documentation, Release 0.01
your infrastructure. Anything you can do ad-hoc can be accomplished by writing a playbook, and playbooks can alsoglue lots of other operations together.
Async
Refers to a task that is configured to run in the background rather than waiting for completion. If you have a longprocess that would run longer than the SSH timeout, it would make sense to launch that task in async mode. Asyncmodes can poll for completion every so many seconds, or can be configured to “fire and forget” in which case Ansiblewill not even check on the task again, it will just kick it off and proceed to future steps. Async modes work with both/usr/bin/ansible and /usr/bin/ansible-playbook.
Callback Plugin
Refers to some user-written code that can intercept results from Ansible and do something with them. Some suppliedexamples in the GitHub project perform custom logging, send email, or even play sound effects.
Check Mode
Refers to running Ansible with the --check option, which does not make any changes on the remote systems,but only outputs the changes that might occur if the command ran without this flag. This is analogous to so-called“dry run” modes in other systems, though the user should be warned that this does not take into account unexpectedcommand failures or cascade effects (which is true of similar modes in other systems). Use this to get an idea of whatmight happen, but it is not a substitute for a good staging environment.
Connection Type, Connection Plugin
By default, Ansible talks to remote machines through pluggable libraries. Ansible supports native OpenSSH (‘ssh’),or a Python implementation called ‘paramiko’. OpenSSH is preferred if you are using a recent version, and alsoenables some features like Kerberos and jump hosts. This is covered in the getting started section. There are also otherconnection types like ‘accelerate’ mode, which must be bootstrapped over one of the SSH-based connection types butis very fast, and local mode, which acts on the local system. Users can also write their own connection plugins.
Conditionals
A conditional is an expression that evaluates to true or false that decides whether a given task will be executed on agiven machine or not. Ansible’s conditionals are powered by the ‘when’ statement, and are discussed in the playbookdocumentation.
Diff Mode
A --diff flag can be passed to Ansible to show how template files change when they are overwritten, or how theymight change when used with --check mode. These diffs come out in unified diff format.
Facts
Facts are simply things that are discovered about remote nodes. While they can be used in playbooks and templatesjust like variables, facts are things that are inferred, rather than set. Facts are automatically discovered by Ansiblewhen running plays by executing the internal ‘setup’ module on the remote nodes. You never have to call the setup
834 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
module explicitly, it just runs, but it can be disabled to save time if it is not needed. For the convenience of users whoare switching from other configuration management systems, the fact module will also pull in facts from the ‘ohai’and ‘facter’ tools if they are installed, which are fact libraries from Chef and Puppet, respectively.
Filter Plugin
A filter plugin is something that most users will never need to understand. These allow for the creation of new Jinja2filters, which are more or less only of use to people who know what Jinja2 filters are. If you need them, you can learnhow to write them in the API docs section.
Forks
Ansible talks to remote nodes in parallel and the level of parallelism can be set either by passing --forks, or editingthe default in a configuration file. The default is a very conservative 5 forks, though if you have a lot of RAM, you caneasily set this to a value like 50 for increased parallelism.
Gather Facts (Boolean)
Facts are mentioned above. Sometimes when running a multi-play playbook, it is desirable to have some plays thatdon’t bother with fact computation if they aren’t going to need to utilize any of these values. Setting gather_facts:False on a playbook allows this implicit fact gathering to be skipped.
Globbing
Globbing is a way to select lots of hosts based on wildcards, rather than the name of the host specifically, or the nameof the group they are in. For instance, it is possible to select “www*” to match all hosts starting with “www”. Thisconcept is pulled directly from Func, one of Michael’s earlier projects. In addition to basic globbing, various setoperations are also possible, such as ‘hosts in this group and not in another group’, and so on.
Group
A group consists of several hosts assigned to a pool that can be conveniently targeted together, and also given variablesthat they share in common.
Group Vars
The “group_vars/” files are files that live in a directory alongside an inventory file, with an optional filename namedafter each group. This is a convenient place to put variables that will be provided to a given group, especially complexdata structures, so that these variables do not have to be embedded in the inventory file or playbook.
Handlers
Handlers are just like regular tasks in an Ansible playbook (see Tasks), but are only run if the Task contains a “notify”directive and also indicates that it changed something. For example, if a config file is changed then the task referencingthe config file templating operation may notify a service restart handler. This means services can be bounced only ifthey need to be restarted. Handlers can be used for things other than service restarts, but service restarts are the mostcommon usage.
1.14. Glossary 835
Ansible 1.2 Documentation, Release 0.01
Host
A host is simply a remote machine that Ansible manages. They can have individual variables assigned to them, andcan also be organized in groups. All hosts have a name they can be reached at (which is either an IP address or adomain name) and optionally a port number if they are not to be accessed on the default SSH port.
Host Specifier
Each Play in Ansible maps a series of tasks (which define the role, purpose, or orders of a system) to a set of systems.
This “hosts:” directive in each play is often called the hosts specifier.
It may select one system, many systems, one or more groups, or even some hosts that are in one group and explicitlynot in another.
Host Vars
Just like “Group Vars”, a directory alongside the inventory file named “host_vars/” can contain a file named aftereach hostname in the inventory file, in YAML format. This provides a convenient place to assign variables to thehost without having to embed them in the inventory file. The Host Vars file can also be used to define complex datastructures that can’t be represented in the inventory file.
Idempotency
The concept that change commands should only be applied when they need to be applied, and that it is better todescribe the desired state of a system than the process of how to get to that state. As an analogy, the path from NorthCarolina in the United States to California involves driving a very long way West, but if I were instead in Anchorage,Alaska, driving a long way west is no longer the right way to get to California. Ansible’s Resources like you to say“put me in California” and then decide how to get there. If you were already in California, nothing needs to happen,and it will let you know it didn’t need to change anything.
Includes
The idea that playbook files (which are nothing more than lists of plays) can include other lists of plays, and task listscan externalize lists of tasks in other files, and similarly with handlers. Includes can be parameterized, which meansthat the loaded file can pass variables. For instance, an included play for setting up a WordPress blog may take aparameter called “user” and that play could be included more than once to create a blog for both “alice” and “bob”.
Inventory
A file (by default, Ansible uses a simple INI format) that describes Hosts and Groups in Ansible. Inventory can alsobe provided via an “Inventory Script” (sometimes called an “External Inventory Script”).
Inventory Script
A very simple program (or a complicated one) that looks up hosts, group membership for hosts, and variable infor-mation from an external resource – whether that be a SQL database, a CMDB solution, or something like LDAP. Thisconcept was adapted from Puppet (where it is called an “External Nodes Classifier”) and works more or less exactlythe same way.
836 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Jinja2
Jinja2 is the preferred templating language of Ansible’s template module. It is a very simple Python template languagethat is generally readable and easy to write.
JSON
Ansible uses JSON for return data from remote modules. This allows modules to be written in any language, not justPython.
Lazy Evaluation
In general, Ansible evaluates any variables in playbook content at the last possible second, which means that if youdefine a data structure that data structure itself can define variable values within it, and everything “just works” as youwould expect. This also means variable strings can include other variables inside of those strings.
Library
A collection of modules made available to /usr/bin/ansible or an Ansible playbook.
Limit Groups
By passing --limit somegroup to ansible or ansible-playbook, the commands can be limited to a subset of hosts.For instance, this can be used to run a playbook that normally targets an entire set of servers to one particular server.
Local Action
A local_action directive in a playbook targeting remote machines means that the given step will actually occur on thelocal machine, but that the variable ‘{{ ansible_hostname }}’ can be passed in to reference the remote hostname beingreferred to in that step. This can be used to trigger, for example, an rsync operation.
Local Connection
By using “connection: local” in a playbook, or passing “-c local” to /usr/bin/ansible, this indicates that we are manag-ing the local host and not a remote machine.
Lookup Plugin
A lookup plugin is a way to get data into Ansible from the outside world. These are how such things as “with_items”,a basic looping plugin, are implemented, but there are also lookup plugins like “with_file” which loads data from afile, and even ones for querying environment variables, DNS text records, or key value stores. Lookup plugins canalso be accessed in templates, e.g., {{ lookup('file','/path/to/file') }}.
1.14. Glossary 837
Ansible 1.2 Documentation, Release 0.01
Loops
Generally, Ansible is not a programming language. It prefers to be more declarative, though various constructs like“with_items” allow a particular task to be repeated for multiple items in a list. Certain modules, like yum and apt, areactually optimized for this, and can install all packages given in those lists within a single transaction, dramaticallyspeeding up total time to configuration.
Modules
Modules are the units of work that Ansible ships out to remote machines. Modules are kicked off by either/usr/bin/ansible or /usr/bin/ansible-playbook (where multiple tasks use lots of different modules in conjunction). Mod-ules can be implemented in any language, including Perl, Bash, or Ruby – but can leverage some useful communallibrary code if written in Python. Modules just have to return JSON or simple key=value pairs. Once modules areexecuted on remote machines, they are removed, so no long running daemons are used. Ansible refers to the collectionof available modules as a ‘library’.
Multi-Tier
The concept that IT systems are not managed one system at a time, but by interactions between multiple systems, andgroups of systems, in well defined orders. For instance, a web server may need to be updated before a database server,and pieces on the web server may need to be updated after THAT database server, and various load balancers andmonitoring servers may need to be contacted. Ansible models entire IT topologies and workflows rather than lookingat configuration from a “one system at a time” perspective.
Notify
The act of a task registering a change event and informing a handler task that another action needs to be run at the endof the play. If a handler is notified by multiple tasks, it will still be run only once. Handlers are run in the order theyare listed, not in the order that they are notified.
Orchestration
Many software automation systems use this word to mean different things. Ansible uses it as a conductor wouldconduct an orchestra. A datacenter or cloud architecture is full of many systems, playing many parts – web servers,database servers, maybe load balancers, monitoring systems, continuous integration systems, etc. In performing anyprocess, it is necessary to touch systems in particular orders, often to simulate rolling updates or to deploy softwarecorrectly. Some system may perform some steps, then others, then previous systems already processed may need toperform more steps. Along the way, emails may need to be sent or web services contacted. Ansible orchestration isall about modeling that kind of process.
paramiko
By default, Ansible manages machines over SSH. The library that Ansible uses by default to do this is a Python-powered library called paramiko. The paramiko library is generally fast and easy to manage, though users desiringKerberos or Jump Host support may wish to switch to a native SSH binary such as OpenSSH by specifying theconnection type in their playbook, or using the “-c ssh” flag.
838 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Playbooks
Playbooks are the language by which Ansible orchestrates, configures, administers, or deploys systems. They arecalled playbooks partially because it’s a sports analogy, and it’s supposed to be fun using them. They aren’t workbooks:)
Plays
A playbook is a list of plays. A play is minimally a mapping between a set of hosts selected by a host specifier (usuallychosen by groups, but sometimes by hostname globs) and the tasks which run on those hosts to define the role thatthose systems will perform. There can be one or many plays in a playbook.
Pull Mode
By default, Ansible runs in push mode, which allows it very fine-grained control over when it talks to each system.Pull mode is provided for when you would rather have nodes check in every N minutes on a particular schedule. Ituses a program called ansible-pull and can also be set up (or reconfigured) using a push-mode playbook. Most Ansibleusers use push mode, but pull mode is included for variety and the sake of having choices.
ansible-pull works by checking configuration orders out of git on a crontab and then managing the machine locally,using the local connection plugin.
Push Mode
Push mode is the default mode of Ansible. In fact, it’s not really a mode at all – it’s just how Ansible works when youaren’t thinking about it. Push mode allows Ansible to be fine-grained and conduct nodes through complex orchestrationprocesses without waiting for them to check in.
Register Variable
The result of running any task in Ansible can be stored in a variable for use in a template or a conditional statement.The keyword used to define the variable is called ‘register’, taking its name from the idea of registers in assemblyprogramming (though Ansible will never feel like assembly programming). There are an infinite number of variablenames you can use for registration.
Resource Model
Ansible modules work in terms of resources. For instance, the file module will select a particular file and ensurethat the attributes of that resource match a particular model. As an example, we might wish to change the owner of/etc/motd to ‘root’ if it is not already set to root, or set its mode to ‘0644’ if it is not already set to ‘0644’. The resourcemodels are ‘idempotent’ meaning change commands are not run unless needed, and Ansible will bring the systemback to a desired state regardless of the actual state – rather than you having to tell it how to get to the state.
Roles
Roles are units of organization in Ansible. Assigning a role to a group of hosts (or a set of groups, or host patterns,etc.) implies that they should implement a specific behavior. A role may include applying certain variable values,certain tasks, and certain handlers – or just one or more of these things. Because of the file structure associated with arole, roles become redistributable units that allow you to share behavior among playbooks – or even with other users.
1.14. Glossary 839
Ansible 1.2 Documentation, Release 0.01
Rolling Update
The act of addressing a number of nodes in a group N at a time to avoid updating them all at once and bringing thesystem offline. For instance, in a web topology of 500 nodes handling very large volume, it may be reasonable toupdate 10 or 20 machines at a time, moving on to the next 10 or 20 when done. The “serial:” keyword in an Ansibleplaybook controls the size of the rolling update pool. The default is to address the batch size all at once, so this issomething that you must opt-in to. OS configuration (such as making sure config files are correct) does not typicallyhave to use the rolling update model, but can do so if desired.
Runner
A core software component of Ansible that is the power behind /usr/bin/ansible directly – and corresponds to theinvocation of each task in a playbook. The Runner is something Ansible developers may talk about, but it’s not reallyuser land vocabulary.
Serial
See “Rolling Update”.
Sudo
Ansible does not require root logins, and since it’s daemonless, definitely does not require root level daemons (whichcan be a security concern in sensitive environments). Ansible can log in and perform many operations wrapped in asudo command, and can work with both password-less and password-based sudo. Some operations that don’t normallywork with sudo (like scp file transfer) can be achieved with Ansible’s copy, template, and fetch modules while runningin sudo mode.
SSH (Native)
Native OpenSSH as an Ansible transport is specified with “-c ssh” (or a config file, or a directive in the playbook) andcan be useful if wanting to login via Kerberized SSH or using SSH jump hosts, etc. In 1.2.1, ‘ssh’ will be used bydefault if the OpenSSH binary on the control machine is sufficiently new. Previously, Ansible selected ‘paramiko’ asa default. Using a client that supports ControlMaster and ControlPersist is recommended for maximum performance– if you don’t have that and don’t need Kerberos, jump hosts, or other features, paramiko is a good choice. Ansiblewill warn you if it doesn’t detect ControlMaster/ControlPersist capability.
Tags
Ansible allows tagging resources in a playbook with arbitrary keywords, and then running only the parts of the play-book that correspond to those keywords. For instance, it is possible to have an entire OS configuration, and havecertain steps labeled “ntp”, and then run just the “ntp” steps to reconfigure the time server information on a remotehost.
Tasks
Playbooks exist to run tasks. Tasks combine an action (a module and its arguments) with a name and optionally someother keywords (like looping directives). Handlers are also tasks, but they are a special kind of task that do not rununless they are notified by name when a task reports an underlying change on a remote system.
840 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
Templates
Ansible can easily transfer files to remote systems, but often it is desirable to substitute variables in other files. Vari-ables may come from the inventory file, Host Vars, Group Vars, or Facts. Templates use the Jinja2 template engineand can also include logical constructs like loops and if statements.
Transport
Ansible uses “Connection Plugins” to define types of available transports. These are simply how Ansible will reachout to managed systems. Transports included are paramiko, SSH (using OpenSSH), and local.
When
An optional conditional statement attached to a task that is used to determine if the task should run or not. If theexpression following the “when:” keyword evaluates to false, the task will be ignored.
Van Halen
For no particular reason, other than the fact that Michael really likes them, all Ansible releases are codenamed afterVan Halen songs. There is no preference given to David Lee Roth vs. Sammy Lee Hagar-era songs, and instrumentalsare also allowed. It is unlikely that there will ever be a Jump release, but a Van Halen III codename release is possible.You never know.
Vars (Variables)
As opposed to Facts, variables are names of values (they can be simple scalar values – integers, booleans, strings) orcomplex ones (dictionaries/hashes, lists) that can be used in templates and playbooks. They are declared things, notthings that are inferred from the remote system’s current state or nature (which is what Facts are).
YAML
Ansible does not want to force people to write programming language code to automate infrastructure, so Ansible usesYAML to define playbook configuration languages and also variable files. YAML is nice because it has a minimumof syntax and is very clean and easy for people to skim. It is a good data format for configuration files and humans,but also machine readable. Ansible’s usage of YAML stemmed from Michael’s first use of it inside of Cobbleraround 2006. YAML is fairly popular in the dynamic language community and the format has libraries available forserialization in many languages (Python, Perl, Ruby, etc.).
See also:
Frequently Asked Questions Frequently asked questions
Playbooks An introduction to playbooks
Best Practices Best practices advice
User Mailing List Have a question? Stop by the google group!
irc.freenode.net #ansible IRC chat channel
1.14. Glossary 841
Ansible 1.2 Documentation, Release 0.01
YAML Syntax
This page provides a basic overview of correct YAML syntax, which is how Ansible playbooks (our configurationmanagement language) are expressed.
We use YAML because it is easier for humans to read and write than other common data formats like XML or JSON.Further, there are libraries available in most programming languages for working with YAML.
You may also wish to read Playbooks at the same time to see how this is used in practice.
YAML Basics
For Ansible, nearly every YAML file starts with a list. Each item in the list is a list of key/value pairs, commonlycalled a “hash” or a “dictionary”. So, we need to know how to write lists and dictionaries in YAML.
There’s another small quirk to YAML. All YAML files (regardless of their association with Ansible or not) can op-tionally begin with --- and end with .... This is part of the YAML format and indicates the start and end of adocument.
All members of a list are lines beginning at the same indentation level starting with a "- " (a dash and a space):
---# A list of tasty fruitsfruits:
- Apple- Orange- Strawberry- Mango
...
A dictionary is represented in a simple key: value form (the colon must be followed by a space):
# An employee record- martin:
name: Martin D'vloperjob: Developerskill: Elite
Dictionaries and lists can also be represented in an abbreviated form if you really want to:
---employees:
- martin: {name: Martin D'vloper, job: Developer, skill: Elite}fruits: ['Apple', 'Orange', 'Strawberry', 'Mango]
Ansible doesn’t really use these too much, but you can also specify a boolean value (true/false) in several forms:
create_key: yesneeds_agent: noknows_oop: Truelikes_emacs: TRUEuses_cvs: false
Let’s combine what we learned so far in an arbitrary YAML example. This really has nothing to do with Ansible, butwill give you a feel for the format:
842 Chapter 1. About Ansible
Ansible 1.2 Documentation, Release 0.01
---# An employee recordname: Martin D'vloperjob: Developerskill: Eliteemployed: Truefoods:
- Apple- Orange- Strawberry- Mango
languages:ruby: Elitepython: Elitedotnet: Lame
That’s all you really need to know about YAML to start writing Ansible playbooks.
Gotchas
While YAML is generally friendly, the following is going to result in a YAML syntax error:
foo: somebody said I should put a colon here: so I did
You will want to quote any hash values using colons, like so:
foo: "somebody said I should put a colon here: so I did"
And then the colon will be preserved.
Further, Ansible uses “{{ var }}” for variables. If a value after a colon starts with a “{”, YAML will think it is adictionary, so you must quote it, like so:
foo: "{{ variable }}"
The same applies for strings that start or contain any YAML special characters ‘‘ [] {} : > | ‘‘ .
Boolean conversion is helpful, but this can be a problem when you want a literal yes or other boolean values as a string.In these cases just use quotes:
non_boolean: "yes"other_string: "False"
See also:
Playbooks Learn what playbooks can do and how to write/run them.
YAMLLint YAML Lint (online) helps you debug YAML syntax if you are having problems
Github examples directory Complete playbook files from the github project source
Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
irc.freenode.net #ansible IRC chat channel
1.15. YAML Syntax 843