LoginSignup
6
5

More than 5 years have passed since last update.

AWS:TAGで指定したサーバのEBS Snapshotを取得

Last updated at Posted at 2015-10-19

LambdaでPythonがサポートされたので使ってみる

Python初心者なので、勉強がてらLambda Pythonを使ってみました。
Rootボリュームしか取っていないので、手が空いたら配列処理するよう改良します。

ebs_backup.py
import os, time
import json
import boto3
from datetime import datetime

#=== setting - Change here!!!
tag_name1 = "myServer1"

#=== execute take snapshot
def execute_snapshot(ebs_id):
    ec2 = boto3.resource('ec2')
    ebs = ec2.Volume(ebs_id)
    try:
        now = datetime.now()
        desc = "%s_%s" % (tag_name1, now.strftime("%Y%m%d"))
        snap = ebs.create_snapshot(Description=desc)
        snap.create_tags(
            Tags=[
                {
                'Key': 'Name',
                'Value': tag_name1
                },
                {
                'Key': 'Date',
                'Value': now.strftime("%Y%m%d")
                },
            ]
        )
    except:
        return "NG"
    return "OK"

#=== get EC2 Info
def get_ec2_info(tag_name):
    client = boto3.client('ec2')
    info_ec2 = client.describe_instances(
        Filters=[
            {
                'Name': 'tag-value',
                'Values': [
                    tag_name,
                ]
            },
        ]
    )
    try:
        ec2_ebs = info_ec2['Reservations'][0]['Instances'][0]['BlockDeviceMappings'][0]['Ebs']['VolumeId']
    except:
        print "NG"
    return ec2_ebs

#=== main process
def lambda_handler(event, context):
    print '========= Make Snapshot(%s): %s =========' % (tag_name1, datetime.now())
    ebs_id = get_ec2_info(tag_name1)
    result = execute_snapshot(ebs_id)
    print '========= Process is %s. End time(Volid=%s): %s =========' % (result, ebs_id, datetime.now())
    return "OK"

LambdaのCron使うとめちゃ便利!

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5