Skip to content

Instantly share code, notes, and snippets.

@sed-i
Created February 28, 2024 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sed-i/63f92c5f3e55d6688db79276e852e736 to your computer and use it in GitHub Desktop.
Save sed-i/63f92c5f3e55d6688db79276e852e736 to your computer and use it in GitHub Desktop.
Print out IP addresses to all juju units in the format of /etc/hosts
#!/usr/bin/env python3
# Print out IP addresses to all juju units in the format of /etc/hosts
import yaml
from typing import Set, Tuple
import os
import subprocess
import sys
def stderr(*args, **kwargs):
# https://stackoverflow.com/a/14981125/3516684
print(*args, file=sys.stderr, **kwargs)
def main():
with open(os.path.expanduser("~/.local/share/juju/models.yaml"), "rt") as f:
models_file = f.read()
ctrl_mdl: Set[Tuple[str, str]] = set()
# It is called a models file, but the root keys are controllers
controllers = yaml.safe_load(models_file)
controllers = controllers["controllers"]
for controller_name in controllers:
models = controllers[controller_name]["models"]
for model_name in models:
ctrl_mdl.add((controller_name, model_name))
stderr(ctrl_mdl)
hosts: Set[Tuple[str, str]] = set() # (address, dns_name)
for controller_name, model_name in ctrl_mdl:
stderr(f"Obtaining status for {controller_name}:{model_name}")
cmd = f"juju status -m {controller_name}:{model_name} --format=yaml".split(" ")
try:
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, timeout=5)
except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
stderr("Failed")
else:
status = yaml.safe_load(output)
model_name = status["model"]["name"]
apps = status["applications"]
for app_name in apps:
app = apps[app_name]
if "address" not in app:
# This happens for "controller" models
stderr(f"No addresses for app '{app_name}'")
continue
hosts.add((app["address"], f"{app_name}.{model_name}.juju.internal"))
units = app["units"]
for unit_name in units:
unit = units[unit_name]
address = unit["address"]
unit_id = unit_name.rsplit("/", 1)[-1]
hosts.add((address, f"unit-{unit_id}.{app_name}.{model_name}.juju.internal"))
if unit["leader"]:
hosts.add((address, f"leader.{app_name}.{model_name}.juju.internal"))
for address, dns_name in hosts:
print(address, dns_name)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment