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
