-
Notifications
You must be signed in to change notification settings - Fork 0
/
inventory.py
executable file
·87 lines (69 loc) · 2.27 KB
/
inventory.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python3
import json
import logging
import os
from pathlib import Path
import re
import subprocess
from typing import Any
import yaml
logger = logging.getLogger(__name__)
def get_default_gateway() -> str | None:
try:
# Check if running in WSL2
with Path("/proc/version").open("r") as file:
if "microsoft-standard-WSL2" not in file.read():
return None
# Run the 'ip route show' command
result = subprocess.run(
["ip", "route", "show"],
stdout=subprocess.PIPE,
check=True,
)
output = result.stdout.decode("utf-8")
# Use regex to find the default gateway IP address
match = re.search(r"default via (\S+)", output)
if match:
return match.group(1)
except Exception as e:
logger.info(e)
return None
def get_inventory() -> dict[str, dict[str, Any]]:
user_home = os.getenv("HOME")
user_home = user_home or ""
if not user_home:
raise Exception("HOME env variable is not set")
config_file_path = Path(user_home) / ".blueprint" / "config.yaml"
with config_file_path.open() as f:
configs = yaml.safe_load(f)
inventory = {
"local": {
"hosts": ["localhost"],
"vars": {
"ansible_connection": "local",
"ansible_python_interpreter": "/usr/bin/python3",
},
},
}
if not configs.get("win_user"):
return inventory
host_name = os.getenv("NAME")
if not host_name:
return inventory
if not configs.get("win_user").get(host_name):
return inventory
win_home = configs["win_user"][host_name]["home"]
ansible_python_interpreter = (
f"{win_home}\\AppData\\Local\\Programs\\Python\\Python312\\python.exe"
)
inventory["win"] = {
"hosts": [get_default_gateway()],
"vars": {
"ansible_shell_type": "cmd",
"ansible_connection": "ssh",
"ansible_python_interpreter": ansible_python_interpreter,
},
}
return inventory
if __name__ == "__main__":
print(json.dumps(get_inventory()))