Skip to content

Instantly share code, notes, and snippets.

Last active December 11, 2020 22:41
  • Star 10 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
AWS Lambda: Advanced Coding Session -
def lambda_handler(event, context):
# retrieve the Auth token
token = event['authorizationToken']
# this should be retrieved by verifying the token (fake)
principal_id = 'abc123'
policy = create_policy(event['methodArn'], principal_id)
# simple fake check
if event['authorizationToken'] == "webinar":
def create_policy(method_arn, principal_id):
# retrieve API details from Arn
tmp = method_arn.split(':')
region = tmp[3]
account_id = tmp[4]
api_id, stage = tmp[5].split('/')[:2]
# create new AuthPolicy object (defined in the official Blueprint)
policy = AuthPolicy(principal_id, account_id)
policy.restApiId = api_id
policy.region = region
policy.stage = stage
return policy
class AuthPolicy(object):
""" Defined in the official Blueprint """
# open API
echo "Open API"
curl $URL -w "\n"
# with API key
echo "With API key"
curl -H "x-api-key: $API_KEY" $URL -w "\n"
# custom Authorizer with Basic Auth
echo "Custom Authorizer"
curl -H "Authorization: webinar" $URL -w "\n"
"principal_id": "$context.authorizer.principalId"
import boto3
import time
import json
import random
client = boto3.client('kinesis', 'eu-west-1')
STREAM_NAME = 'events'
for index in range(1, 31): # 30 iteratins
n = random.randint(10, 100) # random number btw 10 and 100
print("Generating %s records for 'event%s'" % (n, index))
# push n identical records (just the event name)
'Data': b'name-%s' % index, # will be base64-encoded by boto
'PartitionKey': 'my-partition-key-0001', # arbitrary key
} for i in range(n)
import boto3
import base64
DDB = boto3.resource('dynamodb').Table('events')
def lambda_handler(event, context):
print("Received %s records" % len(event['Records'])) # logging is free!
totals = {}
for record in event['Records']:
payload = base64.b64decode(record['kinesis']['data']) # base64 decode
if not payload in totals:
totals[payload] = 0 # init to 0
totals[payload] += 1 # simply inc
# 1 DDB write for each event name in the given batch (counter update)
for name, total in totals.iteritems():
print("Recording %s %s events" % (total, name)) # logging is free!
Key={'Name': name},
UpdateExpression='ADD EventCount :val',
ExpressionAttributeValues={':val': total},
return 'Successfully processed {} records.'.format(len(event['Records']))
def lambda_handler(event, context):
if event['eventType'] == 'SyncTrigger':
records = event['datasetRecords']
email = records.get('Email') # may be None
if email and email['newValue'].endswith(''):
# guess the Company name
records['Company'] = {
'newValue': 'Cloud Academy, Inc.',
'op': 'replace',
print("New event: %s" % event)
return event # return same structure
// init credentials
AWS.config.region = 'eu-west-1';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: "YOUR_POOL_ID",
var syncClient = new AWS.CognitoSyncManager();
syncClient.openOrCreateDataset('account', function(err, dataset) {
// set Email record
dataset.put('Email', '', function(err, record){
// sync the dataset
onSuccess: function(dataset) {
// verify that the Company record has been set
dataset.get('Company', function(err, data){
alert('Company: ' + data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment