ansible/docs/docsite/rst/playbooks_blocks.rst
James Cammarata 483df9c5f8 Imports and includes (#25399)
Initial commit to split includes into static imports/dynamic includes

This implements the new include/import syntax for Ansible 2.4:
* include_{tasks,role,variables} = dynamic
* import_{playbook,tasks,role} = static

The old bare `include` will be considered deprecated, as will any use of the `static: {yes|no}` option.

This also adds docs for import/include and reorganizing the "Playbook Reuse" section of the documentation.
2017-06-06 16:39:48 -05:00

2.8 KiB

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. This does not mean the directive affects the block itself, but is inherited by the tasks enclosed by a block. i.e. a when will be applied to the tasks, not the block itself.

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

In the example above, each of the 3 tasks will be executed after appending the when condition from the block and evaluating it in the task's context. Also they inherit the privilege escalation directives enabling "become to root" 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.

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 with whatever you need to do to recover from the previous error. The always section runs no matter what previous error did or did not occur in the block and rescue sections.

Another example is how to run handlers after an error occurred :

tasks:
 - block:
     - debug: msg='i execute normally'
       notify: run me even after an error
     - command: /bin/false
   rescue:
     - name: make sure all handlers run
       meta: flush_handlers
handlers:
  - name: run me even after an error
    debug: msg='this handler runs even on error'
playbooks

An introduction to playbooks

playbooks_reuse_roles

Playbook organization by roles

User Mailing List

Have a question? Stop by the google group!

irc.freenode.net

#ansible IRC chat channel