簡體   English   中英

當 systemd 服務無法啟動時,如何使 Ansible 失敗?

[英]How can I make Ansible fail when the systemd service fails to start?

我有一個我部署的 systemd 服務,並希望由 Ansible 啟動。

我的 systemd 服務單元文件是這樣的:

[Unit]
Description=Collector service
After=network.target mariadb.service
Requires=mariadb.service

[Service]
Type=simple
ExecStart=/opt/collector/app.py
WorkingDirectory=/opt/collector
Restart=on-abort
User=root

[Install]
WantedBy=multi-user.target

我正在使用Type=simple因為這看起來是正確的解決方案(也是本問題中的首選解決方案)。

我嘗試使用Type=oneshot以及(由初始用戶使這個問題進行重復的所建議的這個問題),但問題是,/opt/collector/app.py腳本是一個長期運行的進程:

while True:
    t = threading.Thread(...)
    t.start()
    t.join()
    time.sleep(15)

並且使用Type=oneshotAnsible 將永遠阻塞

我的 Ansible 起始代碼是:

- name: start Collector service
  systemd:
    name: collector
    state: started
    enabled: yes

在目標系統上, systemctl將顯示:

[root@srv01 /]# systemctl
  UNIT                           LOAD   ACTIVE     SUB       DESCRIPTION
  dev-sda1.device                loaded activating tentative /dev/sda1
  -.mount                        loaded active     mounted   /
  dev-mqueue.mount               loaded active     mounted   POSIX Message Queue File System
  etc-hostname.mount             loaded active     mounted   /etc/hostname
  etc-hosts.mount                loaded active     mounted   /etc/hosts
  etc-resolv.conf.mount          loaded active     mounted   /etc/resolv.conf
  run-user-0.mount               loaded active     mounted   /run/user/0
  session-73.scope               loaded active     running   Session 73 of user root
  crond.service                  loaded active     running   Command Scheduler
  dbus.service                   loaded active     running   D-Bus System Message Bus
  haproxy.service                loaded active     running   HAProxy Load Balancer
<E2><97><8F> collector.service          loaded failed     failed   Collector service
....

由於 Python 進程異常(使用未定義的變量),服務失敗。

但是我的 Ansible playbook 運行並沒有失敗:

TASK [inventory : start Collector service] *********************************
changed: [srv01]

我嘗試了systemdservice Ansible 模塊,行為是相同的。

我怎樣才能使 Ansible:

  • 當 systemd 單元無法啟動時失敗?
  • 不阻塞和 systemd 進入active running狀態,一段while True進程?

我偶然發現了這一點,而我遇到了同樣的問題,默默地失敗了服務。 我還發現了一個描述這個問題的錯誤報告,經過一些研究,我找到了一個解決方法:

- name: start Collector service
  systemd:
    name: collector
    state: started
    enabled: yes

- name: make sure Collector service is really running
  command: systemctl is-active collector

請注意,對於Type=simple服務,僅當服務本身在啟動后立即失敗時才會失敗。

您可以使用failed_when示例:

- name:  validating processes started correctly
  shell: pgrep toto| wc -l
  register: after_count
  failed_when: after_count.stdout_lines[0] == "1"

如果返回的進程數不是== 1failed_when將使任務失敗

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM