ansible register 这个功能非常有用。当我们需要判断对执行了某个操作或者某个命令后,如何做相应的响应处理(执行其他 ansible 语句),则一般会用到register 。
举个例子:
我们需要判断sda6是否存在,如果存在了就执行一些相应的脚本,则可以为该判断注册一个register变量,并用它来判断是否存在,存在返回 succeeded, 失败就是 failed.
ansible执行完命令后的rc=0是什么意思?
命令返回值 returncode
tasks:
-
shell: echo
"I've got '{{ foo }}' and am not afraid to use it!"
when: foo
is
defined
-
fail: msg
=
"Bailing out. this play requires 'bar'"
when: bar
is
not
defined
register关键字可以将任务执行结果保存到一个变量中,该变量可以在模板或者playbooks文件中使用:
1
2
3
4
5
6
7
8
9
10
|
-
name: test play
hosts:
all
tasks:
-
shell: cat
/
etc
/
motd
register: motd_contents
-
shell: echo
"motd contains the word hi"
when: motd_contents.stdout.find(
'hi'
) !
=
-
1
|
上边中的例子中,通过注册变量访问返回的内容,`stdout`里面保存了命令的标准输出内容。注册变量还可以使用在`with_items`中,如果其保存的内容可以转换为列表,或者内容本身就是个列表。如果命令的输出本身就是列表,可以通过`stdout_lines`访问:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
-
name: registered variable usage as a with_items
list
hosts:
all
tasks:
-
name: retrieve the
list
of home directories
command: ls
/
home
register: home_dirs
-
name: add home dirs to the backup spooler
file
: path
=
/
mnt
/
bkspool
/
{{ item }} src
=
/
home
/
{{ item }} state
=
link
with_items: home_dirs.stdout_lines
# same as with_items: home_dirs.stdout.split()
|
ansible register 这个功能非常有用。当我们需要判断对执行了某个操作或者某个命令后,如何做相应的响应处理(执行其他 ansible 语句),则一般会用到register 。
举个例子:
我们需要判断sda6是否存在,如果存在了就执行一些相应的脚本,则可以为该判断注册一个register变量,并用它来判断是否存在,存在返回 succeeded, 失败就是 failed.
- name: Create a register to represent the status if the /dev/sda6 exsited
shell: df -h | grep sda6
register: dev_sda6_result ignore_errors: True tags: docker - name: Copy docker-thinpool.sh to all hosts copy: src=docker-thinpool.sh dest=/usr/bin/docker-thinpool mode=0755 when: dev_sda6_result | succeeded tags: docker
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
注意: 1、register变量的命名不能用 -
中横线,比如dev-sda6_result
,则会被解析成sda6_result
,dev
会被丢掉,所以不要用-
2、ignore_errors
这个关键字很重要,一定要配合设置成True
,否则如果命令执行不成功,即 echo $?
不为0,则在其语句后面的ansible语句不会被执行,导致程序中止。
配合register循环列表
register注册一个变量后,可以配合with_items来遍历变量结果。示例如下:
- shell: echo "{{ item }}"
with_items: - one - two register: echo - name: Fail if return code is not 0 fail: msg: "The command ({{ item.cmd }}) did not have a 0 return code" when: item.rc != 0 with_items: echo.results