2015-07-17 17:53:13 +00:00
|
|
|
Blocks
|
|
|
|
======
|
|
|
|
|
|
|
|
In 2.0 we added a block feature to allow for logical grouping of tasks and even
|
|
|
|
in play error handling. Most of what you can apply to a single task can be applied
|
|
|
|
at the block level, which also makes it much easier to set data or directives common
|
|
|
|
to the tasks.
|
|
|
|
|
|
|
|
|
2015-08-04 23:09:06 +00:00
|
|
|
.. code-block:: YAML
|
|
|
|
:emphasize-lines: 2
|
|
|
|
:caption: Block example
|
2015-07-17 17:53:13 +00:00
|
|
|
|
|
|
|
tasks:
|
|
|
|
- block:
|
|
|
|
- yum: name={{ item }} state=installed
|
|
|
|
with_items:
|
|
|
|
- httpd
|
|
|
|
- memcached
|
|
|
|
|
|
|
|
- template: src=templates/src.j2 dest=/etc/foo.conf
|
|
|
|
|
|
|
|
- service: name=bar state=started enabled=True
|
|
|
|
|
|
|
|
when: ansible_distribution == 'CentOS'
|
|
|
|
become: true
|
|
|
|
become_user: root
|
|
|
|
|
2015-08-04 23:09:06 +00:00
|
|
|
|
2015-07-17 17:53:13 +00:00
|
|
|
In the example above the 3 tasks will be executed only when the block's when condition is met and enables
|
|
|
|
privilege escalation for all the enclosed tasks.
|
|
|
|
|
|
|
|
|
|
|
|
.. _block_error_handling:
|
|
|
|
|
|
|
|
Error Handling
|
|
|
|
``````````````
|
|
|
|
|
2015-08-04 23:09:06 +00:00
|
|
|
Blocks also introduce the ability to handle errors in a way similar to exceptions in most programming languages.
|
|
|
|
|
|
|
|
.. code-block:: YAML
|
|
|
|
:emphasize-lines: 2,6,10
|
|
|
|
:caption: Block error handling example
|
2015-07-17 17:53:13 +00:00
|
|
|
|
|
|
|
tasks:
|
|
|
|
- block:
|
|
|
|
- debug: msg='i execute normally'
|
|
|
|
- command: /bin/false
|
|
|
|
- debug: msg='i never execute, cause ERROR!'
|
|
|
|
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
|
2015-07-19 21:27:13 +00:00
|
|
|
with whatever you need to do to recover from the previous error. The ``always`` section runs no matter what previous
|
2015-07-17 17:53:13 +00:00
|
|
|
error did or did not occur in the ``block`` and ``rescue`` sections.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.. seealso::
|
|
|
|
|
|
|
|
:doc:`playbooks`
|
|
|
|
An introduction to playbooks
|
|
|
|
:doc:`playbooks_roles`
|
|
|
|
Playbook organization by roles
|
|
|
|
`User Mailing List <http://groups.google.com/group/ansible-devel>`_
|
|
|
|
Have a question? Stop by the google group!
|
|
|
|
`irc.freenode.net <http://irc.freenode.net>`_
|
|
|
|
#ansible IRC chat channel
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|