Ansible Register


原文链接: Ansible Register

ansible register 基础使用讲解

Register doc

# 注册变量 result,根据 result 结果判断是否已经生成过 etcd 证书
# result|failed 说明没有生成过证书,下一步生成证书
# result|succeeded 说明已经有 etcd 证书,使用原证书可以保证 api-server 和 calico/node 等对 etcd 集群
# 的访问不受影响,因此跳过证书生成的步骤
- name: 注册变量 result
  command: ls /etc/etcd/ssl/etcd.pem
  register: result
  ignore_errors: True

- name: 创建 etcd 证书目录
  file: name=/etc/etcd/ssl state=directory
  when: result|failed

- name: 创建 etcd 证书请求
  template: src=etcd-csr.json.j2 dest=/etc/etcd/ssl/etcd-csr.json
  when: result|failed

使用 Register 内的变量

把任务的输出定义为变量,然后用于其他任务
使用 register ,可以将当前 task 的输出结果赋值给一个变量。
当我们需要判断对执行了某个操作或者某个命令后,如何做相应的响应处理(执行其他 ansible 语句),则一般会用到 register 。

  举个例子:

  我们需要判断 zip 包是否存在,如果存在了就执行一些相应的脚本,则可以为该判断注册一个 register 变量,并用它来判断是否存在,存在返回 succeeded, 失败就是 failed.

- name:Copy test.zip to hosts
  copy:  src=../../../mnt/patches/test.zip dest=/mnt/patches
 register: 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: 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: 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
`