Advertisement
Guest User

Untitled

a guest
Oct 14th, 2016
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.25 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. "Action": [
  30. "ec2:CreateNetworkInterface"
  31. ],
  32. "Resource": [
  33. "*"
  34. ],
  35. "Effect": "Allow"
  36. }
  37. ]
  38. }
  39. """
  40.  
  41. print('Loading function')
  42.  
  43. def lambda_handler(event, context):
  44. cfnMsgParams = {}
  45. print("Event received: " + json.dumps(event))
  46. for record in event['Records']:
  47. if 'Sns' in record:
  48. msg = record['Sns']['Message'].encode('ascii', 'replace')
  49. for line in str.split(msg, '\n'):
  50. if '=' not in line:
  51. continue
  52. key, value = str.split(line, '=')
  53. key = key.replace('\'', '')
  54. value = value.replace('\'', '')
  55. cfnMsgParams[key] = value
  56.  
  57. if cfnMsgParams['ResourceStatus'] == 'CREATE_COMPLETE':
  58. region = str.split(cfnMsgParams['StackId'], ':')[3]
  59.  
  60. if cfnMsgParams['ResourceType'] == 'AWS::RDS::DBInstance':
  61.  
  62. # Construct the ARN of the RDS DB Instance
  63. arn = ':'.join(['arn', 'aws', 'rds', region, cfnMsgParams['Namespace'], 'db', cfnMsgParams['PhysicalResourceId']])
  64.  
  65. # Snag Master Username & Password from CloudFormation notification message
  66. RDSResourceProperties = json.loads(cfnMsgParams['ResourceProperties'])
  67. master_pw = RDSResourceProperties['MasterUserPassword']
  68. master_un = RDSResourceProperties['MasterUsername']
  69. db_name = RDSResourceProperties['DBName']
  70.  
  71. try:
  72. # Use the IAM policy, above, to query AWS for the DBInstance Endpoint Address
  73. rds = boto3.client('rds')
  74. instance = rds.describe_db_instances(DBInstanceIdentifier = arn)['DBInstances'][0]
  75. host = instance['Endpoint']['Address']
  76. except:
  77. raise Exception('Could not query AWS for DBInstance Endpoint Address')
  78.  
  79. for tag in RDSResourceProperties['Tags']:
  80. if tag['Key'] == 'AppPassword':
  81. app_pw = tag['Value']
  82. if tag['Key'] == 'AppUsername':
  83. app_un = tag['Value']
  84.  
  85. try:
  86. pg = connect(user=master_un, host=host, password=master_pw, dbname=db_name)
  87. pg.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
  88. except:
  89. raise Exception('Could not connect to PostgreSQL at ' + host)
  90.  
  91. cursor = pg.cursor()
  92. cursor.execute('select rolname from pg_roles where rolname = \'' + app_un + '\';');
  93. if len(cursor.fetchall()) > 0:
  94. print app_un + ' role already exists. Exiting.'
  95. else:
  96. try:
  97. cursor.execute('CREATE ROLE ' + app_un + ' WITH LOGIN PASSWORD \'' + app_pw + '\'')
  98. print 'Created role ' + app_un + ' with password ' + app_pw
  99. except:
  100. raise Exception('Could not create role ' + app_un)
  101.  
  102. cursor.close()
  103. pg.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement