Python noob在这里。我最近遇到了一个博客网站,该网站教授如何使用lambda& amp;来自动化EBS快照。蟒蛇。该脚本运行完美,技术上做了我想要的一切,除了我无法弄清楚如何在boto3 lib中添加AWS标签。
import boto3
import datetime
import pytz
import os
ec2 = boto3.resource('ec2')
def lambda_handler(event, context):
print("\n\nAWS snapshot backups starting at %s" % datetime.datetime.now())
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
for instance in instances:
instance_name = filter(lambda tag: tag['Key'] == 'Name', instance.tags)[0]['Value']
for volume in ec2.volumes.filter(Filters=[{'Name': 'attachment.instance-id', 'Values': [instance.id]}]):
description = 'scheduled-%s-%s' % (instance_name,
datetime.datetime.now().strftime("%Y-%m-%d-%H:%M"))
if volume.create_snapshot(VolumeId=volume.volume_id, Description=description):
print("Snapshot created with description [%s]" % description)
for snapshot in volume.snapshots.all():
retention_days = int(os.environ['retention_days'])
if snapshot.description.startswith('scheduled-') and ( datetime.datetime.now().replace(tzinfo=None) - snapshot.start_time.replace(tzinfo=None) ) > datetime.timedelta(days=retention_days):
print("\t\tDeleting snapshot [%s - %s]" % ( snapshot.snapshot_id, snapshot.description ))
snapshot.delete()
print("\n\nAWS snapshot backups completed at %s" % datetime.datetime.now())
return True
请有人解释如何在此脚本创建的ebs快照中添加标签。
我的教育猜测是它应该在脚本的这一部分。因为那是创建描述的地方。那么我理论上可以添加一个名为tag = ec2.Tag的变量('resource_id','key','value')?
for volume in ec2.volumes.filter(Filters=[{'Name': 'attachment.instance-id', 'Values': [instance.id]}]):
description = 'scheduled-%s-%s' % (instance_name,
datetime.datetime.now().strftime("%Y-%m-%d-%H:%M"))
答案 0 :(得分:1)
您在执行volume.create_snapshot
替换
if volume.create_snapshot(VolumeId=volume.volume_id, Description=description):
print("Snapshot created with description [%s]" % description)
与
if volume.create_snapshot(
VolumeId=volume.volume_id,
Description=description,
TagSpecifications=[
{
'ResourceType': 'snapshot',
'Tags': [
{
'Key': 'Owner',
'Value': 'RaGe'
},
{
'Key': 'date',
'Value': datetime.datetime.now().strftime("%Y-%m-%d")
}
]
},
]
):
print("Snapshot created with description [%s]" % description)
这导致: