Skip to content

Commit

Permalink
Ensure that cache directory is writable
Browse files Browse the repository at this point in the history
  • Loading branch information
ssbarnea committed Jan 28, 2025
1 parent 83c5cfb commit b2f0fd8
Showing 1 changed file with 27 additions and 5 deletions.
32 changes: 27 additions & 5 deletions src/ansible_compat/prerun.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Utilities for configuring ansible runtime environment."""

import hashlib
import os
import tempfile
from pathlib import Path


Expand All @@ -13,17 +15,37 @@ def get_cache_dir(project_dir: Path, *, isolated: bool = True) -> Path:
Returns:
Cache directory path.
Raises:
RuntimeError: if cache directory is not writable.
"""
cache_dir = Path(os.environ.get("ANSIBLE_HOME", "~/.ansible")).expanduser()

if "VIRTUAL_ENV" in os.environ:
cache_dir = Path(os.environ["VIRTUAL_ENV"]) / ".ansible"
path = Path(os.environ["VIRTUAL_ENV"])
if not path.exists():
msg = f"VIRTUAL_ENV={os.environ['VIRTUAL_ENV']} does not exist."
raise RuntimeError(msg)
cache_dir = path.resolve() / ".ansible"
elif isolated:
cache_dir = project_dir / ".ansible"
else:
cache_dir = Path(os.environ.get("ANSIBLE_HOME", "~/.ansible")).expanduser()
if not project_dir.exists() or not os.access(project_dir, os.W_OK):
# As "project_dir" can also be "/" and user might not be able
# to write to it, we use a temporary directory as fallback.
checksum = hashlib.sha256(
project_dir.as_posix().encode("utf-8"),
).hexdigest()[:4]

cache_dir = Path(tempfile.gettempdir()) / f".ansible-{checksum}"
cache_dir.mkdir(parents=True, exist_ok=True)
else:
cache_dir = project_dir.resolve() / ".ansible"

# Ensure basic folder structure exists so `ansible-galaxy list` does not
# fail with: None of the provided paths were usable. Please specify a valid path with
if not os.access(cache_dir, os.W_OK):
msg = f"Cache directory {cache_dir} is not writable."
raise RuntimeError(msg)

for name in ("roles", "collections"): # pragma: no cover
(cache_dir / name).mkdir(parents=True, exist_ok=True)

return cache_dir

0 comments on commit b2f0fd8

Please sign in to comment.