feat: update Ansible collection retrieval to use ansible-galaxy for improved accuracy
Some checks failed
Nix Format Check / check-format (push) Failing after 39s

This commit is contained in:
Menno van Leeuwen 2025-03-10 20:41:49 +01:00
parent 8611e203c6
commit f7787c592b
Signed by: vleeuwenmenno
SSH Key Fingerprint: SHA256:OJFmjANpakwD3F2Rsws4GLtbdz1TJ5tkQF0RZmF0TRE

View File

@ -29,41 +29,50 @@ def ensure_ansible_collections():
printfe("cyan", "Checking for required Ansible collections...")
# 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}")
# Get list of installed collections using ansible-galaxy
status, output = run_command(["ansible-galaxy", "collection", "list"], shell=False)
if not status:
printfe("yellow", f"Failed to list Ansible collections: {output}")
printfe("yellow", "Will try to install all required collections.")
installed_collections = []
else:
# Parse output to get installed collections
installed_collections = []
# 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"
]
# Split output into lines and process
lines = output.splitlines()
collection_section = False
# Check if each required collection is installed
for line in lines:
line = line.strip()
# Skip empty lines
if not line:
continue
# Check if we've reached the collection listing section
if line.startswith("Collection"):
collection_section = True
continue
# Skip the separator line after the header
if collection_section and line.startswith("--"):
continue
# Process collection entries
if collection_section and " " in line:
# Format is typically: "community.general 10.4.0"
parts = line.split()
if len(parts) >= 1:
collection_name = parts[0]
installed_collections.append(collection_name)
printfe("cyan", f"Found installed collections: {', '.join(installed_collections) if installed_collections else 'none'}")
# Check which required collections are missing
missing_collections = []
for collection in required_collections:
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:
if collection not in installed_collections:
missing_collections.append(collection)
# Install missing collections