Advertisement
Guest User

Untitled

a guest
Oct 7th, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.72 KB | None | 0 0
  1. import json
  2. import boto3
  3. from psycopg2 import connect
  4. from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
  5.  
  6.  
  7. """ IAM policy:
  8. {
  9. "Version": "2012-10-17",
  10. "Statement": [
  11. {
  12. "Effect": "Allow",
  13. "Action": [
  14. "logs:CreateLogGroup",
  15. "logs:CreateLogStream",
  16. "logs:PutLogEvents"
  17. ],
  18. "Resource": "arn:aws:logs:*:*:*"
  19. },
  20. {
  21. "Sid": "Stmt1475849820226",
  22. "Action": [
  23. "rds:DescribeDBInstances"
  24. ],
  25. "Effect": "Allow",
  26. "Resource": "arn:aws:rds:*"
  27. }
  28. ]
  29. }
  30. """
  31.  
  32. print('Loading function')
  33.  
  34. def lambda_handler(event, context):
  35. cfnMsgParams = {}
  36. print("Event received: " + json.dumps(event))
  37. for record in event['Records']:
  38. if 'Sns' in record:
  39. msg = record['Sns']['Message'].encode('ascii', 'replace')
  40. for line in str.split(msg, '\n'):
  41. if '=' not in line:
  42. continue
  43. key, value = str.split(line, '=')
  44. key = key.replace('\'', '')
  45. value = value.replace('\'', '')
  46. cfnMsgParams[key] = value
  47.  
  48. if cfnMsgParams['ResourceStatus'] == 'CREATE_COMPLETE':
  49. region = str.split(cfnMsgParams['StackId'], ':')[3]
  50.  
  51. if cfnMsgParams['ResourceType'] == 'AWS::RDS::DBInstance':
  52.  
  53. # Construct the ARN of the RDS DB Instance
  54. arn = ':'.join(['arn', 'aws', 'rds', region, cfnMsgParams['Namespace'], 'db', cfnMsgParams['PhysicalResourceId']])
  55.  
  56. # Snag Master Username & Password from CloudFormation notification message
  57. RDSResourceProperties = json.loads(cfnMsgParams['ResourceProperties'])
  58. master_pw = RDSResourceProperties['MasterUserPassword']
  59. master_un = RDSResourceProperties['MasterUsername']
  60. db_name = RDSResourceProperties['DBName']
  61.  
  62. try:
  63. # Use the IAM policy, above, to query AWS for the DBInstance Endpoint Address
  64. rds = boto3.client('rds')
  65. instance = rds.describe_db_instances(DBInstanceIdentifier = arn)['DBInstances'][0]
  66. host = instance['Endpoint']['Address']
  67. except:
  68. raise Exception('Could not query AWS for DBInstance Endpoint Address')
  69.  
  70. for tag in RDSResourceProperties['Tags']:
  71. if tag['Key'] == 'AppPassword':
  72. app_pw = tag['Value']
  73. if tag['Key'] == 'AppUsername':
  74. app_un = tag['Value']
  75.  
  76. try:
  77. pg = connect(user=master_un, host=host, password=master_pw, dbname=db_name)
  78. pg.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
  79. cursor = pg.cursor()
  80. cursor.execute('CREATE ROLE ' + app_un + ' WITH LOGIN PASSWORD \'' + app_pw + '\'')
  81. cursor.close()
  82. pg.close()
  83. except:
  84. raise Exception('Could not connect to PostgreSQL at ' + host)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement