Check instances are really up with Cloud-Init
#!/usr/bin/env python | |
""" | |
Boot the VMs with the following cloud-init, and then start this code: | |
#cloud-config | |
phone_home: | |
url: http://x.x.x.x:8000/$INSTANCE_ID/ | |
post: [ hostname, fqdn ] | |
""" | |
import SocketServer | |
import BaseHTTPServer | |
import requests | |
import os | |
import urlparse | |
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler): | |
def do_HEAD(s): | |
s.send_response(200) | |
s.send_header("Content-type", "text/html") | |
s.end_headers() | |
def do_GET(s): | |
"""Respond to a GET request.""" | |
global instances | |
if s.path.startswith("/reset"): | |
instances = [] | |
s.send_response(200) | |
s.send_header("Content-type", "text/html") | |
s.end_headers() | |
return | |
body = "%d instances registered\n" % len(set(instances)) | |
for instance in set(instances): | |
body = body + instance + "\n" | |
s.send_response(200) | |
s.send_header("Content-type", "text/html") | |
s.end_headers() | |
s.wfile.write(body) | |
def do_POST(s): | |
"""Respond to a POST request.""" | |
global instances | |
length = int(s.headers.getheader('content-length')) | |
field_data = s.rfile.read(length) | |
fields = urlparse.parse_qs(field_data) | |
print "Instance %s just registered\n" % fields['hostname'][0] | |
instances.append(fields['hostname'][0]) | |
print "Total number of instances registered: %d" % len(set(instances)) | |
# Send back a HTTP 200 so the instance will stop trying to register | |
s.send_response(200) | |
instances = [] | |
PORT = 8000 | |
Handler = MyHandler | |
httpd = SocketServer.TCPServer(("", PORT), Handler) | |
print "serving at port", PORT | |
httpd.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment