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

Ansible register fails when there is no output from shell command

我正在尝试检查服务是否 运行 然后将其输出注册到某个变量,如果不是 运行 然后启动服务。下面是我的 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

现在在上述情况下,如果进程不是 运行,则 pgrep node 命令 returns 退出状态代码为 1,这会导致 "check if service is running" 任务失败并进一步中止任务的执行。我知道通过设置 ignore_errors: true 将忽略错误并继续前进,但它会导致 Ansible 运行失败。有没有办法让我们优雅地处理这个问题?

您可以 control what defines failure 并设置当来自 pgrep 的 return 代码为 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.

因此 Ansible 任务应该如下所示:

- name: check if service is running
  shell: pgrep node
  register: pgrep
  failed_when: "pgrep.rc == 2 or pgrep.rc == 3"

添加答案以备将来参考。如果它们存在,如何杀死多个进程。仅在 rc==0 时指示更改。不要显示失败,除非它是 rc==2 或 rc==3。

- name: "Kill any processes"
  become: True
  vars:
    processes_to_kill: ["p1", "p2", "p3", "p4"]
  shell: "pkill -f {{ item }}"
  with_items: "{{ processes_to_kill }}"
  register: pkill
  failed_when: "pkill.rc == 2 or pkill.rc == 3"
  changed_when: "pkill.rc == 0"