简体   繁体   中英

Adding AWS Tag in Boto3 python script

Python noob here. I recently came across a blog site that taught a lesson on how to automate EBS snapshots using lambda & python. The script runs perfect and technically does everything I want except I can't figure out how to add AWS tags in boto3 lib.

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

Please can someone explain how I can add tags to the ebs snapshots being created by this script.

my educational guess is that it should be in this portion of the script. because thats where the description is being created. so could i in theory just add a variable named 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")) 

You add tags while doing volume.create_snapshot

replace

if volume.create_snapshot(VolumeId=volume.volume_id, Description=description):
    print("Snapshot created with description [%s]" % description)

with

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

This results in:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM