AWS Amazon DynamoDB with Lambda and CloudWatch
Amazon DynamoDB is a fully managed proprietary NoSQL database service. It uses synchronous replication across multiple datacenters for high durability and availability.
In this post, to put data into a DynamoDB table, we'll use Write Data to a Table Using the Console or AWS CLI.
Picture credit : How to Create an AWS IAM Policy to Grant AWS Lambda Access to an Amazon DynamoDB Table
In this post, we'll do the following:
- Create a DynamoDB table, Music.
- Create an IAM role, DynamoDBStreamLambdaRole that has AWS policy, AWSLambdaDynamoDBExecutionRole.
- Create a Lambda function, MusicEventProcessor, with the permission specified in AWSLambdaDynamoDBExecutionRole.
- Set event trigger on DynamoDB. Set the trigger Lambda function as MusicEventProcessor.
- Then we create some events by INSERT/MODIFY/DELETE on DynamoDB Table either via CLI or console.
- Check if events have been triggered using Monitoring section of Lambda and CloudWatch Log.
Create a Music table in Amazon DynamoDB with the following details:
- Partition key — Artist
- Sort key — SongTitle
The rest of the steps are from Step 1: Create a Table
Create an IAM role, DynamoDBStreamLambdaRole that has AWS managed policy, AWSLambdaDynamoDBExecutionRole as shown below:
Create a Lambda function, MusicEventProcessor, with the permission specified in AWSLambdaDynamoDBExecutionRole:
The function code looks like this:
import json print('Loading function') def lambda_handler(event, context): print('------------------------') print(event) #1. Iterate over each record try: for record in event['Records']: #2. Handle event by type if record['eventName'] == 'INSERT': handle_insert(record) elif record['eventName'] == 'MODIFY': handle_modify(record) elif record['eventName'] == 'REMOVE': handle_remove(record) print('------------------------') return "Success!" except Exception as e: print(e) print('------------------------') return "Error" def handle_insert(record): print("Handling INSERT Event") #3a. Get newImage content newImage = record['dynamodb']['NewImage'] #3b. Parse values newArtist = newImage['Artist']['S'] newSongTitle = newImage['SongTitle']['S'] #3c. Print it print ('New row added with newArtistId=' + newArtist + "SongTitle=" + SongTitle) print("Done handling INSERT Event") def handle_modify(record): print("Handling MODIFY Event") #3a. Parse oldImage and score oldImage = record['dynamodb']['OldImage'] oldAwards = oldImage['awards']['N'] #3b. Parse oldImage and score newImage = record['dynamodb']['NewImage'] newAwards = newImage['awards']['N'] #3c. Check for change if oldAwards != newAwards: print('Awards changed - oldAwards=' + str(oldAwards) + ', newAwards=' + str(newAwards)) print("Done handling MODIFY Event") def handle_remove(record): print("Handling REMOVE Event") #3a. Parse oldImage oldImage = record['dynamodb']['OldImage'] #3b. Parse values oldArtist = oldImage['Artist']['S'] #3c. Print it print ('Row removed with Artist=' + oldArtist) print("Done handling REMOVE Event")
Actually, I borrowed the code from AWS DynamoDB Streams to Lambda Tutorial in Python | Step by Step Guide and modifed a bit for the Music table.
Also, the OldImage or NewImage are DynamoDB specific, and we can find more info from StreamRecord.
Let's set event trigger on DynamoDB. Set the trigger Lambda function as MusicEventProcessor
We can create some events of INSERT/MODIFY/DELETE.
We can either work on console or use CLI (Step 2: Write Data to a Table Using the Console or AWS CLI), for example, put:
aws dynamodb put-item \ --table-name Music \ --item \ '{"Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Call Me Today"}, "AlbumTitle": {"S": "Somewhat Famous"}, "Awards": {"N": "1"}}' aws dynamodb put-item \ --table-name Music \ --item \ '{"Artist": {"S": "Acme Band"}, "SongTitle": {"S": "Happy Day"}, "AlbumTitle": {"S": "Songs About Life"}, "Awards": {"N": "10"} }'
Finally, we need to check if events have been triggered using Monitoring section of Lambda and CloudWatch Log.
AWS (Amazon Web Services)
- AWS : EKS (Elastic Container Service for Kubernetes)
- AWS : Creating a snapshot (cloning an image)
- AWS : Attaching Amazon EBS volume to an instance
- AWS : Adding swap space to an attached volume via mkswap and swapon
- AWS : Creating an EC2 instance and attaching Amazon EBS volume to the instance using Python boto module with User data
- AWS : Creating an instance to a new region by copying an AMI
- AWS : S3 (Simple Storage Service) 1
- AWS : S3 (Simple Storage Service) 2 - Creating and Deleting a Bucket
- AWS : S3 (Simple Storage Service) 3 - Bucket Versioning
- AWS : S3 (Simple Storage Service) 4 - Uploading a large file
- AWS : S3 (Simple Storage Service) 5 - Uploading folders/files recursively
- AWS : S3 (Simple Storage Service) 6 - Bucket Policy for File/Folder View/Download
- AWS : S3 (Simple Storage Service) 7 - How to Copy or Move Objects from one region to another
- AWS : S3 (Simple Storage Service) 8 - Archiving S3 Data to Glacier
- AWS : Creating a CloudFront distribution with an Amazon S3 origin
- AWS : Creating VPC with CloudFormation
- AWS : WAF (Web Application Firewall) with preconfigured CloudFormation template and Web ACL for CloudFront distribution
- AWS : CloudWatch & Logs with Lambda Function / S3
- AWS : Lambda Serverless Computing with EC2, CloudWatch Alarm, SNS
- AWS : Lambda and SNS - cross account
- AWS : CLI (Command Line Interface)
- AWS : CLI (ECS with ALB & autoscaling)
- AWS : ECS with cloudformation and json task definition
- AWS Application Load Balancer (ALB) and ECS with Flask app
- AWS : Load Balancing with HAProxy (High Availability Proxy)
- AWS : VirtualBox on EC2
- AWS : NTP setup on EC2
- AWS: jq with AWS
- AWS & OpenSSL : Creating / Installing a Server SSL Certificate
- AWS : OpenVPN Access Server 2 Install
- AWS : VPC (Virtual Private Cloud) 1 - netmask, subnets, default gateway, and CIDR
- AWS : VPC (Virtual Private Cloud) 2 - VPC Wizard
- AWS : VPC (Virtual Private Cloud) 3 - VPC Wizard with NAT
- DevOps / Sys Admin Q & A (VI) - AWS VPC setup (public/private subnets with NAT)
- AWS - OpenVPN Protocols : PPTP, L2TP/IPsec, and OpenVPN
- AWS : Autoscaling group (ASG)
- AWS : Setting up Autoscaling Alarms and Notifications via CLI and Cloudformation
- AWS : Adding a SSH User Account on Linux Instance
- AWS : Windows Servers - Remote Desktop Connections using RDP
- AWS : Scheduled stopping and starting an instance - python & cron
- AWS : Detecting stopped instance and sending an alert email using Mandrill smtp
- AWS : Elastic Beanstalk with NodeJS
- AWS : Elastic Beanstalk Inplace/Rolling Blue/Green Deploy
- AWS : Identity and Access Management (IAM) Roles for Amazon EC2
- AWS : Identity and Access Management (IAM) Policies, sts AssumeRole, and delegate access across AWS accounts
- AWS : Identity and Access Management (IAM) sts assume role via aws cli2
- AWS : Creating IAM Roles and associating them with EC2 Instances in CloudFormation
- AWS Identity and Access Management (IAM) Roles, SSO(Single Sign On), SAML(Security Assertion Markup Language), IdP(identity provider), STS(Security Token Service), and ADFS(Active Directory Federation Services)
- AWS : Amazon Route 53
- AWS : Amazon Route 53 - DNS (Domain Name Server) setup
- AWS : Amazon Route 53 - subdomain setup and virtual host on Nginx
- AWS Amazon Route 53 : Private Hosted Zone
- AWS : SNS (Simple Notification Service) example with ELB and CloudWatch
- AWS : Lambda with AWS CloudTrail
- AWS : SQS (Simple Queue Service) with NodeJS and AWS SDK
- AWS : Redshift data warehouse
- AWS : CloudFormation
- AWS : CloudFormation Bootstrap UserData/Metadata
- AWS : CloudFormation - Creating an ASG with rolling update
- AWS : Cloudformation Cross-stack reference
- AWS : OpsWorks
- AWS : Network Load Balancer (NLB) with Autoscaling group (ASG)
- AWS CodeDeploy : Deploy an Application from GitHub
- AWS EC2 Container Service (ECS)
- AWS EC2 Container Service (ECS) II
- AWS Hello World Lambda Function
- AWS Lambda Function Q & A
- AWS Node.js Lambda Function & API Gateway
- AWS API Gateway endpoint invoking Lambda function
- AWS API Gateway invoking Lambda function with Terraform
- AWS API Gateway invoking Lambda function with Terraform - Lambda Container
- Amazon Kinesis Streams
- AWS: Kinesis Data Firehose with Lambda and ElasticSearch
- Amazon DynamoDB
- Amazon DynamoDB with Lambda and CloudWatch
- Loading DynamoDB stream to AWS Elasticsearch service with Lambda
- Amazon ML (Machine Learning)
- Simple Systems Manager (SSM)
- AWS : RDS Connecting to a DB Instance Running the SQL Server Database Engine
- AWS : RDS Importing and Exporting SQL Server Data
- AWS : RDS PostgreSQL & pgAdmin III
- AWS : RDS PostgreSQL 2 - Creating/Deleting a Table
- AWS : MySQL Replication : Master-slave
- AWS : MySQL backup & restore
- AWS RDS : Cross-Region Read Replicas for MySQL and Snapshots for PostgreSQL
- AWS : Restoring Postgres on EC2 instance from S3 backup
- AWS : Q & A
- AWS : Security
- AWS : Security groups vs. network ACLs
- AWS : Scaling-Up
- AWS : Networking
- AWS : Single Sign-on (SSO) with Okta
- AWS : JIT (Just-in-Time) with Okta
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization