risotto/ansible/library/compare.py

84 lines
3 KiB
Python
Raw Normal View History

2022-12-21 16:35:58 +01:00
#!/usr/bin/python3
from time import sleep
2023-01-23 20:23:32 +01:00
from os import fdopen, walk, readlink, chdir, getcwd
from os.path import join, islink, isdir
2022-12-21 16:35:58 +01:00
from ansible.module_utils.basic import AnsibleModule
def run_module():
# define available arguments/parameters a user can pass to the module
module_args = dict(
2023-01-23 20:23:32 +01:00
# shasums=dict(type='dict', required=True),
directories=dict(type='list', required=True),
2022-12-21 16:35:58 +01:00
)
# seed the result dict in the object
# we primarily care about changed and state
# changed is if this module effectively modified the target
# state will include any data that you want your module to pass back
# for consumption, for example, in a subsequent task
result = dict(
2023-01-23 20:23:32 +01:00
directories={},
2022-12-21 16:35:58 +01:00
)
# the AnsibleModule object will be our abstraction working with Ansible
# this includes instantiation, a couple of common attr would be the
# args/params passed to the execution, as well as if the module
# supports check mode
module = AnsibleModule(
argument_spec=module_args,
2023-01-23 20:23:32 +01:00
supports_check_mode=True,
2022-12-21 16:35:58 +01:00
)
2023-01-23 20:23:32 +01:00
current_path = getcwd()
for directory in module.params['directories']:
result['directories'][directory] = {}
if not isdir(directory):
continue
chdir(directory)
search_paths = [join(directory_[2:], f) for directory_, subdirectories, files in walk('.') for f in files]
for path in search_paths:
full_path = join(directory, path)
if not islink(full_path):
result['directories'][directory][path] = module.digest_from_file(full_path, 'sha256')
2022-12-21 16:35:58 +01:00
else:
2023-01-23 20:23:32 +01:00
result['directories'][directory][path] = readlink(full_path)
chdir(current_path)
# current_path = getcwd()
# for server_name, dico in module.params['shasums'].items():
# root = dico['config_dir']
# if not isdir(root):
# result['machines_changed'].append(server_name)
# continue
# chdir(root)
# search_paths = [join(directory[2:], f) for directory, subdirectories, files in walk('.') for f in files]
# chdir(current_path)
# for path in search_paths:
# if path in dico['shasums']:
# full_path = join(root, path)
# if not islink(full_path):
# if module.digest_from_file(full_path, 'sha256') != dico['shasums'][path]:
# result['machines_changed'].append(server_name)
# break
# elif dico['shasums'][path] != readlink(full_path):
# result['machines_changed'].append(server_name)
# break
# del dico['shasums'][path]
# else:
# result['machines_changed'].append(server_name)
# break
# if server_name not in result['machines_changed'] and dico['shasums']:
# result['machines_changed'].append(server_name)
2022-12-21 16:35:58 +01:00
module.exit_json(**result)
def main():
run_module()
if __name__ == '__main__':
main()