ansible的block特性踩坑記

      介紹: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

三、常見陷阱

(1)在2.0中添加了塊特性,在2.3中添加了塊的name特性

錯誤反例(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

(2)block的子任務中不能添加註冊的變量

緣由:若是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

(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
相關文章
相關標籤/搜索