Forked from niedbalski/update-juju-unit-hostnames.py
Created
October 24, 2018 22:45
-
-
Save seffyroff/e019cc34464f7389ff5abae428ee14d1 to your computer and use it in GitHub Desktop.
update-juju-unit-hostnames.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
This script will update all the juju units using | |
the hostname defined on the provided dns server | |
Usage: | |
{0} ip-of-maas-dns-server | |
""" | |
import subprocess | |
import yaml | |
import sys | |
def juju_status(juju_env=None): | |
cmd = ['juju', 'status'] | |
if juju_env: | |
cmd.append(['-e', juju_env]) | |
status_raw = subprocess.check_output(cmd) | |
return yaml.safe_load(status_raw) | |
def dig(ip_addr, dns_server): | |
return subprocess.check_output(["dig", "-x", ip_addr, "@"+dns_server, "+short"])[0:-1] | |
def juju_run(unit, command): | |
return subprocess.check_call(["juju", "run", "--unit", unit, command]) | |
def set_hostname_to_dns_name(dns): | |
status = juju_status() | |
for service in status.get('services'): | |
try: | |
service_units = status['services'][service]['units'] | |
for unit, info in service_units.items(): | |
public_addr = info['public-address'] | |
resolved = dig(public_addr, dns) | |
if resolved != "": | |
print "Setting unit:%s hostname to: %s" % (unit, resolved) | |
juju_run(unit, "sudo hostnamectl set-hostname %s && echo '%s %s' >> /etc/hosts" % (resolved, public_addr, resolved)) | |
except KeyError: | |
pass | |
def main(): | |
if not len(sys.argv) > 1: | |
print __doc__.format(sys.argv[0]) | |
sys.exit(-1) | |
set_hostname_to_dns_name(sys.argv[1]) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment