Ansible在2.0版本引入块功能,块功能可以将任务进行分组,并且可以块级别上应用任务变量,同时支持在块内进行异常处理
常用语法:
- block:定义块
rescue:当出现异常时,执行的语句
always:无论结果如何都要执行的语句
块用法示例:
[root@nfs-server playbook]# cat block.yml --- - hosts: webservers remote_user: root gather_facts: True tasks: - block: - service: name={{ item }} state=stopped with_items: - nginx - httpd - memcached tags: - stop_application - yum: name={{ item }} state=absent with_items: - nginx - httpd - memcached tags: - remove_soft when: ansible_os_family == ‘RedHat‘ [root@nfs-server playbook]# ansible-playbook block.yml PLAY [webservers] ************************************************************************************************************************************** TASK [Gathering Facts] ********************************************************************************************************************************* ok: [192.168.2.111] ok: [192.168.2.101] TASK [service] ***************************************************************************************************************************************** changed: [192.168.2.101] => (item=nginx) changed: [192.168.2.111] => (item=nginx) ok: [192.168.2.101] => (item=httpd) ok: [192.168.2.111] => (item=httpd) changed: [192.168.2.111] => (item=memcached) changed: [192.168.2.101] => (item=memcached) TASK [yum] ********************************************************************************************************************************************* changed: [192.168.2.101] => (item=[u‘nginx‘, u‘httpd‘, u‘memcached‘]) changed: [192.168.2.111] => (item=[u‘nginx‘, u‘httpd‘, u‘memcached‘]) PLAY RECAP ********************************************************************************************************************************************* 192.168.2.101 : ok=3 changed=2 unreachable=0 failed=0 192.168.2.111 : ok=3 changed=2 unreachable=0 failed=0
本文出自 “激情燃烧的岁月” 博客,请务必保留此出处http://liuzhengwei521.blog.51cto.com/4855442/1962666
原文地址:http://liuzhengwei521.blog.51cto.com/4855442/1962666