![当找到条件时,ansible 回显到终端](https://linux22.com/image/210016/%E5%BD%93%E6%89%BE%E5%88%B0%E6%9D%A1%E4%BB%B6%E6%97%B6%EF%BC%8Cansible%20%E5%9B%9E%E6%98%BE%E5%88%B0%E7%BB%88%E7%AB%AF.png)
当使用 lineinfile 满足条件时,如何将输出打印到终端
- lineinfile:
path: /home/pc/date.txt
state: present
line: 'yes'
regexp: '^\s*Wednesday\s*$'
check_mode: yes
register: wednesdayOccur
- debug: msg="{{ wednesdayOccur.stdout }}" #Show on terminal "wednesday is found"
when: wednesdayOccur == 1
答案1
给定文件
# test.yml
- hosts: localhost
tasks:
- lineinfile:
path: /tmp/blah
state: present
line: 'yes'
regexp: '^\s*Wednesday\s*$'
check_mode: yes
register: wednesdayOccur
- debug: msg="wednesday is found"
when: wednesdayOccur is defined
除其他外,这会产生:
$ printf Wednesday'\n' > /tmp/blah
$ ANSIBLE_NOCOLOR=1 ansible-playbook test.yml
...
TASK [debug] *******************************************************************
ok: [localhost] => {
"msg": "wednesday is found"
}
...
这就是 Ansible 呈现调试输出的方式。
如果您需要变量中的某些内容,每个模块都会做自己的事情,因此您必须查阅每个模块的详细手册,例如文件行,或者,记录变量以debug
查看在给定条件下它包含的内容:
# test2.yml
- hosts: localhost
tasks:
- lineinfile:
path: /tmp/blah
state: present
line: 'yes'
regexp: '^\s*Wednesday\s*$'
check_mode: yes
register: wednesdayOccur
- debug: msg="wednesdayOccur"
when: wednesdayOccur is defined
除其他外,这会产生
TASK [debug] *******************************************************************
ok: [localhost] => {
"msg": {
"backup": "",
"changed": true,
"diff": [
{
"after": "",
"after_header": "/tmp/blah (content)",
"before": "",
"before_header": "/tmp/blah (content)"
},
{
"after_header": "/tmp/blah (file attributes)",
"before_header": "/tmp/blah (file attributes)"
}
],
"failed": false,
"msg": "line replaced"
}
}
然后你就得思考如何利用它。