Use nomad-python client for setting nomad vars

This commit is contained in:
IamTheFij 2023-07-07 15:52:52 -07:00
parent b75f8fce7b
commit 486df58bac

View File

@ -1,91 +1,28 @@
#! /usr/bin/env python3 #! /usr/bin/env python3
from collections import defaultdict
from os import getenv
import requests
import yaml import yaml
from nomad import Nomad
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) -> requests.Response:
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
def write_var(path: str, items: dict[str, str | float | int]) -> requests.Response:
return nomad_req("PUT", f"var/{path}",
json={
"Path": path,
"Items": {k: str(v) for k, v in items.items()},
},
)
def delete_var(path: str) -> requests.Response:
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(): def write_nomad():
nomad = Nomad()
with open("./ansible_playbooks/vars/nomad_vars.yml") as f: with open("./ansible_playbooks/vars/nomad_vars.yml") as f:
vars = yaml.load(f, yaml.CLoader) vars = yaml.load(f, yaml.CLoader)
for path, items in vars.items(): for path, items in vars.items():
print("path", path, "items", items) # ignore special path there for terraform
response = None if path == "nomad/oidc":
if items == "DELETE": continue
response = delete_var(path)
else:
response = write_var(path, items)
try: print("path", path, "items", items)
response.raise_for_status() if items == "DELETE":
except: print(nomad.variable.delete_variable(path))
print(response.text) else:
raise print(
nomad.variable.create_variable(
path,
{"Path": path, "Items": {k: str(v) for k, v in items.items()}},
)
)
def main(): def main():