PageRenderTime 55ms CodeModel.GetById 15ms app.highlight 28ms RepoModel.GetById 1ms app.codeStats 0ms

/docsite/rst/playbooks_intro.rst

https://github.com/ajanthanm/ansible
ReStructuredText | 395 lines | 282 code | 113 blank | 0 comment | 0 complexity | 80a15cabba00f086e78c917c6483e3b5 MD5 | raw file
  1Intro to Playbooks
  2==================
  3
  4.. _about_playbooks:
  5
  6About Playbooks
  7```````````````
  8
  9Playbooks are a completely different way to use ansible than in adhoc task execution mode, and are
 10particularly powerful. 
 11
 12Simply put, playbooks are the basis for a really simple configuration management and multi-machine deployment system,
 13unlike any that already exist, and one that is very well suited to deploying complex applications.
 14
 15Playbooks can declare configurations, but they can also orchestrate steps of
 16any manual ordered process, even as different steps must bounce back and forth
 17between sets of machines in particular orders.  They can launch tasks
 18synchronously or asynchronously.
 19
 20While you might run the main /usr/bin/ansible program for ad-hoc
 21tasks, playbooks are more likely to be kept in source control and used
 22to push out your configuration or assure the configurations of your
 23remote systems are in spec.
 24
 25There are also some full sets of playbooks illustrating a lot of these techniques in the
 26`ansible-examples repository <https://github.com/ansible/ansible-examples>`_.  We'd recommend
 27looking at these in another tab as you go along.
 28
 29There are also many jumping off points after you learn playbooks, so hop back to the documentation
 30index after you're done with this section.
 31
 32.. _playbook_language_example:
 33
 34Playbook Language Example
 35`````````````````````````
 36
 37Playbooks are expressed in YAML format (see :doc:`YAMLSyntax`) and have a minimum of syntax, which intentionally
 38tries to not be a programming language or script, but rather a model of a configuration or a process.
 39
 40Each playbook is composed of one or more 'plays' in a list.
 41
 42The goal of a play is to map a group of hosts to some well defined roles, represented by
 43things ansible calls tasks.  At a basic level, a task is nothing more than a call
 44to an ansible module, which you should have learned about in earlier chapters.
 45
 46By composing a playbook of multiple 'plays', it is possible to
 47orchestrate multi-machine deployments, running certain steps on all
 48machines in the webservers group, then certain steps on the database
 49server group, then more commands back on the webservers group, etc.
 50
 51"plays" are more or less a sports analogy.  You can have quite a lot of plays that affect your systems
 52to do different things.  It's not as if you were just defining one particular state or model, and you
 53can run different plays at different times.  
 54
 55For starters, here's a playbook that contains just one play::
 56
 57    ---
 58    - hosts: webservers
 59      vars:
 60        http_port: 80
 61        max_clients: 200
 62      remote_user: root
 63      tasks:
 64      - name: ensure apache is at the latest version
 65        yum: pkg=httpd state=latest
 66      - name: write the apache config file
 67        template: src=/srv/httpd.j2 dest=/etc/httpd.conf
 68        notify:
 69        - restart apache
 70      - name: ensure apache is running
 71        service: name=httpd state=started
 72      handlers:
 73        - name: restart apache
 74          service: name=httpd state=restarted
 75
 76Below, we'll break down what the various features of the playbook language are.
 77
 78.. _playbook_basics:
 79
 80Basics
 81``````
 82
 83.. _playbook_hosts_and_users:
 84
 85Hosts and Users
 86+++++++++++++++
 87
 88For each play in a playbook, you get to choose which machines in your infrastructure
 89to target and what remote user to complete the steps (called tasks) as.
 90
 91The `hosts` line is a list of one or more groups or host patterns,
 92separated by colons, as described in the :doc:`intro_patterns`
 93documentation.  The `remote_user` is just the name of the user account::
 94
 95    ---
 96    - hosts: webservers
 97      remote_user: root
 98
 99.. note::
100
101    The `remote_user` parameter was formerly called just `user`. It was renamed in Ansible 1.4 to make it more distinguishable from the `user` module (used to create users on remote systems).
102
103Remote users can also be defined per task::
104
105    ---
106    - hosts: webservers
107      remote_user: root
108      tasks:
109        - name: test connection
110          ping:
111          remote_user: yourname
112
113.. note::
114
115    The `remote_user` parameter for tasks was added in 1.4.
116
117
118Support for running things from sudo is also available::
119
120    ---
121    - hosts: webservers
122      remote_user: yourname
123      sudo: yes
124
125You can also use sudo on a particular task instead of the whole play::
126
127    ---
128    - hosts: webservers
129      remote_user: yourname
130      tasks:
131        - service: name=nginx state=started
132          sudo: yes
133
134
135You can also login as you, and then sudo to different users than root::
136
137    ---
138    - hosts: webservers
139      remote_user: yourname
140      sudo: yes
141      sudo_user: postgres
142
143If you need to specify a password to sudo, run `ansible-playbook` with ``--ask-sudo-pass`` (`-K`).
144If you run a sudo playbook and the playbook seems to hang, it's probably stuck at the sudo prompt.
145Just `Control-C` to kill it and run it again with `-K`.
146
147.. important::
148
149   When using `sudo_user` to a user other than root, the module
150   arguments are briefly written into a random tempfile in /tmp.
151   These are deleted immediately after the command is executed.  This
152   only occurs when sudoing from a user like 'bob' to 'timmy', not
153   when going from 'bob' to 'root', or logging in directly as 'bob' or
154   'root'.  If this concerns you that this data is briefly readable
155   (not writable), avoid transferring uncrypted passwords with
156   `sudo_user` set.  In other cases, '/tmp' is not used and this does
157   not come into play. Ansible also takes care to not log password
158   parameters.
159
160.. _tasks_list:
161
162Tasks list
163++++++++++
164
165Each play contains a list of tasks.  Tasks are executed in order, one
166at a time, against all machines matched by the host pattern,
167before moving on to the next task.  It is important to understand that, within a play,
168all hosts are going to get the same task directives.  It is the purpose of a play to map
169a selection of hosts to tasks.
170
171When running the playbook, which runs top to bottom, hosts with failed tasks are
172taken out of the rotation for the entire playbook.  If things fail, simply correct the playbook file and rerun.
173
174The goal of each task is to execute a module, with very specific arguments.
175Variables, as mentioned above, can be used in arguments to modules.
176
177Modules are 'idempotent', meaning if you run them
178again, they will make only the changes they must in order to bring the
179system to the desired state.  This makes it very safe to rerun
180the same playbook multiple times.  They won't change things
181unless they have to change things.
182
183The `command` and `shell` modules will typically rerun the same command again,
184which is totally ok if the command is something like
185'chmod' or 'setsebool', etc.  Though there is a 'creates' flag available which can
186be used to make these modules also idempotent.
187
188Every task should have a `name`, which is included in the output from
189running the playbook.   This is output for humans, so it is
190nice to have reasonably good descriptions of each task step.  If the name
191is not provided though, the string fed to 'action' will be used for
192output.
193
194Tasks can be declared using the legacy "action: module options" format, but 
195it is recommended that you use the more conventional "module: options" format.
196This recommended format is used throughout the documentation, but you may
197encounter the older format in some playbooks.
198
199Here is what a basic task looks like, as with most modules,
200the service module takes key=value arguments::
201
202   tasks:
203     - name: make sure apache is running
204       service: name=httpd state=running
205
206The `command` and `shell` modules are the only modules that just take a list
207of arguments and don't use the key=value form.  This makes
208them work as simply as you would expect::
209
210   tasks:
211     - name: disable selinux
212       command: /sbin/setenforce 0
213
214The command and shell module care about return codes, so if you have a command
215whose successful exit code is not zero, you may wish to do this::
216
217   tasks:
218     - name: run this command and ignore the result
219       shell: /usr/bin/somecommand || /bin/true
220
221Or this::
222
223   tasks:
224     - name: run this command and ignore the result
225       shell: /usr/bin/somecommand
226       ignore_errors: True
227
228
229If the action line is getting too long for comfort you can break it on
230a space and indent any continuation lines::
231
232    tasks:
233      - name: Copy ansible inventory file to client
234        copy: src=/etc/ansible/hosts dest=/etc/ansible/hosts
235                owner=root group=root mode=0644
236
237Variables can be used in action lines.   Suppose you defined
238a variable called 'vhost' in the 'vars' section, you could do this::
239
240   tasks:
241     - name: create a virtual host file for {{ vhost }}
242       template: src=somefile.j2 dest=/etc/httpd/conf.d/{{ vhost }}
243
244Those same variables are usable in templates, which we'll get to later.
245
246Now in a very basic playbook all the tasks will be listed directly in that play, though it will usually
247make more sense to break up tasks using the 'include:' directive.  We'll show that a bit later.
248
249.. _action_shorthand:
250
251Action Shorthand
252````````````````
253
254.. versionadded:: 0.8
255
256Ansible prefers listing modules like this in 0.8 and later::
257
258    template: src=templates/foo.j2 dest=/etc/foo.conf
259
260You will notice in earlier versions, this was only available as::
261
262    action: template src=templates/foo.j2 dest=/etc/foo.conf
263
264The old form continues to work in newer versions without any plan of deprecation.
265
266.. _handlers:
267
268Handlers: Running Operations On Change
269``````````````````````````````````````
270
271As we've mentioned, modules are written to be 'idempotent' and can relay  when
272they have made a change on the remote system.   Playbooks recognize this and
273have a basic event system that can be used to respond to change.
274
275These 'notify' actions are triggered at the end of each block of tasks in a playbook, and will only be
276triggered once even if notified by multiple different tasks.
277
278For instance, multiple resources may indicate
279that apache needs to be restarted because they have changed a config file,
280but apache will only be bounced once to avoid unnecessary restarts.
281
282Here's an example of restarting two services when the contents of a file
283change, but only if the file changes::
284
285   - name: template configuration file
286     template: src=template.j2 dest=/etc/foo.conf
287     notify:
288        - restart memcached
289        - restart apache
290
291The things listed in the 'notify' section of a task are called
292handlers.
293
294Handlers are lists of tasks, not really any different from regular
295tasks, that are referenced by name.  Handlers are what notifiers
296notify.  If nothing notifies a handler, it will not run.  Regardless
297of how many things notify a handler, it will run only once, after all
298of the tasks complete in a particular play.
299
300Here's an example handlers section::
301
302    handlers:
303        - name: restart memcached
304          service:  name=memcached state=restarted
305        - name: restart apache
306          service: name=apache state=restarted
307
308Handlers are best used to restart services and trigger reboots.  You probably
309won't need them for much else.
310
311.. note::
312   Notify handlers are always run in the order written.
313
314Roles are described later on.  It's worthwhile to point out that handlers are
315automatically processed between 'pre_tasks', 'roles', 'tasks', and 'post_tasks'
316sections.  If you ever want to flush all the handler commands immediately though,
317in 1.2 and later, you can::
318
319    tasks:
320       - shell: some tasks go here
321       - meta: flush_handlers
322       - shell: some other tasks
323
324In the above example any queued up handlers would be processed early when the 'meta'
325statement was reached.  This is a bit of a niche case but can come in handy from
326time to time.
327
328.. _executing_a_playbook:
329
330Executing A Playbook
331````````````````````
332
333Now that you've learned playbook syntax, how do you run a playbook?  It's simple.
334Let's run a playbook using a parallelism level of 10::
335
336    ansible-playbook playbook.yml -f 10
337
338.. _ansible-pull:
339
340Ansible-Pull
341````````````
342
343Should you want to invert the architecture of Ansible, so that nodes check in to a central location, instead
344of pushing configuration out to them, you can.
345
346Ansible-pull is a small script that will checkout a repo of configuration instructions from git, and then
347run ansible-playbook against that content.
348
349Assuming you load balance your checkout location, ansible-pull scales essentially infinitely.
350
351Run ``ansible-pull --help`` for details.
352
353There's also a `clever playbook <https://github.com/ansible/ansible-examples/blob/master/language_features/ansible_pull.yml>`_ available to configure ansible-pull via a crontab from push mode.
354
355.. _tips_and_tricks:
356
357Tips and Tricks
358```````````````
359
360Look at the bottom of the playbook execution for a summary of the nodes that were targeted
361and how they performed.   General failures and fatal "unreachable" communication attempts are
362kept separate in the counts.
363
364If you ever want to see detailed output from successful modules as well as unsuccessful ones,
365use the ``--verbose`` flag.  This is available in Ansible 0.5 and later.
366
367Ansible playbook output is vastly upgraded if the cowsay
368package is installed.  Try it!
369
370To see what hosts would be affected by a playbook before you run it, you
371can do this::
372
373    ansible-playbook playbook.yml --list-hosts
374
375.. seealso::
376
377   :doc:`YAMLSyntax`
378       Learn about YAML syntax
379   :doc:`playbooks_best_practices`
380       Various tips about managing playbooks in the real world
381   :doc:`index`
382       Hop back to the documentation index for a lot of special topics about playbooks
383   :doc:`modules`
384       Learn about available modules
385   :doc:`developing_modules`
386       Learn how to extend Ansible by writing your own modules
387   :doc:`intro_patterns`
388       Learn about how to select hosts
389   `Github examples directory <https://github.com/ansible/ansible-examples>`_
390       Complete end-to-end playbook examples
391   `Mailing List <http://groups.google.com/group/ansible-project>`_
392       Questions? Help? Ideas?  Stop by the list on Google Groups
393
394
395