ansible register基础使用讲解

当我们需要判断对执行了某个操作或者某个命令后,如何做相应的响应处理(执行其他 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
原文地址:https://www.cnblogs.com/YatHo/p/7542977.html