确认任务是否正在运行的任务


10

Ansible 2.1

在剧本中,我开始了一个过程:

- name: Start Automation Agent, and enable start on boot
  service: name=mongodb-mms-automation-agent state=started enabled=yes

从播放回顾来看,该过程似乎已成功启动。

TASK [install : Start automation agent, and enable start on boot] **************
changed: [server1]

但是,登录到远程主机并执行时ps,该进程未运行。检查进程日志,它没有满足某些先决条件(预定)。

如何在剧本中编写任务以确认过程已成功启动?

Answers:


12

您可以failed在运行检查进程是否正在运行的命令之后使用Jinja2筛选器进行检查。

这是一个使用命令输出systemctl status apache2来确定Apache是​​否正在运行的示例:

- name: Check if Apache is running
  command: systemctl status apache2
  ignore_errors: yes
  changed_when: false
  register: service_apache_status

- name: Report status of Apache
  fail:
    msg: |
      Service apache2 is not running.
      Output of `systemctl status apache2`:
      {{ service_apache_status.stdout }}
      {{ service_apache_status.stderr }}
  when: service_apache_status | failed

如果第一个任务的命令失败,则第二个任务将失败并显示第一个任务失败的原因。
返回码存储在中service_apache_status.rc

失败的示例输出:

TASK: [Check if Apache is running] *********************** 
failed: [localhost] => {"changed": false, "cmd": ["systemctl", "status", "apache2"], "delta": "0:00:00.009379", "end": "2016-06-06 15:17:27.827172", "rc": 3, "start": "2016-06-06 15:17:27.817793", "stdout_lines": ["* apache2.service", "   Loaded: not-found (Reason: No such file or directory)", "   Active: inactive (dead)"], "warnings": []}
stdout: * apache2.service
   Loaded: not-found (Reason: No such file or directory)
   Active: inactive (dead)
...ignoring

TASK: [Report status of Apache] ***************************
failed: [localhost] => {"failed": true}
msg: apache2 is not running
systemctl status apache2 output:
* apache2.service
   Loaded: not-found (Reason: No such file or directory)
   Active: inactive (dead)

这是使用pgrep(检查过程是否正在运行)的另一种方式(尽管可能不太可靠):

- name: Check if Apache is running
  shell: pgrep apache2
  ignore_errors: yes
  changed_when: false
  register: service_apache_status

- name: Report status of Apache
  fail:
    msg: |
      Service apache2 is not running.
      Return code from `pgrep`:
      {{ service_apache_status.rc }}
  when: service_apache_status.rc != 0

如何when: service_apache_status | failed运作?它是否在寻找failed令牌service_apache_status
霍华德·李

2
@HowardLee:我相信它会检查返回码,如果不是0,则将其视为failed
Deltik

1
而不是ps | 您可以尝试的greppgrep apache2
madeddie

@madeddie:我喜欢。答案更新提示pgrep
Deltik '19

4

这就是我现在要做的:

- name: Confirm Automation Agent is running
  command: service mongodb-mms-automation-agent status
  register: agent_status
  failed_when: "'NOT' in agent_status.stdout"
  changed_when: False

failed_when在1.4中引入。changed_when: False用于抑制更改状态。阅读更多

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.