SlideShare a Scribd company logo
© 2016, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Julien Simon, Principal Technical Evangelist
julsimon@amazon.fr
@julsimon
27/04/2016
Using Amazon CloudWatch Events,
AWS Lambda and Spark Streaming
to Process EC2 Events
EC2 Instance Lifecycle
EC2 Lifecycle Hooks – what are they good for?
•  Assign Elastic IP address on launch
•  Register new instances with DNS, message queues,…
•  Pull down log files before instance is terminated
•  Investigate issues with an instance before terminating it
•  Scaling containers on an ECS cluster
What we’re going to build
Kinesis
Firehose
CloudwatchToFirehose
Lambda
S3bucket
firehoseToS3
EC2 CloudWatch
firehose.
put_record()
EMR
Streaming
EC2 events
(autoscaling,
lifecycle)
EC2 event sources in CloudWatch Rules
Auto Scaling events
{
"source": [
"aws.autoscaling"
],
"detail-type": [
"EC2 Instance Launch Successful",
"EC2 Instance Terminate Successful",
"EC2 Instance Launch Unsuccessful",
"EC2 Instance Terminate Unsuccessful",
"EC2 Instance-launch Lifecycle Action",
"EC2 Instance-terminate Lifecycle Action"
]
}
Lifecycle events
{
"source": [
"aws.ec2"
],
"detail-type": [
"EC2 Instance State-change Notification"
]
}
CLI: from CloudWatch Events to Lambda
% aws lambda get-function --function-name CloudwatchToFirehose 
--query "Configuration.FunctionArn”
% aws events put-rule --name EC2AutoScaling 
--event-pattern file://EC2AutoScaling.json --state ENABLED
% aws events put-targets --rule EC2AutoScaling 
--targets Id=1,Arn=FUNCTION_ARN
% aws lambda add-permission --function-name CloudwatchToFirehose 
--statement-id 1 --action 'lambda:InvokeFunction' 
--principal events.amazonaws.com --source-arn RULE_ARN
Lambda function
def lambda_handler(event, context):
print("Received EC2 event: " + json.dumps(event, indent=2))
firehose = boto3.client('firehose')
firehose.put_record(
DeliveryStreamName="firehoseToS3”
Record={"Data":json.dumps(event)}
)
Reminder
a CloudWatch log group is created automatically for each version of your Lambda function
% aws logs describe-log-streams --log-group-name /aws/lambda/CloudwatchToFirehose 
--query "logStreams[].logStreamName"
% aws logs get-log-events --log-stream-name LOG_STREAM_NAME 
--log-group-name /aws/lambda/CloudwatchToFirehose
CLI: from Kinesis Firehose to S3
aws firehose create-delivery-stream 
--delivery-stream-name firehoseToS3 
--s3-destination-configuration 
RoleARN=FIREHOSETOS3_ROLE_ARN, 
BucketARN="arn:aws:s3:::jsimon-public", 
Prefix="firehose", 
BufferingHints={SizeInMBs=1,IntervalInSeconds=60}, 
CompressionFormat=”UNCOMPRESSED", 
EncryptionConfiguration={NoEncryptionConfig="NoEncryption"}
Spark Streaming
import org.apache.log4j.Logger
import org.apache.log4j.Level
import org.apache.spark.streaming.Seconds
Logger.getLogger("org").setLevel(Level.ERROR)
Logger.getLogger("com").setLevel(Level.ERROR)
Logger.getLogger("akka").setLevel(Level.ERROR)
val hadoopConf=sc.hadoopConfiguration;
hadoopConf.set("fs.s3.impl", "org.apache.hadoop.fs.s3native.NativeS3FileSystem")
hadoopConf.set("fs.s3.awsAccessKeyId”, ACCESS_KEY_ID)
hadoopConf.set("fs.s3.awsSecretAccessKey”, SECRET_ACCESS_KEY)
val ssc = new org.apache.spark.streaming.StreamingContext(sc,Seconds(10))
val lines = ssc.textFileStream("s3n://BUCKET_NAME")
lines.print()
ssc.start()
Using Amazon CloudWatch Events,  AWS Lambda and Spark Streaming  to Process EC2 Events

More Related Content

PDF
Deep Dive on Amazon S3 (May 2016)
PDF
AWS Big Data combo
PDF
Scale, baby, scale!
PDF
Scale, baby, scale! (June 2016)
PDF
Deep Dive on Amazon RDS (May 2016)
PDF
Stream Processing in SmartNews #jawsdays
PDF
Building a data warehouse with Amazon Redshift … and a quick look at Amazon ...
PDF
Simplify Big Data with AWS
Deep Dive on Amazon S3 (May 2016)
AWS Big Data combo
Scale, baby, scale!
Scale, baby, scale! (June 2016)
Deep Dive on Amazon RDS (May 2016)
Stream Processing in SmartNews #jawsdays
Building a data warehouse with Amazon Redshift … and a quick look at Amazon ...
Simplify Big Data with AWS

Viewers also liked (19)

PDF
Machine Learning for everyone
PDF
Amazon Redshift (February 2016)
PDF
Best practices for cloud migration (June 2016)
PDF
Hands-on with AWS IoT
PDF
6 stratégies pour migrer vos données dans AWS
PPTX
AWS CodeDeploy
PPTX
Deploying your web application with AWS ElasticBeanstalk
PDF
DevOps with Amazon Web Services (November 2016)
PDF
Creando su primera aplicación Big Data en AWS
PDF
Running Open Source Platforms on AWS (November 2016)
PDF
Running Docker clusters on AWS (June 2016)
PDF
Running Docker clusters on AWS (November 2016)
PDF
Deep Dive on Amazon Relational Database Service (November 2016)
PDF
Deploying a simple Rails application with AWS Elastic Beanstalk
PDF
Deep Learning on AWS (November 2016)
PDF
AWS CloudFormation (February 2016)
PDF
Authentification et autorisation d'accès avec AWS IAM
PDF
An introduction to AWS Direct Connect
PDF
Amazon Inspector
Machine Learning for everyone
Amazon Redshift (February 2016)
Best practices for cloud migration (June 2016)
Hands-on with AWS IoT
6 stratégies pour migrer vos données dans AWS
AWS CodeDeploy
Deploying your web application with AWS ElasticBeanstalk
DevOps with Amazon Web Services (November 2016)
Creando su primera aplicación Big Data en AWS
Running Open Source Platforms on AWS (November 2016)
Running Docker clusters on AWS (June 2016)
Running Docker clusters on AWS (November 2016)
Deep Dive on Amazon Relational Database Service (November 2016)
Deploying a simple Rails application with AWS Elastic Beanstalk
Deep Learning on AWS (November 2016)
AWS CloudFormation (February 2016)
Authentification et autorisation d'accès avec AWS IAM
An introduction to AWS Direct Connect
Amazon Inspector
Ad

Similar to Using Amazon CloudWatch Events, AWS Lambda and Spark Streaming to Process EC2 Events (12)

PDF
Using Amazon CloudWatch Events, AWS Lambda and Spark Streaming to Process EC...
PDF
AWS Cloud Practitioner.PDF
PDF
AWS-Certified-Cloud-Practitioner wiz.pdf
PDF
[Games on AWS 2019] AWS 입문자를 위한 초단기 레벨업 트랙 | AWS 레벨업 하기! : 컨테이너 - 김세호 AWS 솔루션...
PDF
Deploying Data Science with Docker and AWS
PPTX
Architecting Cloud Apps
PPTX
AWS Monitoring & Logging
PDF
WhizCard-CLF-C01-06-09-2022.pdf
KEY
Developing Social Games in the Cloud
PDF
[Jun AWS 201] Technical Workshop
PDF
A 60-mn tour of AWS compute (March 2016)
PDF
X1 Dev Club - Amazon EC2 et al.
Using Amazon CloudWatch Events, AWS Lambda and Spark Streaming to Process EC...
AWS Cloud Practitioner.PDF
AWS-Certified-Cloud-Practitioner wiz.pdf
[Games on AWS 2019] AWS 입문자를 위한 초단기 레벨업 트랙 | AWS 레벨업 하기! : 컨테이너 - 김세호 AWS 솔루션...
Deploying Data Science with Docker and AWS
Architecting Cloud Apps
AWS Monitoring & Logging
WhizCard-CLF-C01-06-09-2022.pdf
Developing Social Games in the Cloud
[Jun AWS 201] Technical Workshop
A 60-mn tour of AWS compute (March 2016)
X1 Dev Club - Amazon EC2 et al.
Ad

More from Julien SIMON (20)

PDF
Implementing high-quality and cost-effiient AI applications with small langua...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
PDF
Arcee AI - building and working with small language models (06/25)
PDF
deep_dive_multihead_latent_attention.pdf
PDF
Deep Dive: Model Distillation with DistillKit
PDF
Deep Dive: Parameter-Efficient Model Adaptation with LoRA and Spectrum
PDF
Building High-Quality Domain-Specific Models with Mergekit
PDF
Tailoring Small Language Models for Enterprise Use Cases
PDF
Tailoring Small Language Models for Enterprise Use Cases
PDF
Julien Simon - Deep Dive: Compiling Deep Learning Models
PDF
Tailoring Small Language Models for Enterprise Use Cases
PDF
Julien Simon - Deep Dive - Optimizing LLM Inference
PDF
Julien Simon - Deep Dive - Accelerating Models with Better Attention Layers
PDF
Julien Simon - Deep Dive - Quantizing LLMs
PDF
Julien Simon - Deep Dive - Model Merging
PDF
An introduction to computer vision with Hugging Face
PDF
Reinventing Deep Learning
 with Hugging Face Transformers
PDF
Building NLP applications with Transformers
PPTX
Building Machine Learning Models Automatically (June 2020)
Implementing high-quality and cost-effiient AI applications with small langua...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Trying to figure out MCP by actually building an app from scratch with open s...
Arcee AI - building and working with small language models (06/25)
deep_dive_multihead_latent_attention.pdf
Deep Dive: Model Distillation with DistillKit
Deep Dive: Parameter-Efficient Model Adaptation with LoRA and Spectrum
Building High-Quality Domain-Specific Models with Mergekit
Tailoring Small Language Models for Enterprise Use Cases
Tailoring Small Language Models for Enterprise Use Cases
Julien Simon - Deep Dive: Compiling Deep Learning Models
Tailoring Small Language Models for Enterprise Use Cases
Julien Simon - Deep Dive - Optimizing LLM Inference
Julien Simon - Deep Dive - Accelerating Models with Better Attention Layers
Julien Simon - Deep Dive - Quantizing LLMs
Julien Simon - Deep Dive - Model Merging
An introduction to computer vision with Hugging Face
Reinventing Deep Learning
 with Hugging Face Transformers
Building NLP applications with Transformers
Building Machine Learning Models Automatically (June 2020)

Recently uploaded (20)

PDF
Encapsulation theory and applications.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
KodekX | Application Modernization Development
PPTX
Cloud computing and distributed systems.
PPT
Teaching material agriculture food technology
PDF
cuic standard and advanced reporting.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Empathic Computing: Creating Shared Understanding
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Encapsulation theory and applications.pdf
Electronic commerce courselecture one. Pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
The Rise and Fall of 3GPP – Time for a Sabbatical?
Reach Out and Touch Someone: Haptics and Empathic Computing
MIND Revenue Release Quarter 2 2025 Press Release
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Spectral efficient network and resource selection model in 5G networks
KodekX | Application Modernization Development
Cloud computing and distributed systems.
Teaching material agriculture food technology
cuic standard and advanced reporting.pdf
The AUB Centre for AI in Media Proposal.docx
MYSQL Presentation for SQL database connectivity
Empathic Computing: Creating Shared Understanding
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Unlocking AI with Model Context Protocol (MCP)
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

Using Amazon CloudWatch Events, AWS Lambda and Spark Streaming to Process EC2 Events

  • 1. © 2016, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Julien Simon, Principal Technical Evangelist julsimon@amazon.fr @julsimon 27/04/2016 Using Amazon CloudWatch Events, AWS Lambda and Spark Streaming to Process EC2 Events
  • 3. EC2 Lifecycle Hooks – what are they good for? •  Assign Elastic IP address on launch •  Register new instances with DNS, message queues,… •  Pull down log files before instance is terminated •  Investigate issues with an instance before terminating it •  Scaling containers on an ECS cluster
  • 4. What we’re going to build Kinesis Firehose CloudwatchToFirehose Lambda S3bucket firehoseToS3 EC2 CloudWatch firehose. put_record() EMR Streaming EC2 events (autoscaling, lifecycle)
  • 5. EC2 event sources in CloudWatch Rules Auto Scaling events { "source": [ "aws.autoscaling" ], "detail-type": [ "EC2 Instance Launch Successful", "EC2 Instance Terminate Successful", "EC2 Instance Launch Unsuccessful", "EC2 Instance Terminate Unsuccessful", "EC2 Instance-launch Lifecycle Action", "EC2 Instance-terminate Lifecycle Action" ] } Lifecycle events { "source": [ "aws.ec2" ], "detail-type": [ "EC2 Instance State-change Notification" ] }
  • 6. CLI: from CloudWatch Events to Lambda % aws lambda get-function --function-name CloudwatchToFirehose --query "Configuration.FunctionArn” % aws events put-rule --name EC2AutoScaling --event-pattern file://EC2AutoScaling.json --state ENABLED % aws events put-targets --rule EC2AutoScaling --targets Id=1,Arn=FUNCTION_ARN % aws lambda add-permission --function-name CloudwatchToFirehose --statement-id 1 --action 'lambda:InvokeFunction' --principal events.amazonaws.com --source-arn RULE_ARN
  • 7. Lambda function def lambda_handler(event, context): print("Received EC2 event: " + json.dumps(event, indent=2)) firehose = boto3.client('firehose') firehose.put_record( DeliveryStreamName="firehoseToS3” Record={"Data":json.dumps(event)} ) Reminder a CloudWatch log group is created automatically for each version of your Lambda function % aws logs describe-log-streams --log-group-name /aws/lambda/CloudwatchToFirehose --query "logStreams[].logStreamName" % aws logs get-log-events --log-stream-name LOG_STREAM_NAME --log-group-name /aws/lambda/CloudwatchToFirehose
  • 8. CLI: from Kinesis Firehose to S3 aws firehose create-delivery-stream --delivery-stream-name firehoseToS3 --s3-destination-configuration RoleARN=FIREHOSETOS3_ROLE_ARN, BucketARN="arn:aws:s3:::jsimon-public", Prefix="firehose", BufferingHints={SizeInMBs=1,IntervalInSeconds=60}, CompressionFormat=”UNCOMPRESSED", EncryptionConfiguration={NoEncryptionConfig="NoEncryption"}
  • 9. Spark Streaming import org.apache.log4j.Logger import org.apache.log4j.Level import org.apache.spark.streaming.Seconds Logger.getLogger("org").setLevel(Level.ERROR) Logger.getLogger("com").setLevel(Level.ERROR) Logger.getLogger("akka").setLevel(Level.ERROR) val hadoopConf=sc.hadoopConfiguration; hadoopConf.set("fs.s3.impl", "org.apache.hadoop.fs.s3native.NativeS3FileSystem") hadoopConf.set("fs.s3.awsAccessKeyId”, ACCESS_KEY_ID) hadoopConf.set("fs.s3.awsSecretAccessKey”, SECRET_ACCESS_KEY) val ssc = new org.apache.spark.streaming.StreamingContext(sc,Seconds(10)) val lines = ssc.textFileStream("s3n://BUCKET_NAME") lines.print() ssc.start()