Ansible在2.0版本引入块功能,块功能可以将任务进行分组,并且可以块级别上应用任务变量,同时支持在块内进行异常处理
常用语法:
- block:定义块
rescue:当出现异常时,执行的语句
always:无论结果如何都要执行的语句
块用法示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
[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
|
本文转自激情燃烧的岁月博客51CTO博客,原文链接http://blog.51cto.com/liuzhengwei521/1962666如需转载请自行联系原作者 weilovepan520 |