Get the Pid of a Running Playbook for Use Within the Playbook

Get the PID of ansible playbook from within the same playbook

Try this:

#!/bin/bash

cd ~/.ansible/tmp

while read pid; do
[ -d /proc/${pid} ] || ls -lad ansible-local-${pid}*;
done < <(find . -type d | sed -n 's/^ansible-local-\([0-9]*\).*$/\1/p' )

If correctly lists the stale directories, then change ls -lad to 'rm -r` in line 6.

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

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

How to get only the parent PID of a process and exclude child processes linked to it with grep

Tac this to the end
| grep -v grep

List running java processes in a linux host via ansible playbook

You could see the result with your actual playbook by running ansible in verbose mode.

However, the good way to do this is to register the output of your task and display its content in a debug task (or use it in any other task/loop).

To know how your registered var looks like, you can read the doc about common and shell's specific return values... or you can simply debug the full var in your playbook and have a look at it.

Here is an example just to get the full stdout of the command:

---
- name: Check the running java processes
hosts: all
tasks:
- name: Check running processes
shell: ps -ef | grep -i java
register: ps_cmd

- name: Show captured processes
debug:
var: ps_cmd.stdout

Make ansible-playbook run the playbook for the given host only once

You can check the ansible pid of the remote server before launching a playbook run. What OS/distro are you using?
Hmm.. depending of what you are testing, you can spin up a container(docker or lxd) to test your environment for each commit. Take in account that if you creating/modifying network interfaces or creating device files, it won't suite your needs.
I use this method to test my playbook roles in just one server having several unit tests for each role param.



Related Topics



Leave a reply



Submit