AWS Lambda Serverless Computing with EC2, CloudWatch Alarm, SNS
In this section, we'll learn how to use lambda function with CloudWatch Events to react EC2 launch.
Let's create a lambda function:
Here is the policy attached to "lambda_micro_role":
{ "Version": "2012-10-17", "Statement": [ { "Action": [ "logs:createLogGroup" ], "Resource": "arn:aws:logs:us-east-1:526262051452:*", "Effect": "Allow" }, { "Action": [ "logs:createLogStream", "logs:PutLogEvents" ], "Resource": "arn:aws:logs:us-east-1:526262051452:log-group:*", "Effect": "Allow" } ] }
The role gives our lambda function basic permissions to respond to log events to EC2 instance.
Click "Create function".
We need a new code to receive events and log the events to a log file:
exports.handler = function(event, context) { console.log("MonitorEC2()"); console.log("Here's the event:\n:"+JSON.stringify(event, null, 4)); context.succeed("Ready!"); };
Once pasted the code, click "Save".
Now, we want to trigger the lambda function whenever an EC2 instance is launched (actually, when it is in running status). So, we need to setup CloudWatch Events rule.
Note that we configured the activity of the rule by setting the trigger target as the lambda function, "EC2-Monitor".
To configure details of the rule, click "Configure details":
Click "Create rule":
To test our CloudWatch Event rule and the lambda function, let's launch an instance with Amazon Linux AMI.
Then, go to our lambda function, "EC2-monitor", and click the "Monitoring" tab.
Click "View logs in CloudWatch":
In this section, we'll create a lambda function from the AWS blueprint called "lambda-canary".
It will check if a site has txt string. If not our lambda function throws an error.
Picture source: https://amazon.qwiklabs.com
Click "Configure"
The function code:
from __future__ import print_function import os import urllib2 from datetime import datetime SITE = os.environ['site'] # URL of the site to check, stored in the site environment variable, e.g. https://aws.amazon.com EXPECTED = os.environ['expected'] # String expected to be on the page, stored in the expected environment variable, e.g. Amazon def validate(res): '''Return False to trigger the canary Currently this simply checks whether the EXPECTED string is present. However, you could modify this to perform any number of arbitrary checks on the contents of SITE. ''' return EXPECTED in res def lambda_handler(event, context): print('Checking {} at {}...'.format(SITE, event['time'])) try: opener = urllib2.build_opener() opener.addheaders = [('User-Agent', 'AWS Lambda')] if not validate(opener.open(SITE).read()): raise Exception('Validation failed') except: print('Check failed!') raise else: print('Check passed!') return event['time'] finally: print('Check complete at {}'.format(str(datetime.now())))
Click "Create function".
Time to test.
Click "Create" button at the bottom of the screen.
Click "Test":
Now, let's setup a notification service (SNS). When an alarm is triggered, we'll receive an email. We receive a notification via SNS by subscribing to the topic (email subscription) whenever a message is sent to the topic.
We need to create a SNS topic:
Once we confirm the email subscription, the SNS is now ready to receive messages from CloudWatch Alarm which will be triggered when the Web site check fails.
Let's setup the CloudWatch Alarm.
Click "Select Metric" => "Lambda" => "Across All Functions":
Click "Create Alarm".
Now, we can try with an input that make web site check fail:
Indeed, we get a notification email that tells us there is a failure:
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