介绍:block是ansible在2.0版本引入的一个特性,块功能能够将任务进行逻辑分组,而且能够在块级别上应用任务变量。同时也能够使用相似于其余编程语言处理异常那样的方法,来处理块内部的任务异常。shell
原理:block中的组任务,都会继承block的属相(支持when,不支持with_items),部署时会分别执行组中的任务,而且都会继承block的属相(在任务后添加block的when条件)编程
--- - hosts: localhost tasks: - block: - yum: name={{ item }} state=installed with_items: - httpd - memcached - template: src=templates/src.j2 dest=/etc/foo.conf - name: start service service: name=bar state=started enabled=True when: ansible_distribution == 'CentOS' become: true become_user: root
rescue:只有脚本报错时才执行编程语言
always:不管结果如何都执行memcached
--- - hosts: localhost tasks: - block: - debug: msg='I execute normally' - command: /bin/false - debug: msg='I never execute, due to the above task failing' 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.this
错误反例(2.3如下不支持。2.3及以上就支持了)spa
--- - hosts: localhost tasks: - name: bbbb #2.3如下的正确姿式应该去掉block的name block: - name: bbbb shell: echo bbbb when: false - name: cccc shell: echo cccc #-----报错 - name: bbbb ^ here
缘由:若是block的when结果是false,就不会执行任务得到注册变量的值,可是组中有些任务调用此注册变量,就会任务失败。debug
--- - hosts: localhost tasks: - block: - name: aaaa shell: echo aaaa - name: bbbb shell: echo bbbb register: results #-------后面调用会致使失败 - name: echo {{results.stdout}} #-------调用了,此任务会失败 shell: echo cccc when: false - name: dddd shell: echo dddd
解决办法:能够给block的vars属相添加变量,在block的组任务中进行调用code
--- - hosts: localhost tasks: - name: bbbb shell: echo bbb register: result #-------注册result变量 - block: - name: aaaa shell: echo aaaa - name: echo {{results}} #-------调用了 shell: echo cccc when: false vars: results: "{{result.stdout}}" #-------使用vars,将注册的result放入block中results变量中 - name: dddd shell: echo dddd
--- - hosts: localhost tasks: - block: - name: aaaa shell: echo aaaa with_items: #-----会报错,block不支持此属相 - myname: dxx when: false - name: dddd shell: echo dddd