python - 在 Boto3 python 脚本中添加 AWS 标签

标签 python amazon-web-services aws-lambda boto3

这里是 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)

reference

这导致:

enter image description here

关于python - 在 Boto3 python 脚本中添加 AWS 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50822985/

相关文章:

Python 打开 Microsoft SQL Server MDF 文件

python - 获取Python列表中连续性第一次中断的索引

amazon-web-services - AWS S3 预签名 URL 包含 X-Amz-Security-Token

amazon-web-services - 如何处理关系数据库中的AWS IOT流数据

amazon-web-services - 雅典娜查询结果在S3上的特定路径

amazon-web-services - AWS API Gateway 禁止连续请求

python - (Python/TFTP-Server)如何监听(尚未)现有的IP地址(RNDIS)?

python - (?ui) 在 Python 正则表达式中意味着什么?

amazon-web-services - 多个 Lambda 函数完成后调用 AWS Lambda 函数

amazon-web-services - VS 运行哪些命令来发布 .net core 无服务器应用程序?