当 shell 命令没有输出时,Ansible 注册失败

Mru*_*sar 0 ansible ansible-playbook

我试图检查服务是否正在运行,然后将其输出注册到某个变量,如果它没有运行,则启动服务。下面是我的 Ansible 剧本片段。

- hosts: localhost
  tasks:
  - name: check if service is running
    shell: pgrep node
    register: pgrep
  - name: stop running service
    shell: pkill node
    when: pgrep.stdout_lines != ''
    tags:
    - stop
  - name: start running service
    shell: pkill node
    when: pgrep.stdout_lines == ''
    tags:
    - start
Run Code Online (Sandbox Code Playgroud)

现在在上述情况下,如果进程未运行,则该pgrep node命令将退出状态代码返回为 1,这将使“检查服务是否正在运行”任务失败并中止进一步执行任务。我知道通过设置ignore_errors: true将忽略错误并继续进行,但它无法运行 Ansible。有没有办法可以优雅地处理这个问题?

tec*_*raf 5

您可以控制定义失败的内容并将条件设置为失败,当返回码 frompgrep为 2 或 3 时。

man pgrep:

 The pgrep and pkill utilities return one of the following values upon exit:

 0       One or more processes were matched.
 1       No processes were matched.
 2       Invalid options were specified on the command line.
 3       An internal error occurred.
Run Code Online (Sandbox Code Playgroud)

所以 Ansible 任务应该如下所示:

- name: check if service is running
  shell: pgrep node
  register: pgrep
  failed_when: "pgrep.rc == 2 or pgrep.rc == 3"
Run Code Online (Sandbox Code Playgroud)