Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the pid of a running playbook for use within the playbook

When we run a playbook, with verbose output enabled, in the ansible logs we can see something like this:

2016-02-03 12:51:58,235 p=4105 u=root | PLAY RECAP

I guess that the p=4105 is the pid of the playbook when it ran.

Is there a way to get this pid inside the playbook during its runtime (as a variable for example)?

like image 303
Cobra Kai Dojo Avatar asked Feb 03 '16 12:02

Cobra Kai Dojo


People also ask

How do I run a specific part of my playbook in Ansible?

The easiest way to run only one task in Ansible Playbook is using the tags statement parameter of the “ansible-playbook” command. The default behavior is to execute all the tags in your Playbook with --tags all .

How do you pass variable value while running Ansible playbook?

To pass a value to nodes, use the --extra-vars or -e option while running the Ansible playbook, as seen below. This ensures you avoid accidental running of the playbook against hardcoded hosts.

Which tag lets you define the variables which you can use in your playbook?

Vars tag lets you define the variables which you can use in your playbook. Usage is similar to variables in any programming language.

Can I run Ansible playbook locally?

By Default, Ansible would run the playbook on the host group which is mentioned in the playbook with hosts: directive. But if you want to ignore all those hosts specified in the playbook and run it locally. You can use this method.


2 Answers

You can define the PID for localhost using the set_fact module with a lookup filter.

- hosts: localhost
  tasks:
    - set_fact:
        pid: "{{ lookup('pipe', 'echo $PPID') }}"

And later on you can reference the PID via the hostvars dictionary.

- hosts: remote
  tasks:
    - debug: var=hostvars.localhost.pid
like image 62
ceving Avatar answered Oct 14 '22 00:10

ceving


This sounds a little like an XY problem, but one option may be to spawn a shell with the shell command and then ask for the parent PID:

- name: get pid of playbook
  shell: |
    echo "$PPID"
  register: playbook_pid

This will give you the PID of the python process that is executing the playbook.

like image 25
larsks Avatar answered Oct 14 '22 00:10

larsks