当shell命令没有输出时,Ansible寄存器失败

时间:2016-12-19 14:11:35

标签: ansible ansible-playbook

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

- 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命令将退出状态代码返回为1,这使得“检查服务是否正在运行”任务失败并中止进一步执行任务。我知道通过设置ignore_errors: true将忽略错误并继续前进,但它无法通过Ansible运行。有没有办法让我们能够优雅地处理这个问题?

2 个答案:

答案 0 :(得分:3)

pgrep的返回代码为2或3时,您可以control what defines failure并将条件设置为失败。

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"

答案 1 :(得分:0)

添加答案以供将来参考。如何终止多个进程(如果存在)。仅当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"