diff --git a/.gitignore b/.gitignore index ace00ac8ad581331eced697688888b9bcb69cde3..f4fe304d17b3a578f5fce6763ee0f5db8255520f 100644 --- a/.gitignore +++ b/.gitignore @@ -23,4 +23,6 @@ docs/source/lso.rst docs/source/lso.*.rst docs/source/modules.rst +artifactory/ + .env diff --git a/ansible_inventory_generator/app.py b/ansible_inventory_generator/app.py index 4eed9d02f97656e53d56cc8bdb0799e9f4e5144d..ecd806475e37fb39247708466a4682ea1c52a476 100644 --- a/ansible_inventory_generator/app.py +++ b/ansible_inventory_generator/app.py @@ -1,3 +1,4 @@ +import os import shutil import sys import tempfile @@ -78,9 +79,11 @@ def generate_host_vars_and_hosts_file(router_subscriptions: list, temp_dir: Path @contextmanager -def safe_write(temp_dir: Path, old_host_vars_dir: Path) -> Generator[Path, None, None]: +def safe_write(temp_dir: Path) -> Generator[Path, None, None]: + settings = load_settings() temp_dir.mkdir(exist_ok=True) - + ansible_inventory_path = Path(settings.aig_ansible_inventory_path) + ansible_inventory_path.mkdir(exist_ok=True) try: yield temp_dir except Exception as e: @@ -88,11 +91,16 @@ def safe_write(temp_dir: Path, old_host_vars_dir: Path) -> Generator[Path, None, typer.echo(f"Error: {e}") sys.exit(1) else: - if old_host_vars_dir.exists(): - shutil.rmtree(old_host_vars_dir) + host_vars = ansible_inventory_path / "host_vars" + if host_vars.exists(): + shutil.rmtree(host_vars) - shutil.copytree(temp_dir, old_host_vars_dir) # Copy new host_vars dir - shutil.copy(temp_dir / "hosts.yaml", old_host_vars_dir) # Copy new hosts.yaml file + hosts_file = ansible_inventory_path / "hosts.yaml" + if hosts_file.exists(): + os.remove(hosts_file) + + shutil.copytree(temp_dir / "host_vars", ansible_inventory_path / "host_vars") # Copy new host_vars dir + shutil.copy(temp_dir / "hosts.yaml", ansible_inventory_path) # Copy new hosts.yaml file shutil.rmtree(temp_dir) @@ -111,9 +119,7 @@ def generate_inventory_from_api() -> None: sys.exit(1) temp_dir = Path(tempfile.mkdtemp()) - old_host_vars_dir = Path(settings.aig_ansible_inventory_path) - - with safe_write(temp_dir, old_host_vars_dir) as temp_dir: + with safe_write(temp_dir) as temp_dir: generate_host_vars_and_hosts_file(router_subscriptions, temp_dir)