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

前端 未结 5 1747
终归单人心
终归单人心 2021-01-17 14:35

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

相关标签:
5条回答
  • 2021-01-17 14:55

    This might be what you are looking for, but is only applicable to Linux:

    - name: Get the pid of this playbook
      shell: pstree -spal $PPID | grep ansible-playbook | awk '{print $1;exit}' | awk -F, '{print $2}'
      register: ansible_pid
    
    - name: Set the ansible playbook pid variable
      set_fact:
        ansible_playbook_pid: "{{ ansible_pid.stdout|int }}"
    
    0 讨论(0)
  • 2021-01-17 14:56

    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.

    0 讨论(0)
  • 2021-01-17 15:01

    If you will be using the pid in different plays, just add it to the setup module.

    setup_result['ansible_facts']['ansible_pid'] = os.getpid()
    

    and it will always be available.

        "ansible_os_family": "Debian",
        "ansible_pid": 27930,
        "ansible_pkg_mgr": "apt",
    
    0 讨论(0)
  • 2021-01-17 15:01

    You can refer to the pids module new with v2.8. which delivers all pids for a specific process name to you.

    Simple example to get Pids of Ansible Playbooks on host machines:

    - hosts: localhost
      tasks:
    
        - name: "get pids! and no, 'ansible-playboo' is no typo"
          pids:
            name: ansible-playboo
          register: pids_of_python
    
        - name: "Print pids"
          debug:
            msg: "PIDs: {{ pids_of_python.pids|join(',') }}"
    

    Downside: you'll have to install psutil

    Please refer to https://docs.ansible.com/ansible/latest/modules/pids_module.html

    0 讨论(0)
  • 2021-01-17 15:16

    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
    
    0 讨论(0)
提交回复
热议问题