I am writing a custom ansible module to get process id with process name using the linux package psutil . this is my module file.
from ansible.module_utils.basic import AnsibleModule
import sys
try:
import psutil
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
def get_pid(name, module):
return [int(p.info['pid']) for p in psutil.process_iter(attrs=['pid', 'name']) if name in p.info['name']]
def main():
module = AnsibleModule(
argument_spec={
"name": {"required": True, "type": "str"}
}
)
if not HAS_PSUTIL:
module.fail_json(msg="Missing required 'psutil' python module. Try installing it with: pip install psutil")
name = module.params["name"]
response = dict(pids=get_pid(name, module))
module.exit_json(**response)
if __name__ == '__main__':
main()
ansible code to use the module
- name: "Checking the process IDs (PIDs) of sleep binary"
pids:
name: "some-long-process-name-999999"
register: pids
- name: "Verify that the Process IDs (PIDs) returned is not empty"
assert:
that:
- "pids.pids | length > 0"
I am getting empty process name when trying with long name, for small name it works fine. Is it some issue with psutil module ? I have tried pidof and pgrep also it also seems to be failing. Can anyone help me with this ? thanks for your time.