Skip to content

Instantly share code, notes, and snippets.

@ianmas-aws
Created March 28, 2017 07:43
Show Gist options
  • Save ianmas-aws/ce847270ecedf9a58cbcc1ed736cf541 to your computer and use it in GitHub Desktop.
Save ianmas-aws/ce847270ecedf9a58cbcc1ed736cf541 to your computer and use it in GitHub Desktop.
Example Lambda Fuction for pushing event data into a MongoDB database
# Run this Lambda function inside a VPC with a MongoDB instance inside it.
# Set up security groups to allow the function to communicate with the MongoDB endpoint
# NAT service or NAT instance is required because the function need to access AWS KMS, which an external endpoint
# Set four environment variables for the function containing the details required for the MongoDB endpoint uri
# I used the Bitnami MongoDB install from the AWS Marketplace
import boto3
import os
from base64 import b64decode
from pymongo import MongoClient
print "decrypting enviroment variables"
ENCRYPTEDusername = os.environ['MongoDBusername']
MongoDBusername = boto3.client('kms').decrypt(CiphertextBlob=b64decode(ENCRYPTEDusername))['Plaintext']
ENCRYPTEDpassword = os.environ['MongoDBpassword']
MongoDBpassword = boto3.client('kms').decrypt(CiphertextBlob=b64decode(ENCRYPTEDpassword))['Plaintext']
ENCRYPTEDaddress = os.environ['MongoDBaddress']
MongoDBaddress = boto3.client('kms').decrypt(CiphertextBlob=b64decode(ENCRYPTEDaddress))['Plaintext']
ENCRYPTEDname = os.environ['MongoDBname']
MongoDBname = boto3.client('kms').decrypt(CiphertextBlob=b64decode(ENCRYPTEDname))['Plaintext']
def lambda_handler(event, context):
print "starting function"
print "constructing uri for MongoDB connection"
uri = "mongodb://" + MongoDBusername + ":" + MongoDBpassword + "@" + MongoDBaddress + "/" + MongoDBname
client = MongoClient(uri)
print client
db = client['lambda_demo']
print db
result = db.lambda_demo.insert_one(event)
print result
print "function end"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment