Ansible 中 register 注册变量
Ansible的register模块用于捕获和保存任务执行结果的,register是一个关键字,可以将任务执行的结果赋值给指定的变量名称,这个变量可以在后续任务中使用。
register模块可以捕获各种类型的输出,包括stdout、stderr、rc、changed等。也可以与其他模块一起使用,例如“when”条件、“loop”循环等。
在web1组的主机上执行任务,创建/tmp/dir1,并打印创建结果,代码示意如下:
[root@pubserver ansible]# vim regi1.yml
---
- name: create file /tmp/dir1
hosts: web1
tasks:
- name: create file
file:
path: /tmp/dir1
state: touch
register: result
- name: display output
debug:
msg: "{{result}}"
[root@pubserver ansible]# ansible-playbook regi1.yml
.............
TASK [display output] *****************************************************************************************************************************
ok: [web1] => {
"msg": {
"changed": true,
"dest": "/tmp/dir1",
"diff": {
"after": {
"atime": 1693385587.9442923,
"mtime": 1693385587.9442923,
"path": "/tmp/dir1",
"state": "touch"
},
"before": {
"atime": 1693385587.9377587,
"mtime": 1693385587.9377587,
"path": "/tmp/dir1",
"state": "absent"
}
},
"failed": false,
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"secontext": "unconfined_u:object_r:user_tmp_t:s0",
"size": 0,
"state": "file",
"uid": 0
}
}
PLAY RECAP ****************************************************************************************************************************************
web1 : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
在webservers组的主机上执行任务,创建文件/tmp/ademo/abc,如果创建不成功,则通过debug输出create failed,代码示意如下:
[root@pubserver ansible]# vim regi2.yml
---
- name: create file /tmp/ademo/abc
hosts: webservers
ignore_errors: yes
tasks:
- name: create file
file:
path: /tmp/ademo/abc
state: touch
register: result
- name: debug output if create failed
debug:
msg: "create failed"
when: not result.changed
# 测试
[root@pubserver ansible]# ansible-playbook regi2.yml
..........
TASK [create file] ********************************************************************************************************************************
fatal: [web2]: FAILED! => {"changed": false, "msg": "Error, could not touch target: [Errno 2] 没有那个文件或目录: b'/tmp/ademo/abc'", "path": "/tmp/ademo/abc"}
...ignoring
fatal: [web1]: FAILED! => {"changed": false, "msg": "Error, could not touch target: [Errno 2] 没有那个文件或目录: b'/tmp/ademo/abc'", "path": "/tmp/ademo/abc"}
...ignoring
TASK [debug output if create failed] **************************************************************************************************************
ok: [web1] => {
"msg": "create failed"
}
ok: [web2] => {
"msg": "create failed"
}
PLAY RECAP ****************************************************************************************************************************************
web1 : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1
web2 : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1