homelab-nomad/nomad_vars.py

92 lines
2.2 KiB
Python
Raw Normal View History

#! /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")
2023-03-24 16:57:37 +00:00
def nomad_req(method: str, path: str, json: dict|None = None) -> dict:
headers = {}
if NOMAD_TOKEN:
headers["X-Nomad-Token"] = NOMAD_TOKEN
2023-03-24 16:57:37 +00:00
result = requests.request(
method,
f"{NOMAD_ADDR}/v1/{path}",
headers=headers,
2023-03-24 16:57:37 +00:00
json=json,
)
print(result.text)
result.raise_for_status()
return result.json()
def write_var(path: str, items: dict[str, str | float | int]) -> dict:
return nomad_req("PUT", f"var/{path}",
json={
"Path": path,
"Items": {k: str(v) for k, v in items.items()},
},
)
2023-03-24 16:57:37 +00:00
def delete_var(path: str) -> dict:
return nomad_req("DELETE", f"var/{path}")
def write_consul():
with open("./ansible_playbooks/vars/consul_values.yml") as f:
vars = yaml.load(f, yaml.CLoader)["consul_values"]
2023-03-24 16:57:37 +00:00
prefix = "insecure/"
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)
2023-03-24 16:57:37 +00:00
response = write_var(prefix + 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)
2023-03-24 16:57:37 +00:00
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)
2023-03-24 16:57:37 +00:00
response = None
if items == "DELETE":
response = delete_var(path)
else:
response = write_var(path, items)
print(response)
def main():
write_nomad()
if __name__ == "__main__":
main()