通过AWS创建包含描述的快照Lambda
这是我通过AWS Lambda创建快照的代码。通过AWS创建包含描述的快照Lambda
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 = 14
for volume in ec.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"))
print 'description: %s' % (description)
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},
]
)
我得到以下响应:
'EC2' object has no attribute 'volumes': AttributeError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 34, in lambda_handler
for volume in ec.volumes.filter(Filters=[
AttributeError: 'EC2' object has no attribute 'volumes'
Whgen我用EC = boto3.resource( 'EC2')代替EC = boto3.client( 'EC2' ),我得到的描述,但其他一些如describe_instances不起作用
那么,请告诉我是什么替代卷是boto3.client( 'EC2')
我发现这些家伙的解决方案是迄今为止最好的:
https://blog.powerupcloud.com/2016/02/15/automate-ebs-snapshots-using-lambda-function/
在其代码库中添加了描述的例子被添加到快照中。
boto3.resource
是低电平boto3.client
你混合两者的抽象。如果您使用client.describe_instances
,则使用client.describe_volumes
。
如果要使用resource.volumes
,请使用resource.instances
。由于其强大的过滤和抽象,我更喜欢resource.instances
。如果您使用资源并且由于某种原因想要访问底层客户端,则可以使用meta
获取底层客户端。
ec2 = boto3.resource('ec2')
client = ec2.meta.client
避免处理预订等,请使用resource.instances
。如果你是谷歌的话,有很多例子。几行代码,非常可读。
谢谢你的宝贵意见。我现在要做的就是向快照添加一个描述。您能否告诉我如何在不更改代码的情况下添加该代码? – prudhvi
我有同样的问题,但对我来说,我需要所有的标签从EC2实例拷贝到快照,看看我的代码它可以帮助你或执法机关指导您:
这样做,这样,你只需要确保该实例具有“名称”标签,因此它可以被复制到快照,我还需要这一点,因为CostCenter标签的
这满足了我的要求。谢谢 – prudhvi