一、概述
block是ansible在2.0版本引入的一個特性 ##ansible2.0之下的版本無法使用
塊功能可以将任務進行邏輯分組,并且可以在塊級别上應用任務變量。
同時也可以使用類似于其他程式設計語言處理異常那樣的方法,來處理塊内部的任務異常。
原理:block中的組任務,都會繼承block的屬相(支援when,不支援with_items)
部署時會分别執行組中的任務,并且都會繼承block的屬相(在任務後添加block的when條件)
塊錯誤處理
rescue 當block中出現錯誤時,執行相應任務子產品。
always 無論block中是否出現錯誤,最終都執行相應任務子產品。
二、試驗
1、使用塊任務分組
---
- 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
2、異常處理
1、例子一
首先備份配置檔案,執行一次對nginx.conf檔案的修改,修改完配置檔案會執行nginx -t。如果驗證配置檔案有問題,則将目前有問題的配置檔案打
上-failed标簽,且復原之前備份的配置檔案。
無論block和rescue中是否發生錯誤,通過always,都會記錄記錄檔。
---
- name: test nginx config
hosts: nginx_module
gather_facts: False
tasks:
- name: modify config and test
block:
- name: backup config file
command: cp /etc/nginx/nginx.conf /etc/nginx/conf-backup/nginx.conf
- name: nginx config file add "include"
lineinfile:
path: /etc/nginx/nginx.conf
insertafter: 'include /etc/nginx/conf.d/'
line: 'include /etc/nginx/site-enabled/*.conf;'
- name: nginx config test
command: nginx -t
rescue:
- name: move failed config file
command: mv /etc/nginx/nginx.conf /etc/nginx/nginx.conf-failed
- name: copy backup file
command: mv /etc/nginx/conf-backup/nginx.conf /etc/nginx/
always:
- name: add operation recode
shell: echo `date` modify config >> /etc/nginx/conf-backup/modify-config.log
2、例子二
---
- 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"
三、陷阱
1、2.3版本添加了塊的name特性
在2.0中添加了塊特性,在2.3中添加了塊的name特性---
- hosts: localhost
tasks:
- name: bbbb #2.3以下的正确姿勢應該去掉block的name
block:
- name: bbbb
shell: echo bbbb
when: false
2、block的子任務中不能添加注冊的變量
原因:如果block的when結果是false,就不會執行任務獲得注冊變量的值,但是組中有些任務調用此注冊變量,就會任務失敗。
---
- 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
解決辦法:可以給block的vars屬相添加變量,在block的組任務中進行調用
---
- 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變量中
3、block沒有with_items屬相
---
- hosts: localhost
tasks:
- block:
- name: aaaa
shell: echo aaaa
with_items: #-----會報錯,block不支援此屬相
- myname: dxx
when: false
- name: dddd
shell: echo dddd