11
change_type = os.environ.get("ENSEMBLE_CHANGE")
13
change_unit = os.environ.get("ENSEMBLE_REMOTE_UNIT")
14
# We'll name the database the same as the service.
15
database_name, _ = change_unit.split("/")
16
# A user per service unit so we can deny access quickly
17
user = change_unit.replace("/","-")
22
passwd = open("/var/lib/ensemble/mysql.passwd").read().strip()
24
connection = MySQLdb.connect(user="root", host="localhost", passwd=passwd)
26
return connection.cursor()
30
cursor = get_db_cursor()
32
# Find existing databases
33
cursor.execute("show databases")
34
databases = [i[0] for i in cursor.fetchall()]
36
# Determine if we need to create a new database
37
if database_name not in databases:
40
"create database `%s` character set utf8" % database_name)
42
# Create database user and grant access
43
service_password = "".join(random.sample(string.letters, 10))
45
"grant all on `%s`.* to `%s` identified by '%s'" % (
50
cursor.execute("flush privileges")
54
hostname = urllib.urlopen(
55
"http://169.254.169.254/latest/meta-data/local-hostname").read()
57
print "setting values"
58
print "host", hostname
59
print "database", database_name
61
print "password", service_password
64
print str(["relation-set",
65
"database=%s" % database_name,
67
"password=%s" % service_password,
68
'host=%s' % hostname,])
70
# Store new values in relation settings.
73
"database=%s" % database_name,
75
"password=%s" % service_password,
76
'host=%s' % hostname,],
82
cursor = get_db_cursor()
83
cursor.execute("revoke all privileges on `%s`.* from `%s`" % (database_name, user))
84
print "revoked privileges for `%s` on database `%s`" % (user, database_name)
86
if change_type == "joined":
88
elif change_type == "departed":
91
if connection is not None:
2
echo "Nothing to do on modified"