ansible/playbooks2.html

741 lines
No EOL
39 KiB
HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Advanced Playbooks &mdash; Ansible Documentation</title>
<link rel="stylesheet" href="_static/default.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="_static/bootstrap.css" type="text/css" />
<link rel="stylesheet" href="_static/bootstrap-sphinx.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '',
VERSION: '0.01',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: false
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/bootstrap-dropdown.js"></script>
<script type="text/javascript" src="_static/bootstrap-scrollspy.js"></script>
<link rel="shortcut icon" href="_static/favicon.ico"/>
<link rel="top" title="Ansible Documentation" href="index.html" />
<link rel="next" title="Best Practices" href="bestpractices.html" />
<link rel="prev" title="Playbooks" href="playbooks.html" />
<script type="text/javascript">
(function () {
/**
* Patch TOC list.
*
* Will mutate the underlying span to have a correct ul for nav.
*
* @param $span: Span containing nested UL's to mutate.
* @param minLevel: Starting level for nested lists. (1: global, 2: local).
*/
var patchToc = function ($span, minLevel) {
var $tocList = $("<ul/>").attr('class', "dropdown-menu"),
findA;
// Find all a "internal" tags, traversing recursively.
findA = function ($elem, level) {
var level = level || 0,
$items = $elem.find("> li > a.internal, > ul, > li > ul");
// Iterate everything in order.
$items.each(function (index, item) {
var $item = $(item),
tag = item.tagName.toLowerCase(),
pad = 10 + ((level - minLevel) * 10);
if (tag === 'a' && level >= minLevel) {
// Add to existing padding.
$item.css('padding-left', pad + "px");
// Add list element.
$tocList.append($("<li/>").append($item));
} else if (tag === 'ul') {
// Recurse.
findA($item, level + 1);
}
});
};
// Start construction and return.
findA($span);
// Wipe out old list and patch in new one.
return $span.empty("ul").append($tocList);
};
$(document).ready(function () {
// Patch the global and local TOC's to be bootstrap-compliant.
patchToc($("span.globaltoc"), 1);
patchToc($("span.localtoc"), 2);
// Activate.
$('#topbar').dropdown();
});
}());
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-29861888-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type =
'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' :
'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
</head>
<body>
<div class="topbar" data-scrollspy="scrollspy" >
<div class="topbar-inner">
<div class="container">
<a class="brand" href="index.html">Ansible Documentation</a>
<ul class="nav">
<li><a href="/">Home</A>
<li class="dropdown" data-dropdown="dropdown">
<a href="index.html"
class="dropdown-toggle">Chapter</a>
<span class="globaltoc"><ul class="current">
<li class="toctree-l1"><a class="reference internal" href="gettingstarted.html">Getting Started</a></li>
<li class="toctree-l1"><a class="reference internal" href="patterns.html">Inventory &amp; Patterns</a></li>
<li class="toctree-l1"><a class="reference internal" href="examples.html">Command Line Examples And Next Steps</a></li>
<li class="toctree-l1"><a class="reference internal" href="modules.html">Ansible Modules</a></li>
<li class="toctree-l1"><a class="reference internal" href="YAMLSyntax.html">YAML Syntax</a></li>
<li class="toctree-l1"><a class="reference internal" href="playbooks.html">Playbooks</a></li>
<li class="toctree-l1 current"><a class="current reference internal" href="">Advanced Playbooks</a></li>
<li class="toctree-l1"><a class="reference internal" href="bestpractices.html">Best Practices</a></li>
<li class="toctree-l1"><a class="reference internal" href="api.html">API &amp; Integrations</a></li>
<li class="toctree-l1"><a class="reference internal" href="moduledev.html">Module Development</a></li>
</ul>
</span>
</li>
<li class="dropdown" data-dropdown="dropdown">
<a href="#"
class="dropdown-toggle">Page</a>
<span class="localtoc"><ul>
<li><a class="reference internal" href="#">Advanced Playbooks</a><ul>
<li><a class="reference internal" href="#tags">Tags</a></li>
<li><a class="reference internal" href="#playbooks-including-playbooks">Playbooks Including Playbooks</a></li>
<li><a class="reference internal" href="#ignoring-failed-commands">Ignoring Failed Commands</a></li>
<li><a class="reference internal" href="#accessing-complex-variable-data">Accessing Complex Variable Data</a></li>
<li><a class="reference internal" href="#accessing-information-about-other-hosts">Accessing Information About Other Hosts</a></li>
<li><a class="reference internal" href="#variable-file-seperation">Variable File Seperation</a></li>
<li><a class="reference internal" href="#prompting-for-sensitive-data">Prompting For Sensitive Data</a></li>
<li><a class="reference internal" href="#passing-variables-on-the-command-line">Passing Variables On The Command Line</a></li>
<li><a class="reference internal" href="#conditional-execution">Conditional Execution</a></li>
<li><a class="reference internal" href="#conditional-imports">Conditional Imports</a></li>
<li><a class="reference internal" href="#loop-shorthand">Loop Shorthand</a></li>
<li><a class="reference internal" href="#selecting-files-and-templates-based-on-variables">Selecting Files And Templates Based On Variables</a></li>
<li><a class="reference internal" href="#asynchronous-actions-and-polling">Asynchronous Actions and Polling</a></li>
<li><a class="reference internal" href="#local-playbooks">Local Playbooks</a></li>
<li><a class="reference internal" href="#turning-off-facts">Turning Off Facts</a></li>
<li><a class="reference internal" href="#pull-mode-playbooks">Pull-Mode Playbooks</a></li>
<li><a class="reference internal" href="#register-variables">Register Variables</a></li>
<li><a class="reference internal" href="#rolling-updates">Rolling Updates</a></li>
<li><a class="reference internal" href="#delegation">Delegation</a></li>
<li><a class="reference internal" href="#understanding-variable-precedence">Understanding Variable Precedence</a></li>
<li><a class="reference internal" href="#style-points">Style Points</a></li>
</ul>
</li>
</ul>
</span>
</li>
</ul>
<ul class="nav secondary-nav">
<form class="pull-left" action="search.html" method="get">
<input type="text" name="q" placeholder="Search" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</ul>
</div>
</div>
</div>
<div class="container">
<div class="section" id="advanced-playbooks">
<h1><a class="toc-backref" href="#contents">Advanced Playbooks</a><a class="headerlink" href="#advanced-playbooks" title="Permalink to this headline"></a></h1>
<p>Here are some advanced features of the playbooks language. Using all of these features
are not neccessary, but many of them will prove useful. If a feature doesn&#8217;t seem immediately
relevant, feel free to skip it. For many people, the features documented in <cite>playbooks</cite> will
be 90% or more of what they use in Ansible.</p>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#advanced-playbooks" id="id1">Advanced Playbooks</a><ul>
<li><a class="reference internal" href="#tags" id="id2">Tags</a></li>
<li><a class="reference internal" href="#playbooks-including-playbooks" id="id3">Playbooks Including Playbooks</a></li>
<li><a class="reference internal" href="#ignoring-failed-commands" id="id4">Ignoring Failed Commands</a></li>
<li><a class="reference internal" href="#accessing-complex-variable-data" id="id5">Accessing Complex Variable Data</a></li>
<li><a class="reference internal" href="#accessing-information-about-other-hosts" id="id6">Accessing Information About Other Hosts</a></li>
<li><a class="reference internal" href="#variable-file-seperation" id="id7">Variable File Seperation</a></li>
<li><a class="reference internal" href="#prompting-for-sensitive-data" id="id8">Prompting For Sensitive Data</a></li>
<li><a class="reference internal" href="#passing-variables-on-the-command-line" id="id9">Passing Variables On The Command Line</a></li>
<li><a class="reference internal" href="#conditional-execution" id="id10">Conditional Execution</a></li>
<li><a class="reference internal" href="#conditional-imports" id="id11">Conditional Imports</a></li>
<li><a class="reference internal" href="#loop-shorthand" id="id12">Loop Shorthand</a></li>
<li><a class="reference internal" href="#selecting-files-and-templates-based-on-variables" id="id13">Selecting Files And Templates Based On Variables</a></li>
<li><a class="reference internal" href="#asynchronous-actions-and-polling" id="id14">Asynchronous Actions and Polling</a></li>
<li><a class="reference internal" href="#local-playbooks" id="id15">Local Playbooks</a></li>
<li><a class="reference internal" href="#turning-off-facts" id="id16">Turning Off Facts</a></li>
<li><a class="reference internal" href="#pull-mode-playbooks" id="id17">Pull-Mode Playbooks</a></li>
<li><a class="reference internal" href="#register-variables" id="id18">Register Variables</a></li>
<li><a class="reference internal" href="#rolling-updates" id="id19">Rolling Updates</a></li>
<li><a class="reference internal" href="#delegation" id="id20">Delegation</a></li>
<li><a class="reference internal" href="#understanding-variable-precedence" id="id21">Understanding Variable Precedence</a></li>
<li><a class="reference internal" href="#style-points" id="id22">Style Points</a></li>
</ul>
</li>
</ul>
</div>
<div class="section" id="tags">
<h2><a class="toc-backref" href="#contents">Tags</a><a class="headerlink" href="#tags" title="Permalink to this headline"></a></h2>
<p class="versionadded">
<span class="versionmodified">New in version 0.6.</span></p>
<p>If you have a large playbook it may become useful to be able to run a
specific part of the configuration. Both plays and tasks support a
&#8220;tags:&#8221; attribute for this reason.</p>
<p>Example:</p>
<div class="highlight-python"><pre>tasks:
- action: yum name=$item state=installed
with_items:
- httpd
- memcached
tags:
- packages
- action: template src=templates/src.j2 dest=/etc/foo.conf
tags:
- configuration</pre>
</div>
<p>If you wanted to just run the &#8220;configuration&#8221; and &#8220;packages&#8221; part of a very long playbook, you could do this:</p>
<div class="highlight-python"><pre>ansible-playbook example.yml --tags "configuration,packages"</pre>
</div>
</div>
<div class="section" id="playbooks-including-playbooks">
<h2><a class="toc-backref" href="#contents">Playbooks Including Playbooks</a><a class="headerlink" href="#playbooks-including-playbooks" title="Permalink to this headline"></a></h2>
<p class="versionadded">
<span class="versionmodified">New in version 0.6.</span></p>
<p>To further advance the concept of include files, playbook files can
include other playbook files. Suppose you define the behavior of all
your webservers in &#8220;webservers.yml&#8221; and all your database servers in
&#8220;dbservers.yml&#8221;. You can create a &#8220;site.yml&#8221; that would reconfigure
all of your systems like this:</p>
<div class="highlight-python"><pre>----
- include: playbooks/webservers.yml
- include: playbooks/dbservers.yml</pre>
</div>
<p>This concept works great with tags to rapidly select exactly what plays you want to run, and exactly
what parts of those plays.</p>
</div>
<div class="section" id="ignoring-failed-commands">
<h2><a class="toc-backref" href="#contents">Ignoring Failed Commands</a><a class="headerlink" href="#ignoring-failed-commands" title="Permalink to this headline"></a></h2>
<p class="deprecated">
<span class="versionmodified">Deprecated since version 0.6.</span></p>
<p>Generally playbooks will stop executing any more steps on a host that
has a failure. Sometimes, though, you want to continue on. To do so,
write a task that looks like this:</p>
<div class="highlight-python"><pre>- name: this will not be counted as a failure
action: command /bin/false
ignore_errors: True</pre>
</div>
</div>
<div class="section" id="accessing-complex-variable-data">
<h2><a class="toc-backref" href="#contents">Accessing Complex Variable Data</a><a class="headerlink" href="#accessing-complex-variable-data" title="Permalink to this headline"></a></h2>
<p>Some provided facts, like networking information, are made available as nested data structures. To access
them a simple &#8216;$foo&#8217; is not sufficient, but it is still easy to do. Here&#8217;s how we get an IP address:</p>
<div class="highlight-python"><pre>${ansible_eth0.ipv4.address}</pre>
</div>
<p>It is also possible to access variables whose elements are arrays:</p>
<div class="highlight-python"><pre>${somelist[0]}</pre>
</div>
<p>And the array and hash reference syntaxes can be mixed.</p>
<p>In templates, the simple access form still holds, but they can also be accessed from Jinja2 in more Python-native ways if
that is preferred:</p>
<div class="highlight-python"><pre>{{ ansible_eth0["ipv4"]["address"] }}</pre>
</div>
</div>
<div class="section" id="accessing-information-about-other-hosts">
<h2><a class="toc-backref" href="#contents">Accessing Information About Other Hosts</a><a class="headerlink" href="#accessing-information-about-other-hosts" title="Permalink to this headline"></a></h2>
<p>If your database server wants to check the value of a &#8216;fact&#8217; from another node, or an inventory variable
assigned to another node, it&#8217;s easy to do so within a template or even an action line:</p>
<div class="highlight-python"><pre>${hostvars.hostname.factname}</pre>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">No database or other complex system is required to exchange data
between hosts. The hosts that you want to reference data from must
be included in either the current play or any previous play.</p>
</div>
<p>Additionally, <em>group_names</em> is a list (array) of all the groups the current host is in. This can be used in templates using Jinja2 syntax to make template source files that vary based on the group membership (or role) of the host:</p>
<div class="highlight-python"><pre>{% if 'webserver' in group_names %}
# some part of a configuration file that only applies to webservers
{% endif %}</pre>
</div>
<p><em>groups</em> 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:</p>
<div class="highlight-python"><pre>{% for host in groups['app_servers'] %}
# something that applies to all app servers.
{% endfor %}</pre>
</div>
<p>Use cases include pointing a frontend proxy server to all of the app servers, setting up the correct firewall rules between servers, etc.</p>
<p><em>inventory_hostname</em> is the name of the hostname as configured in Ansible&#8217;s inventory host file. This can
be useful for when you don&#8217;t want to rely on the discovered hostname <cite>ansible_hostname</cite> or for other mysterious
reasons. If you have a long FQDN, <em>inventory_hostname_short</em> (in Ansible 0.6) also contains the part up to the first
period.</p>
<p>Don&#8217;t worry about any of this unless you think you need it. You&#8217;ll know when you do.</p>
</div>
<div class="section" id="variable-file-seperation">
<h2><a class="toc-backref" href="#contents">Variable File Seperation</a><a class="headerlink" href="#variable-file-seperation" title="Permalink to this headline"></a></h2>
<p>It&#8217;s a great idea to keep your playbooks under source control, but
you may wish to make the playbook source public while keeping certain
important variables private. Similarly, sometimes you may just
want to keep certain information in different files, away from
the main playbook.</p>
<p>You can do this by using an external variables file, or files, just like this:</p>
<div class="highlight-python"><pre>---
- hosts: all
user: root
vars:
favcolor: blue
vars_files:
- /vars/external_vars.yml
tasks:
- name: this is just a placeholder
action: command /bin/echo foo</pre>
</div>
<p>This removes the risk of sharing sensitive data with others when
sharing your playbook source with them.</p>
<p>The contents of each variables file is a simple YAML dictionary, like this:</p>
<div class="highlight-python"><pre>---
# in the above example, this would be vars/external_vars.yml
somevar: somevalue
password: magic</pre>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">It&#8217;s also possible to keep per-host and per-group variables in very
similar files, this is covered in <a class="reference internal" href="patterns.html#patterns"><em>Inventory &amp; Patterns</em></a>.</p>
</div>
</div>
<div class="section" id="prompting-for-sensitive-data">
<h2><a class="toc-backref" href="#contents">Prompting For Sensitive Data</a><a class="headerlink" href="#prompting-for-sensitive-data" title="Permalink to this headline"></a></h2>
<p>You may wish to prompt the user for certain input, and can
do so with the similarly named &#8216;vars_prompt&#8217; section. This has uses
beyond security, for instance, you may use the same playbook for all
software releases and would prompt for a particular release version
in a push-script:</p>
<div class="highlight-python"><pre>---
- hosts: all
user: root
vars:
from: "camelot"
vars_prompt:
name: "what is your name?"
quest: "what is your quest?"
favcolor: "what is your favorite color?"</pre>
</div>
<p>There are full examples of both of these items in the github examples/playbooks directory.</p>
<p>An alternative form of vars_prompt allows for hiding input from the user, and may later support
some other options, but otherwise works equivalently:</p>
<div class="highlight-python"><pre>vars_prompt:
- name: "some_password"
prompt: "Enter password"
private: True
- name: "release_version"
prompt: "Product release version"
private: False</pre>
</div>
</div>
<div class="section" id="passing-variables-on-the-command-line">
<h2><a class="toc-backref" href="#contents">Passing Variables On The Command Line</a><a class="headerlink" href="#passing-variables-on-the-command-line" title="Permalink to this headline"></a></h2>
<p>In addition to <cite>vars_prompt</cite> and <cite>vars_files</cite>, 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 the application to deploy:</p>
<div class="highlight-python"><pre>ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo"</pre>
</div>
<p>This is useful, for, among other things, setting the hosts group or the user for the playbook.</p>
<p>Example:</p>
<div class="highlight-python"><pre>-----
- user: $user
hosts: $hosts
tasks:
- ...
ansible-playbook release.yml --extra-vars "hosts=vipers user=starbuck"</pre>
</div>
</div>
<div class="section" id="conditional-execution">
<h2><a class="toc-backref" href="#contents">Conditional Execution</a><a class="headerlink" href="#conditional-execution" title="Permalink to this headline"></a></h2>
<p>Sometimes you will want to skip a particular step on a particular host. This could be something
as simple as not installing a certain package if the operating system is a particular version,
or it could be something like performing some cleanup steps if a filesystem is getting full.</p>
<p>This is easy to do in Ansible, with the <cite>only_if</cite> clause, which actually is a Python expression.
Don&#8217;t panic &#8211; it&#8217;s actually pretty simple:</p>
<div class="highlight-python"><pre>vars:
favcolor: blue
is_favcolor_blue: "'$favcolor' == 'blue'"
is_centos: "'$facter_operatingsystem' == 'CentOS'"
tasks:
- name: "shutdown if my favorite color is blue"
action: command /sbin/shutdown -t now
only_if: '$is_favcolor_blue'</pre>
</div>
<p>Variables from tools like <cite>facter</cite> and <cite>ohai</cite> can be used here, if installed, or you can
use variables that bubble up from ansible, which many are provided by the <a class="reference internal" href="modules.html#setup"><em>setup</em></a> module. As a reminder,
these variables are prefixed, so it&#8217;s <cite>$facter_operatingsystem</cite>, not <cite>$operatingsystem</cite>. Ansible&#8217;s
built in variables are prefixed with <cite>ansible_</cite>.</p>
<p>The only_if expression is actually a tiny small bit of Python, so be sure to quote variables and make something
that evaluates to <cite>True</cite> or <cite>False</cite>. It is a good idea to use &#8216;vars_files&#8217; instead of &#8216;vars&#8217; to define
all of your conditional expressions in a way that makes them very easy to reuse between plays
and playbooks.</p>
<p>You cannot use live checks here, like &#8216;os.path.exists&#8217;, so don&#8217;t try.</p>
<p>It&#8217;s also easy to provide your own facts if you want, which is covered in <a class="reference internal" href="moduledev.html"><em>Module Development</em></a>. To run them, just
make a call to your own custom fact gathering module at the top of your list of tasks, and variables returned
there will be accessible to future tasks:</p>
<div class="highlight-python"><pre>tasks:
- name: gather site specific fact data
action: site_facts
- action: command echo ${my_custom_fact_can_be_used_now}</pre>
</div>
</div>
<div class="section" id="conditional-imports">
<h2><a class="toc-backref" href="#contents">Conditional Imports</a><a class="headerlink" href="#conditional-imports" title="Permalink to this headline"></a></h2>
<p>Sometimes you will want to do certain things differently in a playbook based on certain criteria.
Having one playbook that works on multiple platforms and OS versions is a good example.</p>
<p>As an example, the name of the Apache package may be different between CentOS and Debian,
but it is easily handled with a minimum of syntax in an Ansible Playbook:</p>
<div class="highlight-python"><pre>---
- hosts: all
user: root
vars_files:
- "vars/common.yml"
- [ "vars/$facter_operatingsystem.yml", "vars/os_defaults.yml" ]
tasks:
- name: make sure apache is running
action: service name=$apache state=running</pre>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The variable (<cite>$facter_operatingsystem</cite>) is being interpolated into
the list of filenames being defined for vars_files.</p>
</div>
<p>As a reminder, the various YAML files contain just keys and values:</p>
<div class="highlight-python"><pre>---
# for vars/CentOS.yml
apache: httpd
somethingelse: 42</pre>
</div>
<p>How does this work? If the operating system was &#8216;CentOS&#8217;, the first file Ansible would try to import
would be &#8216;vars/CentOS.yml&#8217;, followed up by &#8216;/vars/os_defaults.yml&#8217; if that file
did not exist. If no files in the list were found, an error would be raised.
On Debian, it would instead first look towards &#8216;vars/Debian.yml&#8217; instead of &#8216;vars/CentOS.yml&#8217;, before
falling back on &#8216;vars/os_defaults.yml&#8217;. Pretty simple.</p>
<p>To use this conditional import feature, you&#8217;ll need facter or ohai installed prior to running the playbook, but
you can of course push this out with Ansible if you like:</p>
<div class="highlight-python"><pre># for facter
ansible -m yum -a "pkg=facter ensure=installed"
ansible -m yum -a "pkg=ruby-json ensure=installed"
# for ohai
ansible -m yum -a "pkg=ohai ensure=installed"</pre>
</div>
<p>Ansible&#8217;s approach to configuration &#8211; seperating variables from tasks, keeps your playbooks
from turning into arbitrary code with ugly nested ifs, conditionals, and so on - and results
in more streamlined &amp; auditable configuration rules &#8211; especially because there are a
minimum of decision points to track.</p>
</div>
<div class="section" id="loop-shorthand">
<h2><a class="toc-backref" href="#contents">Loop Shorthand</a><a class="headerlink" href="#loop-shorthand" title="Permalink to this headline"></a></h2>
<p>To save some typing, repeated tasks can be written in short-hand like so:</p>
<div class="highlight-python"><pre>- name: add user $item
action: user name=$item state=present groups=wheel
with_items:
- testuser1
- testuser2</pre>
</div>
<p>If you have defined a YAML list in a variables file, or the &#8216;vars&#8217; section, you can also do:</p>
<div class="highlight-python"><pre>with_items: $somelist</pre>
</div>
<p>The above would be the equivalent of:</p>
<div class="highlight-python"><pre>- name: add user testuser1
action: user name=testuser1 state=present groups=wheel
- name: add user testuser2
action: user name=testuser2 state=present groups=wheel</pre>
</div>
<p>In a future release, the yum and apt modules will use with_items to execute fewer package
manager transactions.</p>
</div>
<div class="section" id="selecting-files-and-templates-based-on-variables">
<h2><a class="toc-backref" href="#contents">Selecting Files And Templates Based On Variables</a><a class="headerlink" href="#selecting-files-and-templates-based-on-variables" title="Permalink to this headline"></a></h2>
<p>Sometimes a configuration file you want to copy, or a template you will use may depend on a variable.
The following construct selects the first available file appropriate for the variables of a given host,
which is often much cleaner than putting a lot of if conditionals in a template.</p>
<p>The following example shows how to template out a configuration file that was very different between, say,
CentOS and Debian:</p>
<div class="highlight-python"><pre>- name: template a file
action: template src=$item dest=/etc/myapp/foo.conf
first_available_file:
- /srv/templates/myapp/${ansible_distribution}.conf
- /srv/templates/myapp/default.conf</pre>
</div>
</div>
<div class="section" id="asynchronous-actions-and-polling">
<h2><a class="toc-backref" href="#contents">Asynchronous Actions and Polling</a><a class="headerlink" href="#asynchronous-actions-and-polling" title="Permalink to this headline"></a></h2>
<p>By default tasks in playbooks block, meaning the connections stay open
until the task is done on each node. If executing playbooks with
a small parallelism value (aka <tt class="docutils literal"><span class="pre">--forks</span></tt>), you may wish that long
running operations can go faster. The easiest way to do this is
to kick them off all at once and then poll until they are done.</p>
<p>You will also want to use asynchronous mode on very long running
operations that might be subject to timeout.</p>
<p>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 <cite>poll</cite>:</p>
<div class="highlight-python"><pre>---
- hosts: all
user: root
tasks:
- name: simulate long running op (15 sec), wait for up to 45, poll every 5
action: command /bin/sleep 15
async: 45
poll: 5</pre>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">There is no default for the async time limit. If you leave off the
&#8216;async&#8217; keyword, the task runs synchronously, which is Ansible&#8217;s
default.</p>
</div>
<p>Alternatively, if you do not need to wait on the task to complete, you may
&#8220;fire and forget&#8221; by specifying a poll value of 0:</p>
<div class="highlight-python"><pre>---
- hosts: all
user: root
tasks:
- name: simulate long running op, allow to run for 45, fire and forget
action: command /bin/sleep 15
async: 45
poll: 0</pre>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">You shouldn&#8217;t &#8220;fire and forget&#8221; with operations that require
exclusive locks, such as yum transactions, if you expect to run other
commands later in the playbook against those same resources.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Using a higher value for <tt class="docutils literal"><span class="pre">--forks</span></tt> will result in kicking off asynchronous
tasks even faster. This also increases the efficiency of polling.</p>
</div>
</div>
<div class="section" id="local-playbooks">
<h2><a class="toc-backref" href="#contents">Local Playbooks</a><a class="headerlink" href="#local-playbooks" title="Permalink to this headline"></a></h2>
<p>It may be useful to use a playbook locally, rather than by connecting over SSH. This can be useful
for assuring the configuration of a system by putting a playbook on a crontab. This may also be used
to run a playbook inside a OS installer, such as an Anaconda kickstart.</p>
<p>To run an entire playbook locally, just set the &#8220;hosts:&#8221; line to &#8220;hosts:127.0.0.1&#8221; and then run the playbook like so:</p>
<div class="highlight-python"><pre>ansible-playbook playbook.yml --connection=local</pre>
</div>
<p>Alternatively, a local connection can be used in a single playbook play, even if other plays in the playbook
use the default remote connection type:</p>
<div class="highlight-python"><pre>hosts: 127.0.0.1
connection: local</pre>
</div>
</div>
<div class="section" id="turning-off-facts">
<h2><a class="toc-backref" href="#contents">Turning Off Facts</a><a class="headerlink" href="#turning-off-facts" title="Permalink to this headline"></a></h2>
<p>If you know you don&#8217;t need any fact data about your hosts, and know everything about your systems centrally, you
can 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:</p>
<div class="highlight-python"><pre>- hosts: whatever
gather_facts: False</pre>
</div>
</div>
<div class="section" id="pull-mode-playbooks">
<h2><a class="toc-backref" href="#contents">Pull-Mode Playbooks</a><a class="headerlink" href="#pull-mode-playbooks" title="Permalink to this headline"></a></h2>
<p>The use of playbooks in local mode (above) is made extremely powerful with the addition of <cite>ansible-pull</cite>.
A script for setting up ansible-pull is provided in the examples/playbooks directory of the source
checkout.</p>
<p>The basic idea is to use Ansible to set up a remote copy of ansible on each managed node, each set to run via
cron and update playbook source via git. This interverts the default push architecture of ansible into a pull
architecture, which has near-limitless scaling potential. The setup playbook can be tuned to change
the cron frequency, logging locations, and parameters to ansible-pull.</p>
<p>This is useful both for extreme scale-out as well as periodic remediation. Usage of the &#8216;fetch&#8217; module to retrieve
logs from ansible-pull runs would be an excellent way to gather and analyze remote logs from ansible-pull.</p>
</div>
<div class="section" id="register-variables">
<h2><a class="toc-backref" href="#contents">Register Variables</a><a class="headerlink" href="#register-variables" title="Permalink to this headline"></a></h2>
<p class="versionadded">
<span class="versionmodified">New in version 0.7.</span></p>
<p>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 the command module in this way can in many ways eliminate the need to write site specific facts, for
instance, you could test for the existance of a particular program.</p>
<p>The &#8216;register&#8217; keyword decides what variable to save a result in. The resulting variables can be used in templates, action lines, or only_if statements. It looks like this (in an obviously trivial example):</p>
<div class="highlight-python"><pre>- name: test play
hosts: all
tasks:
- action: shell cat /etc/motd
register: motd_contents
- action: shell echo "motd contains the word hi"
only_if: "'${motd_contents.stdout}'.find('hi') != -1"</pre>
</div>
</div>
<div class="section" id="rolling-updates">
<h2><a class="toc-backref" href="#contents">Rolling Updates</a><a class="headerlink" href="#rolling-updates" title="Permalink to this headline"></a></h2>
<p class="versionadded">
<span class="versionmodified">New in version 0.7.</span></p>
<p>By default ansible will try to manage all of the machines referenced in a play in parallel. For a rolling updates
use case, you can define how many hosts ansible should manage at a single time by using the &#8216;&#8217;serial&#8217;&#8217; keyword:</p>
<div class="highlight-python"><pre>- name: test play
hosts: webservers
serial: 3</pre>
</div>
<p>In the above example, if we had 100 hosts, 3 hosts in the group &#8216;webservers&#8217;
would complete the play completely before moving on to the next 3 hosts.</p>
</div>
<div class="section" id="delegation">
<h2><a class="toc-backref" href="#contents">Delegation</a><a class="headerlink" href="#delegation" title="Permalink to this headline"></a></h2>
<p class="versionadded">
<span class="versionmodified">New in version 0.7.</span></p>
<p>If you want to perform a task on one host with reference to other hosts, use the &#8216;delegate_to&#8217; keyword on a task.
This is ideal for placing nodes in a load balanced pool, or removing them. It is also very useful for controlling
outage windows. Using this with the &#8216;serial&#8217; keyword to control the number of hosts executing at one time is also
a good idea:</p>
<div class="highlight-python"><pre>---
- hosts: webservers
serial: 5
tasks:
- name: take out of load balancer pool
action: command /usr/bin/take_out_of_pool $inventory_hostname
delegate_to: 127.0.0.1
- name: actual steps would go here
action: yum name=acme-web-stack state=latest
- name: add back to load balancer pool
action: command /usr/bin/add_back_to_pool $inventory_hostname
delegate_to: 127.0.0.1</pre>
</div>
<p>Here is the same playbook as above, but using the shorthand syntax,
&#8216;local_action&#8217;, for delegating to 127.0.0.1:</p>
<div class="highlight-python"><pre>---
# ...
tasks:
- name: take out of load balancer pool
local_action: command /usr/bin/take_out_of_pool $inventory_hostname
# ...
- name: add back to load balancer pool
local_action: command /usr/bin/add_back_to_pool $inventory_hostname</pre>
</div>
</div>
<div class="section" id="understanding-variable-precedence">
<h2><a class="toc-backref" href="#contents">Understanding Variable Precedence</a><a class="headerlink" href="#understanding-variable-precedence" title="Permalink to this headline"></a></h2>
<p>You have already learned about inventory host and group variables, &#8216;vars&#8217;, and &#8216;vars_files&#8217;.</p>
<p>If a variable name is defined in more than one place with the same name, priority is as follows
to determine which place sets the value of the variable.</p>
<ol class="arabic simple">
<li>Variables loaded from YAML files mentioned in &#8216;vars_files&#8217; in a playbook.</li>
<li>&#8216;vars&#8217; as defined in the playbook.</li>
<li>facts, whether built in or custom, or variables assigned from the &#8216;register&#8217; keyword.</li>
<li>variables passed to parameterized task include statements.</li>
<li>Host variables from inventory.</li>
<li>Group variables from inventory, in order of least specific group to most specific.</li>
</ol>
<p>Therefore, if you want to set a default value for something you wish to override somewhere else, the best
place to set such a default is in a group variable.</p>
</div>
<div class="section" id="style-points">
<h2><a class="toc-backref" href="#contents">Style Points</a><a class="headerlink" href="#style-points" title="Permalink to this headline"></a></h2>
<p>Ansible playbooks are colorized. If you do not like this, set the ANSIBLE_NOCOLOR=1 environment variable.</p>
<p>Ansible playbooks also look more impressive with cowsay installed, and we encourage installing this package.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference internal" href="YAMLSyntax.html"><em>YAML Syntax</em></a></dt>
<dd>Learn about YAML syntax</dd>
<dt><a class="reference internal" href="playbooks.html"><em>Playbooks</em></a></dt>
<dd>Review the basic playbook features</dd>
<dt><a class="reference internal" href="bestpractices.html"><em>Best Practices</em></a></dt>
<dd>Various tips about playbooks in the real world</dd>
<dt><a class="reference internal" href="modules.html"><em>Ansible Modules</em></a></dt>
<dd>Learn about available modules</dd>
<dt><a class="reference internal" href="moduledev.html"><em>Module Development</em></a></dt>
<dd>Learn how to extend Ansible by writing your own modules</dd>
<dt><a class="reference internal" href="patterns.html"><em>Inventory &amp; Patterns</em></a></dt>
<dd>Learn about how to select hosts</dd>
<dt><a class="reference external" href="https://github.com/ansible/ansible/tree/devel/examples/playbooks">Github examples directory</a></dt>
<dd>Complete playbook files from the github project source</dd>
<dt><a class="reference external" href="http://groups.google.com/group/ansible-project">Mailing List</a></dt>
<dd>Questions? Help? Ideas? Stop by the list on Google Groups</dd>
</dl>
</div>
</div>
</div>
<br/>
</div>
<footer class="footer">
<div class="container">
<p>
<p>
&copy; Copyright 2012 Michael DeHaan.<br/>
Last updated on Sep 27, 2012.<br/>
</p>
</div>
</footer>
</body>
</html>