Background

備份一直以來都是一件很重要的事. 那剛好介紹一下如何用AWS中EBS Snapshot來進行備份. 其實AWS他有提供Cloud Watch的event (類似crontab的東西) 來幫你進行自動備份. 但可以他沒有自動刪除 Snapshot 的功能. 那因為怕一直備份然後忘記刪掉. Cost會增加, 所以我只好就自己寫程式來控制.

Code

#-*- coding: utf-8 -*-
#!/usr/bin/env python3

from __future__ import print_function
from pprint import pprint
from datetime import datetime, timedelta

import imp
import sys
import getopt
import os
import ujson

def main(volume_id_list):
    for v in volume_id_list:
        print("============", v, "============")
        print("=== get snapshot list ===")
        command_str = "/usr/local/bin/aws ec2 describe-snapshots --filters Name=volume-id,Values=" + str(v)
        print(command_str)
        result = os.popen(command_str).read()
        #print(result)
        result = ujson.loads(result)

        for s in result['Snapshots']:
            d = datetime.strptime(s['StartTime'], "%Y-%m-%dT%H:%M:%S.%fZ")
            week_ago = datetime.now() - timedelta(days=7)

            if 'Description' in s and s['Description'] == "This is regular backup.":
                if d < week_ago:
                    print("past", d)
                    print("week_ago", week_ago)
                    delete_str = "/usr/local/bin/aws ec2 delete-snapshot --snapshot-id " + str(s['SnapshotId'])
                    print("=== delete snapshot ===")
                    print(delete_str)
                    os.system(delete_str)

        # create snapshot
        command_str = '/usr/local/bin/aws ec2 create-snapshot --volume-id ' + str(v) + ' --description "This is regular backup."'
        print("=== create snapshot ===")
        print(command_str)
        os.system(command_str)
        print()

if __name__ == "__main__":

    start = datetime.now()
    argv = sys.argv[1:]

    try:
      opts, args = getopt.getopt(argv,"h",["help"])
    except getopt.GetoptError:
      print('Usage: python snapshot.py')
      sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print('Usage: python snapshot.py')
            sys.exit()

    # parameter of volume-id (need to change here)
    volume_id_list = ["vol-11111111", "vol-22222222"]

    main(volume_id_list)

    end = datetime.now()
    print([str(start), str(end), str(end - start)])

其實大家可以自己改上面的code以符合自己的需求. 我的需求是每天備份一次(搭配crontab). 超過7天的備份檔會自動刪除.