Created
April 28, 2023 09:50
-
-
Save unsafe9/c999136b76ff9036994510fb7bf8691d to your computer and use it in GitHub Desktop.
This file contains 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
import os | |
import subprocess | |
from pathlib import Path | |
import venv | |
CURRENT_DIR = Path(__file__).resolve().parent | |
PROJECT_DIR = CURRENT_DIR.parent | |
VENV_NAME = "venv" | |
VENV_PATH = PROJECT_DIR / VENV_NAME | |
CONFIG_DIR = PROJECT_DIR / "config" | |
CONFIG_IGNORED_EXTS = (".sample", ".example") | |
class AnsibleEnvBuilder(venv.EnvBuilder): | |
def post_setup(self, context): | |
super().post_setup(context) | |
self.install_requirements(context) | |
self.set_env_vars(context) | |
def install_requirements(self, context): | |
pip_path = Path(context.bin_path) / "pip" | |
subprocess.check_call([str(pip_path), "install", "-r", CURRENT_DIR / "requirements.txt"]) | |
def set_env_vars(self, context): | |
# setup environment variables to lookup in ansible. | |
# TODO : unset when deactivating | |
activate_script = Path(context.bin_path) / "activate" | |
with open(str(activate_script), "a") as f: | |
f.write(f"""\n | |
config_dir="{CONFIG_DIR}" | |
config_ignored_exts="{CONFIG_IGNORED_EXTS}" | |
for file in "$config_dir"/*; do | |
if [[ -f "$file" && !( "$config_ignored_exts" =~ *"$(basename $file)" ) ]]; then | |
source "$file" | |
fi | |
done | |
""".lstrip()) | |
if __name__ == "__main__": | |
try: | |
if VENV_PATH.exists(): | |
print("Virtual environment already exists!") | |
exit(1) | |
builder = AnsibleEnvBuilder(with_pip=True) | |
builder.create(str(VENV_PATH)) | |
print("Virtual environment created and configured!") | |
except Exception as e: | |
print(f"An error occurred: {e}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment