-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinv.py
More file actions
46 lines (34 loc) · 1.02 KB
/
inv.py
File metadata and controls
46 lines (34 loc) · 1.02 KB
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
#!/usr/bin/env python3
## Execute from root ansible directory
## ansible-playbook -i dynamic_inventory.py site.yml
## Where site.yml contains all playbooks
## host file for all hosts lives in /metadata/hosts_metadata.yml
import json
import yaml
META_FILE = "hosts.yml"
with open(META_FILE) as f:
data = yaml.safe_load(f)
inventory = {
"_meta": {"hostvars": {}}
}
for host in data["hosts"]:
name = host["name"]
env = host["env"]
roles = host.get("roles", [])
# Group by environment
inventory.setdefault(env, {"hosts": []})
inventory[env]["hosts"].append(name)
# Group by role
for role in roles:
inventory.setdefault(role, {"hosts": []})
inventory[role]["hosts"].append(name)
# Host vars
host_vars = {
"ansible_host": host["ip"],
"environment": env,
"roles": roles,
}
if host.get("local", False):
host_vars["ansible_connection"] = "local"
inventory["_meta"]["hostvars"][name] = host_vars
print(json.dumps(inventory))