#! /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 nomad_req(method: str, path: str, json: dict|None = None) -> dict: headers = {} if NOMAD_TOKEN: headers["X-Nomad-Token"] = NOMAD_TOKEN result = requests.request( method, f"{NOMAD_ADDR}/v1/{path}", headers=headers, 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("GET", f"var/{path}", json={ "Path": path, "Items": {k: str(v) for k, v in items.items()}, }, ) 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"] 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) 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) 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 = None if items == "DELETE": response = delete_var(path) else: response = write_var(path, items) print(response) def main(): write_nomad() if __name__ == "__main__": main()