Skip to content

Instantly share code, notes, and snippets.

@UtahDave
Forked from njpatel/etc-salt-reactor
Last active August 29, 2015 14:07
Show Gist options
  • Save UtahDave/371dd85931cce137ab07 to your computer and use it in GitHub Desktop.
Save UtahDave/371dd85931cce137ab07 to your computer and use it in GitHub Desktop.
<contents of normal file>
# Add any additional locations to look for master runners
runner_dirs: [/srv/runners]
# Register a reactor whenever a cloud provider emits 'created'
# the * is the name of the VM, we want any, but you could
# do something like salt/cloud/Webservers-*/created if you only
# wanted your webservers
reactor:
- 'salt/cloud/*/created':
- /srv/reactor/subdomain.sls
# `runner.subdomain.add` is literally
# run subdomain.py's add method and the first argument to that function is vm_name
# and set vm_name to the name of the vm just created
subdomain:
runner.subdomain.add:
- vm_name: {{ data['name'] }}
import sys
import salt.client
import json
import urllib2
from urllib2 import HTTPError
client_id = DIGITALOCEAN_CLIENT_ID
api_key = DIGITALOCEAN_API_KEY
base_url = "https://api.digitalocean.com/domains/$DOMAIN_NAME/records"
list_url = base_url + "?client_id=%s&api_key=%s"
remove_url = base_url + "/%s/destroy?client_id=%s&api_key=%s"
add_url = base_url + "/new?client_id=%s&api_key=%s&record_type=A&data=%s&name=%s"
def pretty_json(j):
return json.dumps(j, indent=2, separators=(',',':'))
def request(url):
return json.load(urllib2.urlopen(url))
def remove(vm_name):
'''
Remove a vm's subdomain if it already exists
'''
# First get a list of existing records
url = list_url % (client_id, api_key)
try:
res = request(url)
# Try and find a duplicate
records = res['records']
remove = None
for record in records:
if record['name'] == vm_name:
remove = record;
break;
if remove:
print "Removing %s" % pretty_json(remove)
url = remove_url % (remove['id'], client_id, api_key)
res = request(url)
print pretty_json(res)
else:
print "No existing record found"
except HTTPError, e:
print "Unable to list existing records: %s" % e
# vm_name is coming from salt directly, see the .sls file above
def add(vm_name):
'''
Add a new vm to the our cloud domain
'''
client = salt.client.LocalClient(__opts__['conf_file'])
ip = client.cmd(vm_name, 'network.ip_addrs', interface='eth0', timeout=5)[vm_name][0]
remove(vm_name)
print 'Adding %s (%s) to subdomain list' % (vm_name, ip)
url = add_url % (client_id, api_key, ip, vm_name)
try:
res = request(url)
print res
except HTTPError, e:
print "Unable to add record: %s" % e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment