Allow deleting of Nomad variables

This commit is contained in:
IamTheFij 2023-03-24 09:57:37 -07:00
parent 5fb0e0841e
commit 9f5752c66b

View File

@ -10,18 +10,16 @@ NOMAD_ADDR = getenv("NOMAD_ADDR", "http://127.0.0.1:4646")
NOMAD_TOKEN = getenv("NOMAD_TOKEN") NOMAD_TOKEN = getenv("NOMAD_TOKEN")
def write_var(path: str, items: dict[str, str | float | int]) -> dict: def nomad_req(method: str, path: str, json: dict|None = None) -> dict:
headers = {} headers = {}
if NOMAD_TOKEN: if NOMAD_TOKEN:
headers["X-Nomad-Token"] = NOMAD_TOKEN headers["X-Nomad-Token"] = NOMAD_TOKEN
result = requests.post( result = requests.request(
f"{NOMAD_ADDR}/v1/var/{path}", method,
f"{NOMAD_ADDR}/v1/{path}",
headers=headers, headers=headers,
json={ json=json,
"Path": path,
"Items": {k: str(v) for k, v in items.items()},
},
) )
print(result.text) print(result.text)
@ -30,9 +28,24 @@ def write_var(path: str, items: dict[str, str | float | int]) -> dict:
return result.json() 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(): def write_consul():
with open("./ansible_playbooks/vars/consul_values.yml") as f: with open("./ansible_playbooks/vars/consul_values.yml") as f:
vars = yaml.load(f, yaml.CLoader)["consul_values"] vars = yaml.load(f, yaml.CLoader)["consul_values"]
prefix = "insecure/"
key_values = defaultdict(list) key_values = defaultdict(list)
for path, value in vars.items(): for path, value in vars.items():
@ -41,7 +54,7 @@ def write_consul():
for path, items in key_values.items(): for path, items in key_values.items():
print("path", path, "items", items) print("path", path, "items", items)
response = write_var(path, dict(items)) response = write_var(prefix + path, dict(items))
print(response) print(response)
@ -55,13 +68,18 @@ def write_vault():
response = write_var(prefix + path, items) response = write_var(prefix + path, items)
print(response) print(response)
def write_nomad(): def write_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) print("path", path, "items", items)
response = write_var(path, items) response = None
if items == "DELETE":
response = delete_var(path)
else:
response = write_var(path, items)
print(response) print(response)