Write a custom Ansible module in Python that checks systemd service status, verifies SHA256 hash of the binary, and only restarts the service if the binary on disk differs from the running version.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a great question about writing a custom Ansible module in Python. I need to create a module that:
Checks systemd service status
Verifies SHA256 hash of the binary
Compares the hash of the binary on disk with the running version
Only restarts the service if they differ
Reports changes appropriately
Let me think about the structure:
The module needs to use AnsibleModule from ansible.module_utils.basic
It should interact with systemd (using systemctl or dbus)
It needs to read the binary file and calculate SHA256 hash
Get the current running process info
Compare hashes and restart if needed
Here's what I need to include:
Module parameters:
service_name (required)
binary_path (optional, can be discovered)
check_mode support
force (optional, to force restart)
Key functions:
Get service status
Get binary path from systemd unit
Calculate SHA256 hash of a file
Get process info of running service
Calculate hash of the running binary
Compare hashes
Restart service if needed
Let me write this comprehensive module:
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
---
module: systemd_service_validator
short_description: Check systemd service status and binary integrity
description:
- Checks if a systemd service's running binary differs from the one on disk
- Verifies SHA256 hash of the binary
- Only restarts the service if the binary has changed
version_added: "2.10"
author:
- "Custom Author"
options:
name:
description:
- Name of the systemd service to check
required: true
type: str
binary_path:
description:
- Path to the binary of the service. If not provided, will be auto-discovered
required: false
type: str
force:
description:
- Force restart even if binary hasn't changed
required: false
type: bool
default: false
state:
description:
- Desired state of the service
required: false
type: str
choices: ['started', 'stopped', 'restarted']
default: 'started'
requirements:
- psutil
- systemd
notes:
- Requires root or appropriate systemd permissions
Usage examples include checking nginx with an explicit binary path, auto-discovering the binary for postgresql, and forcing a redis-server restart. The module returns the service name, the SHA256 hash of the running binary, and the hash of the binary on disk for comparison.
The return values also include whether the hashes match, the current service status, the binary path location, whether a restart occurred, and a descriptive message about the operation. The implementation uses psutil for process inspection and subprocess calls to interact with systemctl for service management.
The get_service_status function queries systemd to determine if a service is active or inactive, handling timeouts and errors appropriately. The get_binary_path_from_unit function parses the systemd unit file to automatically extract the binary path by looking for the ExecStart directive, then isolates the executable path from that line. not HAS_PSUTIL:
module.fail_json(msg=missing_required_lib('psutil'))
code
try:
for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
try:
if service_name in proc.name() or \
(proc.cmdline() and service_name in ' '.join(proc.cmdline())):
return proc.exe()
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
return None
except Exception as e:
raise Exception(f"Failed to find running process for {service_name}: {str(e)}")
def
I'm iterating through active processes to locate the service by matching against its name or command line arguments, then returning the executable path when found. If psutil isn't available, the module fails early. Any process access errors are caught and skipped to continue searching.
Now I need to define a function that restarts the systemd service using subprocess, handling timeouts and errors appropriately. The main function then initializes the Ansible module with parameters for service name, binary path, force flag, and desired state, setting up the result dictionary to track changes and status information.
The logic continues by retrieving the current service status, auto-discovering the binary path if not provided, verifying the binary exists on disk, and calculating its hash. Then it processes the requested state change—whether to start, stop, or restart the service. (module, service_name)
code
if running_binary:
running_hash = calculate_hash(running_binary)
result['running_hash'] = running_hash
if running_hash == disk_hash:
result['hash_match'] = True
result['message'] = f"Service {service_name} is running with current binary"
else:
result['hash_match'] = False
result['message'] = f"Binary mismatch detected for {service_name}: " \
f"running hash={running_hash[:16]}..."
if not force:
if not module.check_mode:
restart_service(module, service_name)
result['changed'] = True
result['restarted'] = True
result['message'] += " - Service restarted"
else:
result['changed'] = False
result['message'] += " (not restarting, force=false would require force=true)"
else:
result['message'] = f"Could not determine binary path of running {service_name}"
except Exception as e:
result['message'] = f"Could not verify running binary: {str(e)}"
if force:
if not module.check_mode:
restart_service(module, service_name)
result['changed'] = True
result['restarted'] = True
else:
result['message'] = f"Service {service_name} is not running"
When the hashes don't match and force isn't set, I restart the service and append a note to the message. If force is true, I skip the restart and note that it would need force=true to proceed. When I can't get the running binary path or encounter an error during verification, I capture that in the message, and only restart if force is enabled. For services that aren't running, I simply record that state.
If the service isn't running, I start it in the actual execution. The module then exits with the result dictionary containing all the status information.
Looking at the logic more carefully, when the hashes match, the service is already running the current binary. If force is enabled, I restart anyway. When hashes don't match, a restart is necessary to load the updated binary. I'm restructuring this to be clearer: check if hashes align, then decide whether to restart based on that comparison and the force flag.
Custom Ansible Module for Systemd Service Validation
Here's a comprehensive custom Ansible module that checks systemd service status and binary integrity:
# 1. Create library directory
mkdir -p library
# 2. Place the module file
cp systemd_service_validator.py library/
# 3. Install dependencies on target systems
ansible all -m pip -a "name=psutil state=present" -b
# 4. Run playbook
ansible-playbook -i inventory playbook.yml
# 5. With verbose output
ansible-playbook -i inventory playbook.yml -v
# 6. Dry-run mode
ansible-playbook -i inventory playbook.yml --check
Key Features
✅ Auto-discovery of binary path from systemd unit files
✅ SHA256 hashing for integrity verification
✅ Process comparison between running and disk binaries
✅ Check mode support for safe dry-runs
✅ Comprehensive error handling and validation
✅ Detailed reporting with hash comparisons
✅ Force restart option to override hash matching
✅ Multiple state options (started, stopped, restarted, checked)
This module provides enterprise-grade systemd service validation with cryptographic integrity checking!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
---
module: systemd_service_validator
short_description: Check systemd service status and binary integrity
description:
- Checks if a systemd service's running binary differs from the one on disk
- Verifies SHA256 hash of the binary
- Only restarts the service if the binary has changed
- Supports check mode for dry-run testing
version_added: "2.10"
author: "DevOps Team"
options:
name:
description: Name of the systemd service to check
required: true
type: str
example: nginx
binary_path:
description:
- Path to the service binary
- If not provided, will attempt auto-discovery from systemd unit
required: false
type: str
example: /usr/sbin/nginx
force:
description: Force restart even if binary hash matches
required: false
type: bool
default: false
state:
description: Desired state of the service
required: false
type: str
choices: ['started', 'stopped', 'restarted', 'checked']
default: 'started'
requirements:
- psutil >= 5.0
notes:
- Requires root or sufficient privileges to read /proc and manage services
- Uses psutil to retrieve running process information
'''
EXAMPLES = '''
- name: Check nginx and restart if binary changed
systemd_service_validator:
name: nginx
binary_path: /usr/sbin/nginx
state: started
- name: Check service with auto-discovery
systemd_service_validator:
name: postgresql
state: started
- name: Force restart service regardless of binary hash
systemd_service_validator:
name: redis-server
force: true
state: restarted
- name: Dry-run check without making changes
systemd_service_validator:
name: mysql
binary_path: /usr/sbin/mysqld
check_mode: yes
'''
RETURN = '''
service_name:
description: Name of the service checked
type: str
returned: always
service_status:
description: Service status (active, inactive, failed, etc)
type: str
returned: always
binary_path:
description: Path to the service binary
type: str
returned: always
disk_hash:
description: SHA256 hash of the binary on disk
type: str
returned: always
running_hash:
description: SHA256 hash of the currently running binary
type: str
returned: when service is running
hash_match:
description: Whether running and disk binary hashes match
type: bool
returned: always
restarted:
description: Whether the service was restarted
type: bool
returned: always
changed:
description: Whether any changes were made
type: bool
returned: always
message:
description: Informational message about the operation
type: str
returned: always
process_info:
description: Information about the running process (PID, etc)
type: dict
returned: when service is running
'''
import hashlib
import os
import subprocess
import re
import sys
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
try:
import psutil
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
class SystemdServiceValidator:
"""Validates systemd service binary integrity"""
def __init__(self, module):
self.module = module
self.service_name = module.params['name']
self.binary_path = module.params['binary_path']
self.force = module.params['force']
self.state = module.params['state']
def get_service_status(self):
"""Get the current status of a systemd service"""
try:
result = subprocess.run(
['systemctl', 'is-active', '--quiet', self.service_name],
capture_output=True,
text=True,
timeout=10
)
# Get detailed status
detail = subprocess.run(
['systemctl', 'show', self.service_name, '-p', 'ActiveState', '-p', 'SubState'],
capture_output=True,
text=True,
timeout=10
)
status = 'active' if result.returncode == 0 else 'inactive'
return status, detail.stdout
except subprocess.TimeoutExpired:
self.module.fail_json(
msg=f"Timeout checking status of {self.service_name}"
)
except Exception as e:
self.module.fail_json(
msg=f"Failed to check service status: {str(e)}"
)
def get_binary_path_from_unit(self):
"""Auto-discover binary path from systemd unit file"""
try:
result = subprocess.run(
['systemctl', 'cat', self.service_name],
capture_output=True,
text=True,
timeout=10
)
if result.returncode != 0:
return None
# Parse ExecStart line
for line in result.stdout.split('\n'):
if line.strip().startswith('ExecStart='):
# Extract the binary path
exec_line = line.split('=', 1)[1].strip()
# Remove any prefixes like @ or -
exec_line = re.sub(r'^[@-+]', '', exec_line)
# Get the first token (the binary path)
binary_path = exec_line.split()[0]
# Expand variables if needed
if '$' in binary_path:
binary_path = os.path.expandvars(binary_path)
return binary_path
return None
except Exception as e:
self.module.debug(f"Failed to auto-discover binary path: {str(e)}")
return None
@staticmethod
def calculate_hash(file_path):
"""Calculate SHA256 hash of a file"""
sha256_hash = hashlib.sha256()
try:
with open(file_path, 'rb') as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
except Exception as e:
raise Exception(f"Failed to calculate hash for {file_path}: {str(e)}")
def get_running_process_binary(self, status):
"""Get the binary path of the running service process"""
if not HAS_PSUTIL:
self.module.fail_json(msg=missing_required_lib('psutil'))
if status != 'active':
return None, None
try:
# Try to find the main process of the service
for proc in psutil.process_iter(['pid', 'name', 'exe', 'cmdline']):
try:
exe = proc.info['exe']
cmdline = proc.info['cmdline']
name = proc.info['name']
# Match by service name in command line or process name
if cmdline and self.service_name in ' '.join(cmdline):
return exe, {
'pid': proc.pid,
'name': name,
'cmdline': ' '.join(cmdline) if cmdline else 'N/A'
}
except (psutil.NoSuchProcess, psutil.AccessDenied,
psutil.ZombieProcess, TypeError):
continue
return None, None
except Exception as e:
raise Exception(
f"Failed to find running process for {self.service_name}: {str(e)}"
)
def restart_service(self):
"""Restart a systemd service"""
if self.module.check_mode:
return True
try:
result = subprocess.run(
['systemctl', 'restart', self.service_name],
capture_output=True,
text=True,
timeout=30
)
if result.returncode != 0:
self.module.fail_json(
msg=f"Failed to restart service {self.service_name}",
stderr=result.stderr
)
return True
except subprocess.TimeoutExpired:
self.module.fail_json(
msg=f"Timeout restarting {self.service_name}"
)
except Exception as e:
self.module.fail_json(
msg=f"Failed to restart service: {str(e)}"
)
def stop_service(self):
"""Stop a systemd service"""
if self.module.check_mode:
return True
try:
subprocess.run(
['systemctl', 'stop', self.service_name],
capture_output=True,
text=True,
timeout=30
)
return True
except Exception as e:
self.module.fail_json(msg=f"Failed to stop service: {str(e)}")
def start_service(self):
"""Start a systemd service"""
if self.module.check_mode:
return True
try:
subprocess.run(
['systemctl', 'start', self.service_name],
capture_output=True,
text=True,
timeout=30
)
return True
except Exception as e:
self.module.fail_json(msg=f"Failed to start service: {str(e)}")
def validate(self):
"""Perform the validation"""
result = {
'changed': False,
'failed': False,
'service_name': self.service_name,
'restarted': False,
'message': '',
'service_status': '',
'hash_match': None,
'binary_path': None,
'disk_hash': None,
'running_hash': None,
'process_info': None,
}
# Get service status
status, _ = self.get_service_status()
result['service_status'] = status
# Determine binary path
if not self.binary_path:
self.binary_path = self.get_binary_path_from_unit()
if not self.binary_path:
self.module.fail_json(
msg=f"Could not determine binary path for {self.service_name}. "
"Please provide binary_path parameter."
)
result['binary_path'] = self.binary_path
# Verify binary exists
if not os.path.exists(self.binary_path):
self.module.fail_json(
msg=f"Binary not found at {self.binary_path}"
)
# Calculate disk hash
try:
disk_hash = self.calculate_hash(self.binary_path)
result['disk_hash'] = disk_hash
except Exception as e:
self.module.fail_json(msg=f"Failed to calculate disk hash: {str(e)}")
# Handle states
if self.state == 'stopped':
if status == 'active':
self.stop_service()
result['changed'] = True
result['restarted'] = True
result['message'] = f"Service '{self.service_name}' stopped"
else:
result['message'] = f"Service '{self.service_name}' already stopped"
elif self.state == 'restarted':
self.restart_service()
result['changed'] = True
result['restarted'] = True
result['message'] = f"Service '{self.service_name}' restarted (forced)"
else: # state == 'started' or 'checked'
if status == 'active':
# Service is running, compare hashes
try:
running_binary, proc_info = self.get_running_process_binary(status)
result['process_info'] = proc_info
if running_binary:
running_hash = self.calculate_hash(running_binary)
result['running_hash'] = running_hash
if running_hash == disk_hash:
result['hash_match'] = True
if self.force:
self.restart_service()
result['changed'] = True
result['restarted'] = True
result['message'] = (
f"Service '{self.service_name}' restarted "
"(force=true)"
)
else:
result['message'] = (
f"Service '{self.service_name}' running with "
"current binary (no restart needed)"
)
else:
result['hash_match'] = False
result['message'] = (
f"Binary mismatch for '{self.service_name}': "
f"running={running_hash[:12]}... "
f"disk={disk_hash[:12]}..."
)
self.restart_service()
result['changed'] = True
result['restarted'] = True
result['message'] += " → Service restarted"
else:
result['message'] = (
f"Could not determine binary of running "
f"'{self.service_name}'"
)
except Exception as e:
self.module.fail_json(
msg=f"Error during validation: {str(e)}"
)
else: # Service not running
result['message'] = f"Service '{self.service_name}' not running"
if self.state == 'started':
self.start_service()
result['changed'] = True
result['restarted'] = True
result['message'] += " → Service started"
return result
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(
type='str',
required=True,
help='Name of the systemd service'
),
binary_path=dict(
type='str',
required=False,
default=None,
help='Path to the service binary'
),
force=dict(
type='bool',
required=False,
default=False,
help='Force restart even if hashes match'
),
state=dict(
type='str',
required=False,
default='started',
choices=['started', 'stopped', 'restarted', 'checked'],
help='Desired service state'
),
),
supports_check_mode=True,
)
if not HAS_PSUTIL:
module.fail_json(msg=missing_required_lib('psutil'))
validator = SystemdServiceValidator(module)
result = validator.validate()
module.exit_json(**result)
if __name__ == '__main__':
main()