这里是 Python 菜鸟。我最近发现了一个博客网站,该网站教授有关如何使用 lambda 和 python 自动化 EBS 快照的类(class)。该脚本运行完美,技术上可以做我想做的一切,除了我不知道如何在 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"))
最佳答案
您在执行 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)
这导致:
关于python - 在 Boto3 python 脚本中添加 AWS 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50822985/