Block块

多个action组装成块,可以根据不同条件执行一段语句 :

  1. tasks:
  2. - block:
  3. - yum: name={{ item }} state=installed
  4. with_items:
  5. - httpd
  6. - memcached
  7. - template: src=templates/src.j2 dest=/etc/foo.conf
  8. - service: name=bar state=started enabled=True
  9. when: ansible_distribution == 'CentOS'
  10. become: true
  11. become_user: root

组装成块处理异常更方便:

  1. tasks:
  2. - block:
  3. - debug: msg='i execute normally'
  4. - command: /bin/false
  5. - debug: msg='i never execute, cause ERROR!'
  6. rescue:
  7. - debug: msg='I caught an error'
  8. - command: /bin/false
  9. - debug: msg='I also never execute :-('
  10. always:
  11. - debug: msg="this always executes"