--- - hosts: all gather_facts: no become: true become_user: root become_method: sudo vars: remote_dir: /opt/sensusagent tasks: - name: Stop sensusagent systemd service if present ansible.builtin.systemd: name: sensusagent state: stopped ignore_errors: yes - name: Find running agent PIDs by full path ansible.builtin.shell: "pgrep -f '^{{ remote_dir }}/agent( |$)' || true" register: agent_pids changed_when: false failed_when: false - name: Kill agent PIDs if any ansible.builtin.shell: "kill -TERM {{ item }}" loop: "{{ agent_pids.stdout_lines }}" when: agent_pids.stdout != '' changed_when: true failed_when: false - name: Remove remote directory ansible.builtin.file: path: "{{ remote_dir }}" state: absent