Created
January 8, 2019 18:27
-
-
Save 1davidmichael/e35214fbd98dcf7418c4a9fdd87a520d to your computer and use it in GitHub Desktop.
Example Lambda Custom Resource to create a MySQL database on RDS
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
import json | |
import MySQLdb | |
import os | |
import requests | |
def handler(event, context): | |
if event['RequestType'] == 'Create' or event['RequestType'] == 'Update': | |
parameters = event['ResourceProperties'] | |
create_db( | |
user=parameters['DBUsername'], | |
passwd=parameters['DBPassword'], | |
host=parameters['DBHost'], | |
port=parameters['DBPort'], | |
db_name=parameters['DBName'] | |
) | |
send_response( | |
event, | |
context, | |
"SUCCESS", | |
"Resource %s successful" % event['RequestType'] | |
) | |
elif event['RequestType'] == 'Delete': | |
send_response( | |
event, | |
context, | |
"SUCCESS", | |
"Resource %s successful" % event['RequestType'] | |
) | |
else: | |
send_response( | |
event, | |
context, | |
"FAILED", | |
"Resource %s failed" % event['RequestType'] | |
) | |
def send_response(event, context, response_status, response_data): | |
'''Send a resource manipulation status response to CloudFormation''' | |
response_body = json.dumps( | |
{ | |
"Status": response_status, | |
"Reason": context.log_stream_name, | |
"StackId": event['StackId'], | |
"RequestId": event['RequestId'], | |
"LogicalResourceId": event['LogicalResourceId'], | |
"Data": {"Message": response_data} | |
} | |
) | |
headers = { | |
"Content-Type": '', | |
"Content-Length": len(response_body) | |
} | |
requests.put( | |
event['ResponseURL'], | |
headers=headers, | |
data=response_body | |
) | |
def create_db(user, passwd, host, port, db_name): | |
db = MySQLdb.connect( | |
user=os.environ['DB_USERNAME'], | |
passwd=os.environ['DB_PASSWORD'], | |
host=os.environ['DB_HOST'], | |
port=os.environ['DB_PORT'] | |
) | |
cursor = db.cursor() | |
cursor.execute('CREATE DATABASE IF NOT EXISTS %s' % db_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment