AWS lambda function script template, Study notes of Computer science

AWS lambda function script template for amazon web services

Typology: Study notes

2016/2017

Uploaded on 07/25/2017

shipra-bansal-1
shipra-bansal-1 🇮🇳

4.5

(11)

5 documents

1 / 1

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
# Snap_and_Tag Lambda function
#
# This function is triggered when Auto Scaling launches a new instance.
# A snapshot of EBS volumes will be created and a tag will be added.
from __future__ import print_function
import json, boto3
def lambda_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
# Extract the EC2 instance ID from the Auto Scaling event notification
message = event['Records'][0]['Sns']['Message']
autoscalingInfo = json.loads(message)
ec2InstanceId = autoscalingInfo['EC2InstanceId']
# Snapshot all EBS volumes attached to the instance
ec2 = boto3.resource('ec2')
for v in ec2.volumes.filter(Filters=[{'Name': 'attachment.instance-id', 'Values':
[ec2InstanceId]}]):
description = 'Autosnap-%s-%s' % ( ec2InstanceId, v.volume_id )
if v.create_snapshot(Description = description):
print("\t\tSnapshot created with description [%s]" % description)
# Add a tag to the EC2 instance: Key = Snapshots, Value = Created
ec2 = boto3.client('ec2')
response = ec2.create_tags(
Resources=[ec2InstanceId],
Tags=[{'Key': 'Snapshots', 'Value': 'Created'}]
)
print ("***Tag added to EC2 instance with id: " + ec2InstanceId)
# Finished!
return ec2InstanceId

Partial preview of the text

Download AWS lambda function script template and more Study notes Computer science in PDF only on Docsity!

Snap_and_Tag Lambda function

This function is triggered when Auto Scaling launches a new instance.

A snapshot of EBS volumes will be created and a tag will be added.

from future import print_function

import json, boto

def lambda_handler(event, context): print("Received event: " + json.dumps(event, indent=2))

Extract the EC2 instance ID from the Auto Scaling event notification

message = event['Records'][0]['Sns']['Message'] autoscalingInfo = json.loads(message) ec2InstanceId = autoscalingInfo['EC2InstanceId']

Snapshot all EBS volumes attached to the instance

ec2 = boto3.resource('ec2') for v in ec2.volumes.filter(Filters=[{'Name': 'attachment.instance-id', 'Values': [ec2InstanceId]}]): description = 'Autosnap-%s-%s' % ( ec2InstanceId, v.volume_id )

if v.create_snapshot(Description = description): print("\t\tSnapshot created with description [%s]" % description)

Add a tag to the EC2 instance: Key = Snapshots, Value = Created

ec2 = boto3.client('ec2') response = ec2.create_tags( Resources=[ec2InstanceId], Tags=[{'Key': 'Snapshots', 'Value': 'Created'}] ) print ("***Tag added to EC2 instance with id: " + ec2InstanceId)

Finished!

return ec2InstanceId