ansible register基礎使用講解

YatHo發表於2017-09-18

當我們需要判斷對執行了某個操作或者某個命令後,如何做相應的響應處理(執行其他 ansible 語句),則一般會用到register 。

  舉個例子:

  我們需要判斷 zip 包是否存在,如果存在了就執行一些相應的指令碼,則可以為該判斷註冊一個register變數,並用它來判斷是否存在,存在返回 succeeded, 失敗就是 failed.

- name:Copy test.zip to hosts
  copy:  src=/mnt/patches/test.zip dest=/mnt/patches 
  register: patches_testzip_result
  ignore_errors: True
  tags: deploy
- name: Create a register to represent the status if the /mnt/patches/test.zip exsited 
  shell: ls -l /mnt/patches| grep test.zip
  register: patches_testzip_result
  ignore_errors: True
  tags: deploy

- name: Copy Env_update.sh to hosts
  copy: src=/Users/jenkins/jenkins/lirbary/Env_update_shell/Env_updata_cpzh_v1.0.10.sh dest=/mnt/patches mode=0755
  when: patches_testzip_result | succeeded
  tags: deploy

  

注意: 
1、register變數的命名不能用 -中橫線,比如patches-testzip_result,則會被解析成patches,testzip_result會被丟掉,所以不要用- 

2、ignore_errors這個關鍵字很重要,一定要配合設定成True,否則如果命令執行不成功,即 echo $?不為0,則在其語句後面的ansible語句不會被執行,導致程式中止。

那我如何去做多種條件的判斷呢,比如我還需要判斷是否有Env_update.sh存在,則還需要為它註冊一個變數。

- name: Create a register to represent the status if the Env_update.sh

exsited shell: ls -l /mnt/patches | grep Env_update
register: Env_update_result
ignore_errors: True
tags: deploy

 然後在when中用and或者or來組合判斷。比如當兩種條件都成功,執行shell指令碼:

- name: for Env_update test.zip

  shell: sh Env_update.sh  BD_${BD_date}_${Env} ${Updata_Modle}
  when: ( patches_testzip_result | succeeded) and ( Env_update_result | succeeded)   
  tags: deploy

相關文章