Last active
April 7, 2021 08:04
-
-
Save nemunaire/26a7f774969973bb1372 to your computer and use it in GitHub Desktop.
An Ansible module to merge files contained in a directory to a single file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python2 | |
import filecmp | |
import json | |
import os | |
import shutil | |
import tempfile | |
def main(): | |
global module | |
module = AnsibleModule( | |
argument_spec = dict( | |
header=dict(required=False), | |
footer=dict(required=False), | |
path=dict(required=True), | |
dest=dict(required=True), | |
owner=dict(required=False), | |
group=dict(required=False), | |
mode=dict(required=False), | |
), | |
supports_check_mode=True | |
) | |
if not os.path.isdir(module.params["path"]): | |
module.fail_json(msg="%s is not a path to an existing directory." % module.params["path"]) | |
if not os.path.isdir(os.path.dirname(module.params["dest"])): | |
module.fail_json(msg="Destination directory (%s) doesn't exist, please create it first." % os.path.dirname(module.params["dest"])) | |
# Open a temporary file for doing the merge | |
fmerge = tempfile.NamedTemporaryFile() | |
if "header" in module.params and module.params["header"]: | |
fmerge.write(module.params["header"]) | |
# Open files contained in the directory, sorted by name | |
files = os.listdir(module.params["path"]) | |
files.sort() | |
for fname in files: | |
fpath = os.path.join(module.params["path"], fname) | |
if os.path.isfile(fpath): | |
with open(fpath) as f: | |
fmerge.write(f.read()) | |
if "footer" in module.params and module.params["footer"]: | |
fmerge.write(module.params["footer"]) | |
fmerge.flush() | |
# Check if the dest file is different | |
if os.path.isfile(module.params["dest"]) and filecmp.cmp(fmerge.name, module.params["dest"]): | |
module.exit_json(changed=False) | |
# Do the swap | |
if not module.check_mode: | |
shutil.copyfile(fmerge.name, module.params["dest"]) | |
# Settings good rights on file | |
if ("owner" in module.params and module.params["owner"]) or ("group" in module.params and module.params["group"]): | |
os.chown(module.params["dest"], | |
module.params["owner"] if "owner" in module.params and module.params["owner"] else -1, | |
module.params["group"] if "group" in module.params and module.params["group"] else -1) | |
if "mode" in module.params and module.params["mode"]: | |
os.chmod(module.params["dest"], module.params["mode"]) | |
module.exit_json(changed=True) | |
from ansible.module_utils.basic import * | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment