当找到条件时,ansible 回显到终端

当找到条件时,ansible 回显到终端

当使用 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"
    }
}

然后你就得思考如何利用它。

相关内容