From 9bc865e151bb128186037aff6e92e6eae061bbfc Mon Sep 17 00:00:00 2001 From: Menno van Leeuwen Date: Mon, 10 Mar 2025 19:59:34 +0100 Subject: [PATCH] feat: enhance ensure_ansible_collections function to check and install missing Ansible collections --- bin/actions/update.py | 46 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/bin/actions/update.py b/bin/actions/update.py index 85d2264..e2e6a0a 100755 --- a/bin/actions/update.py +++ b/bin/actions/update.py @@ -28,15 +28,47 @@ def ensure_ansible_collections(): ] printfe("cyan", "Checking for required Ansible collections...") - status, output = run_command(["ansible-galaxy", "collection", "list"], shell=False) - if not status: - printfe("red", "Failed to list Ansible collections") - return False + # Get default collections paths from Ansible config + collections_paths = [] + try: + status, output = run_command(["ansible-config", "dump", "COLLECTIONS_PATHS"], shell=False) + if status and output.strip(): + # Extract paths from output which is in format "COLLECTIONS_PATHS(default) = ['/path1', '/path2']" + import re + paths_match = re.search(r'\[(.*)\]', output) + if paths_match: + paths_str = paths_match.group(1) + # Split by comma, strip quotes and whitespace + collections_paths = [p.strip().strip("'\"") for p in paths_str.split(',')] + except Exception as e: + printfe("yellow", f"Failed to get collections paths: {e}") - # Check each required collection and install if missing + # Add default paths if we couldn't get them from config + if not collections_paths: + collections_paths = [ + os.path.expanduser("~/.ansible/collections"), + "/usr/share/ansible/collections" + ] + + # Check if each required collection is installed + missing_collections = [] for collection in required_collections: - if collection not in output: + collection_found = False + namespace, name = collection.split('.') + + for path in collections_paths: + collection_path = os.path.join(path, "ansible_collections", namespace, name) + if os.path.exists(collection_path): + collection_found = True + break + + if not collection_found: + missing_collections.append(collection) + + # Install missing collections + if missing_collections: + for collection in missing_collections: printfe("yellow", f"Installing {collection} collection...") status, install_output = run_command(["ansible-galaxy", "collection", "install", collection], shell=False) if not status: @@ -44,6 +76,8 @@ def ensure_ansible_collections(): printfe("yellow", f"Continuing anyway, but playbook might fail if it requires {collection}") else: printfe("green", f"Successfully installed {collection} collection") + else: + printfe("green", "All required collections are already installed.") return True