Saffik
Saffik

Reputation: 1013

How to check if PID is running in ansible and if not then fail the task?

I have ansible playbook which does 3 things:

a) Start up a flask server

b) Waits for 10 seconds for it to start

c) Checks if the PID is running

- name: "execute script to start flask"
  shell: nohup python main.py &
  args:
    chdir: /home/ubuntu/flask
    executable: /bin/bash

- pause: seconds=10

- name: "verify that the server has started"
  command: ?????

Manually I do this to get PID

pgrep -f /'main.py'

Which returns a PID lets say...

8212

How do I do step(c) in ansible playbook, and to make sure if PID is not found, task will fail?

Upvotes: 0

Views: 3708

Answers (1)

CLNRMN
CLNRMN

Reputation: 1457

I would not work with pause, it slows down your playbook unnecessarily. You could simply work with the pids Ansible-Module and until

Pids: https://docs.ansible.com/ansible/latest/modules/pids_module.html

Loop-Until: https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#retrying-a-task-until-a-condition-is-met

Example checking every 5 seconds for 10 retries, if the Pid from main.py is not available then, the playbook will fail.

---
- hosts: localhost
  tasks:
  - name: check the pid of main.py
    pids:
      name: main.py
    register: pid
    until: pid.pids | length > 0
    delay: 5
    retries: 10
  - debug: var=pid

Upvotes: 1

Related Questions