import boto3
import datetime
import time
import os
ec2 = boto3.resource('ec2', region_name='ap-northeast-2')
ec = boto3.client('ec2')
def create_backup_snapshot():
print("\n\nAWS snapshot backups starting at %s" % datetime.datetime.now())
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values': ['running']},{'Name': 'tag:Name', 'Values': ['*DSTG*']},{'Name': 'tag:BackupYN', 'Values': ['Y']}])
for instance in instances:
instance_name = filter(lambda tag: tag['Key'] == 'Name', instance.tags)[0]['Value']
print("instance_name [%s]" % instance_name)
for volume in ec2.volumes.filter(Filters=[{'Name': 'attachment.instance-id', 'Values': [instance.id]}]):
description = 'scheduled-%s.%s-%s' % (instance_name, volume.volume_id,
datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
response = volume.create_snapshot(Description=description, VolumeId=volume.volume_id)
if response:
print("Snapshot created with description [%s]" % description)
ec2.create_tags( Resources=[response.snapshot_id],
Tags=[
{'Key': 'Name', 'Value': description}
])
#snapshot = ec2.Snapshot(response.snapshot_id)
#snapshot.create_tags(Tags=[{'Key': 'Name','Value': description}])
def backup_snapshot():
print("\n\nAWS snapshot backups starting at %s" % datetime.datetime.now())
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']},{'Name': 'tag:Name', 'Values': ['*DSTG*']}])
for instance in instances:
instance_name = filter(lambda tag: tag['Key'] == 'Name', instance.tags)[0]['Value']
print("instance_name [%s]" % instance_name)
create_time = datetime.datetime.now()
create_fmt = create_time.strftime('%Y-%m-%d')
AMIid = ec.create_image(InstanceId=instance.id, Name="Lambda-" + instance_name +"-"+instance.id + " from " + create_fmt, Description="Lambda created AMI of instance " + instance.id + " from " + create_fmt, NoReboot=True, DryRun=False)
print("\n\nAWS snapshot backups completed at %s" % datetime.datetime.now())
def lambda_handler(event, context):
backup_snapshot()
#create_backup_snapshot()
return 'successful'
댓글 없음:
댓글 쓰기