homelab-nomad/nomad_vars.py
2023-03-24 08:55:23 -07:00

74 lines
1.8 KiB
Python
Executable File

#! /usr/bin/env python3
from collections import defaultdict
from os import getenv
import requests
import yaml
NOMAD_ADDR = getenv("NOMAD_ADDR", "http://127.0.0.1:4646")
NOMAD_TOKEN = getenv("NOMAD_TOKEN")
def write_var(path: str, items: dict[str, str | float | int]) -> dict:
headers = {}
if NOMAD_TOKEN:
headers["X-Nomad-Token"] = NOMAD_TOKEN
result = requests.post(
f"{NOMAD_ADDR}/v1/var/{path}",
headers=headers,
json={
"Path": path,
"Items": {k: str(v) for k, v in items.items()},
},
)
print(result.text)
result.raise_for_status()
return result.json()
def write_consul():
with open("./ansible_playbooks/vars/consul_values.yml") as f:
vars = yaml.load(f, yaml.CLoader)["consul_values"]
key_values = defaultdict(list)
for path, value in vars.items():
path, _, item = path.rpartition("/")
key_values[path].append((item, value))
for path, items in key_values.items():
print("path", path, "items", items)
response = write_var(path, dict(items))
print(response)
def write_vault():
with open("./ansible_playbooks/vars/vault_hashi_vault_values.yml") as f:
vars = yaml.load(f, yaml.CLoader)["hashi_vault_values"]
prefix = "secrets/"
for path, items in vars.items():
print("path", path, "items", items)
response = write_var(prefix + path, items)
print(response)
def write_nomad():
with open("./ansible_playbooks/vars/nomad_vars.yml") as f:
vars = yaml.load(f, yaml.CLoader)
for path, items in vars.items():
print("path", path, "items", items)
response = write_var(path, items)
print(response)
def main():
write_nomad()
if __name__ == "__main__":
main()