0% found this document useful (0 votes)
59 views3 pages

CloudWatch Events

The document contains a CloudWatch event triggered by an EC2 instance stopping in us-east-1 region. It also contains Lambda code to start the stopped instance. A separate CloudWatch schedule event is shown to create EBS snapshots of tagged instances and retain them according to the tag retention period.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views3 pages

CloudWatch Events

The document contains a CloudWatch event triggered by an EC2 instance stopping in us-east-1 region. It also contains Lambda code to start the stopped instance. A separate CloudWatch schedule event is shown to create EBS snapshots of tagged instances and retain them according to the tag retention period.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

CloudWatch Lambda Event:

{
"version": "0",
"id": "556d4090-aff5-4a2f-764e-c20cda89a5e9",
"detail-type": "EC2 Instance State-change Notification",
"source": "aws.ec2",
"account": "721834156908",
"time": "2020-12-22T16:01:45Z",
"region": "us-east-1",
"resources": [
"arn:aws:ec2:us-east-1:721834156908:instance/i-046301d1732bb7734"
],
"detail": {
"instance-id": "i-046301d1732bb7734",
"state": "stopped"
}
}

Code for Starting the EC2 Machine using Lambda:


import json
import boto3

def lambda_handler(event, context):


inst = event['detail']['instance-id']
client = boto3.client('ec2')
response = client.start_instances(
InstanceIds=[
inst
])
print(f'Server {inst} was been started')

CloudWatch Schedule Event:


import boto3
import collections
import datetime

ec = boto3.client('ec2')

def lambda_handler(event, context):


reservations = ec.describe_instances(
Filters=[
{'Name': 'tag-key', 'Values': ['backup', 'Backup']},
]
).get(
'Reservations', []
)

instances = sum(
[
[i for i in r['Instances']]
for r in reservations
], [])

print "Found %d instances that need backing up" % len(instances)

to_tag = collections.defaultdict(list)

for instance in instances:


try:
retention_days = [
int(t.get('Value')) for t in instance['Tags']
if t['Key'] == 'Retention'][0]
except IndexError:
retention_days = 10

for dev in instance['BlockDeviceMappings']:


if dev.get('Ebs', None) is None:
continue
vol_id = dev['Ebs']['VolumeId']
print "Found EBS volume %s on instance %s" % (
vol_id, instance['InstanceId'])
snap = ec.create_snapshot(
VolumeId=vol_id,
)

to_tag[retention_days].append(snap['SnapshotId'])

print "Retaining snapshot %s of volume %s from instance %s for %d


days" % (
snap['SnapshotId'],
vol_id,
instance['InstanceId'],
retention_days,
)

for retention_days in to_tag.keys():


delete_date = datetime.date.today() +
datetime.timedelta(days=retention_days)
delete_fmt = delete_date.strftime('%Y-%m-%d')
print "Will delete %d snapshots on %s" % (len(to_tag[retention_days]),
delete_fmt)
ec.create_tags(
Resources=to_tag[retention_days],
Tags=[
{'Key': 'DeleteOn', 'Value': delete_fmt},
{'Key': 'Name', 'Value': "LIVE-BACKUP"}
]
)

You might also like