Providing complete custom Ansible module code
The full Python code for the requested custom Ansible module is ready, including argument spec, documentation, SHA256 computations, systemd checks, idempotent restart logic, and check_mode support.
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2023
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = r'''
---
module: verify_restart_service
short_description: Check a systemd service and restart it if the binary changed
version_added: "1.0.0"
description:
- This module checks the status of a systemd service, computes the SHA256 hash of the binary on disk
and of the executable that the running service is using, and restarts the service if the hashes differ.
options:
service:
description:
- Name of the systemd unit (service) to manage.
required: true
type: str
binary_path:
description:
- Path to the expected binary on disk.
- This will be hashed and compared to the executable currently used by the running service.
required: true
type: str
author:
- Your Name (@yourhandle)
'''
EXAMPLES = r'''
- name: Restart myservice if its binary has been updated
verify_restart_service:
service: myservice
binary_path: /usr/local/bin/myservice
'''
RETURN = r'''
changed:
description: Whether the service was restarted.
type: bool
returned: always
service_active:
description: Whether the service was running before the module executed.
type: bool
returned: always
sha_disk:
description: SHA256 of the binary on disk.
type: str
returned: always
sha_running:
description: SHA256 of the executable used by the running service (if active).
type: str
returned: when service is active
msg:
description: Human-readable message.
type: str
returned: always
'''
import os
import hashlib
from ansible.module_utils.basic import AnsibleModule
def sha256sum(path):
"""Compute SHA256 for a file"""
h = hashlib.sha256()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(8192), b''):
h.update(chunk)
return h.hexdigest()
def get_service_active(module, service):
rc, out, err = module.run_command(['systemctl', 'is-active', service])
if rc != 0:
# is-active returns non-zero if inactive
return False, out.strip()
return out.strip() == 'active', out.strip()
def get_service_mainpid(module, service):
rc, out, err = module.run_command(['systemctl', 'show', service, '--property', 'MainPID'])
if rc != 0:
module.fail_json(msg="Failed to get MainPID for service %s: %s" % (service, err))
# Output like: MainPID=1234
line = out.strip()
if '=' in line:
_, pid_str = line.split('=', 1)
try:
pid = int(pid_str)
return pid if pid > 0 else None
except ValueError:
return None
return None
def main():
module = AnsibleModule(
argument_spec=dict(
service=dict(type='str', required=True),
binary_path=dict(type='str', required=True),
),
supports_check_mode=True
)
service = module.params['service']
binary_path = module.params['binary_path']
result = {
'changed': False,
'service_active': False,
'sha_disk': None,
'sha_running': None,
'msg': ''
}
if not os.path.exists(binary_path):
module.fail_json(msg="Binary path %s does not exist" % binary_path)
try:
sha_disk = sha256sum(binary_path)
except Exception as e:
module.fail_json(msg="Failed to compute SHA256 of %s: %s" % (binary_path, str(e)))
result['sha_disk'] = sha_disk
active, state_str = get_service_active(module, service)
result['service_active'] = active
if not active:
result['msg'] = "Service %s is not active (%s)" % (service, state_str)
# Service isn't running; nothing to restart based on binary difference
module.exit_json(**result)
pid = get_service_mainpid(module, service)
if pid is None:
module.fail_json(msg="Unable to determine MainPID for running service %s" % service)
running_exe = "/proc/%d/exe" % pid
if not os.path.exists(running_exe):
module.fail_json(msg="Cannot find running executable for PID %d" % pid)
try:
sha_running = sha256sum(running_exe)
except Exception as e:
module.fail_json(msg="Failed to compute SHA256 of running executable %s: %s" % (running_exe, str(e)))
result['sha_running'] = sha_running
if sha_running != sha_disk:
result['msg'] = "Binary on disk differs from running binary"
if module.check_mode:
result['changed'] = True
module.exit_json(**result)
rc, out, err = module.run_command(['systemctl', 'restart', service])
if rc != 0:
module.fail_json(msg="Failed to restart service %s: %s" % (service, err), **result)
result['changed'] = True
result['msg'] = "Service %s restarted due to binary change" % service
else:
result['msg'] = "Binary on disk matches running binary; no restart required"
module.exit_json(**result)
if __name__ == '__main__':
main()