我想通过脚本制作EBS卷的快照,它将在1天后自动删除。
scorpiochenyr 回答:如何从AWS CLI制作EBS卷的快照?
您可以使用create-snapshot命令创建快照:
aws ec2 create-snapshot --volume-id abcd1234
创建快照时,不可能指定要删除快照的时间。
但是,您可以使用Amazon EBS Snapshot Lifecycle来配置何时应通过一系列规则删除快照。快照生命周期可以通过AWS CLI进行配置,尽管通过控制台更容易做到。
,我有这个。
首先,使用这些策略创建一个IAM用户。
#!/usr/bin/env python3
# backup.py --volume-ids=vol-6b25bca2 --volume-ids=vol-6b25bca2 --expiry-days=1#
# 0 */3 * * * python3 /home/ubuntu/aws/snapshot_script.py --volume-ids=vol-010ce65755eb3f71e --expiry-days=1
import argparse
import subprocess
import json
import logging
import time,datetime,dateutil.parser
profile = 'backup' # Your AWS CLI profile
region = 'ap-southeast-1' # replace this region to your EC2 instance region
def bash(command):
process = subprocess.Popen(command,stdout=subprocess.PIPE)
return process.communicate()[0].decode('utf-8')
def getOurSnapshots():
"""
Return a list of snapshot Dicts created with this plugin.
"""
return json.loads(bash([
"aws","ec2","describe-snapshots","--filters","Name=tag-key,Values=Group","Name=tag-value,Values=backup","--profile",profile,"--region",region,"--output=json"
]))['Snapshots']
def createSnapshots(volumeIds):
"""
Return True if snapshots of the given volumes are created,else False
Keyword arguments:
volumeIds -- List of EBS volume IDs
"""
# Create the snapshots
snapshots = []
for volumeId in volumeIds:
snapshots.append(createSnapshotForVolume(volumeId))
# Add Name and Group tags to the snapshot
if len(snapshots):
snapshotIds = []
date = time.strftime("%Y-%m-%d")
for snapshot in snapshots:
snapshotIds.append(snapshot['SnapshotId'])
# create-tags returns no output now so just perform the command and
# return True
bash([
"aws","create-tags","--resources",' '.join(snapshotIds),"--tags","Key=Name,Value='Snapshot "+date+"'","Key=Group,Value=backup","--output=json"
])
return True
return False
def createSnapshotForVolume(volumeId):
"""
Return a Dict of a created snapshot for the given EBS volume
Keyword arguments:
volumeId -- An EBS volume ID
"""
date = time.strftime("%Y-%m-%d")
message = "Creating snapshot for volume "+volumeId+"..."
response = json.loads(bash([
"aws","create-snapshot","--volume-id",volumeId,"--description","Volume Snapshot"+date,"--output=json"
]))
message += response['SnapshotId']
logging.info(message)
return response
def deleteOldSnapshots(snapshots,max_age):
"""
Delete all listed snapshots older than max_age
"""
snapshotIds = []
date = datetime.datetime.now()
for snapshot in snapshots:
snapshotDate = dateutil.parser.parse(snapshot['StartTime']).replace(tzinfo=None)
dateDiff = date - snapshotDate
if dateDiff.days >= max_age:
message = "Deleting snapshot "+snapshot['SnapshotId']+" ("+str(dateDiff.days)+" days old)..."
# delete-snapshot no longer returns any output
bash([
"aws","delete-snapshot","--snapshot-id",snapshot['SnapshotId'],"--output=json"
])
message += "done"
logging.info(message)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='ADD YOUR DESCRIPTION HERE')
parser.add_argument('-i','--volume-ids',help='EBS volume ID',required=True)
parser.add_argument('-d','--delete-old',help='Delete old snapshots?',required=False,type=bool,default=True)
parser.add_argument('-x','--expiry-days',help='Number of days to keep snapshots',type=int,default=7)
args = parser.parse_args()
logging.basicConfig(filename='backup.log',level=logging.DEBUG,format='%(asctime)s:%(message)s',datefmt='%Y-%m-%d %I:%M:%S%p')
# Get all active volumes
volumeIds = args.volume_ids.split(',')
# Create the snapshots
if len(volumeIds):
snapshots = createSnapshots(volumeIds)
pass
# Delete snapshots older than expiry-days
if args.delete_old:
deleteOldSnapshots(getOurSnapshots(),args.expiry_days)
然后通过 aws configure 命令配置awscli。
在此之后,为crontab创建.sh脚本。
0 */3 * * * python3 /home/ubuntu/aws/snapshot_script.py --volume-ids=vol-01fc7eeece0c20d97 --expiry-days=1
最后,根据您的卷名添加一个crontab,创建快照时间并删除快照时间。
This database failed to load.