Skip to content

Instantly share code, notes, and snippets.

@niedbalski
Created March 3, 2016 22:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save niedbalski/bf87d20ce03b3308c4c7 to your computer and use it in GitHub Desktop.
Save niedbalski/bf87d20ce03b3308c4c7 to your computer and use it in GitHub Desktop.
update-juju-unit-hostnames.py
#!/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