Skip to content

Commit

Permalink
Add 'report_diff' key in result data in case of available diff data
Browse files Browse the repository at this point in the history
In case that a 'diff' key with 'before' and 'after' data is available
create a unified diff from 'before' and 'after' and store below the
'report_diff' key as a string for later consumption in config reports
on the Foreman server.
Remove the 'diff' key afterwards to save space as it contains the full
contents of the saved file before and after the change.

Signed-off-by: Ruediger Pluem <[email protected]>
  • Loading branch information
rpluem-vf committed Jan 20, 2025
1 parent 5f5ba20 commit 78494d0
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions plugins/callback/foreman.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@
from collections import defaultdict
import json
import time
import difflib

try:
import requests
Expand All @@ -122,6 +123,16 @@
from ansible.module_utils.parsing.convert_bool import boolean as to_bool
from ansible.plugins.callback import CallbackBase

def create_report_diff(diff_data):
"""
Create a unified diff string from the contents of the file before and
after the change.
"""
before = diff_data['before'].splitlines(True)
after = diff_data['after'].splitlines(True)
diff = difflib.unified_diff(before, after, formfile=diff_data['before_header'],
tofile=diff_data['after_header'])
return ''.join(diff)

def build_log_foreman(data_list):
"""
Expand All @@ -140,6 +151,16 @@ def build_log_foreman(data_list):
else:
level = 'info'

# Check is the 'diff' key is set and its sub data structure is as
# expected. In this case transform the contents of the file before
# and after the change into a unified diff string and store it
# below the 'report_diff' key. Remove the 'diff' key afterwards
# as the content of a file is probably big.
if (('diff' in result) and isinstance(result['diff'], list) and
result['diff'] and isinstance(result['diff'][0], dict)):
result['report_diff'] = create_report_diff(result['diff'][0])
del result['diff']

yield {
"log": {
'sources': {
Expand Down

0 comments on commit 78494d0

Please sign in to comment.