首页 > 解决方案 > Boto3 python 脚本 AMI 备份 create_image 函数不接受 TagSpecifications

问题描述

我创建的脚本正在运行,它会创建使用某些标签的实例的 AMI 备份。(除了当我添加TagSpecifications部件时,它可以工作)我现在最大的问题是为 AMI 创建的快照根本没有任何标签名称。

我得到的错误是:

输入中的未知参数:“TagSpecifications”,必须是以下之一:BlockDeviceMappings、Description、DryRun、InstanceId、Name、NoReboot

它出现在文档中,但让我发疯:https ://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.create_image

知道它可能是什么吗?

import boto3
import datetime

today = datetime.date.today()

session = boto3.Session(region_name="us-east-2")
ec2 = session.resource('ec2')

instances = ec2.instances.filter(
    Filters=[{'Name': 'tag:Backup', 'Values': ['Yes']}])


for instance in instances:
    instance_name = ''
    for tag in instance.tags:
        if tag["Key"] == 'Name':
            instance_name = tag["Value"]
    print(instance.id, "{0}-{1}".format(instance_name, today.strftime("%Y-%m-%d")))
    instance.create_image(
        Name="{0}-{1}".format(instance_name, today.strftime("%Y-%m-%d")),
        InstanceId=instance.id,
        Description='Quarterly-Backup-AMI',
        NoReboot=True,
        TagSpecifications=[
            {
                'ResourceType': 'snapshot',
                'Tags': [
                    {
                        'Key': 'Name',
                        'Value': 'Testing123123'
                    },
                ]
            },
        ]
    )

标签: pythonamazon-ec2boto3amazon-ami

解决方案


create_image不带InstanceId参数,因为您instance已经是Instance对象。

同样对于 AMI,您需要image,而不是snapshot

    instance.create_image(
        Name="dddd",
        Description='Quarterly-Backup-AMI',
        NoReboot=True,
        TagSpecifications=[
            {
                'ResourceType': 'image',
                'Tags': [
                    {
                        'Key': 'Name',
                        'Value': 'Testing123123'
                    },
                ]
            },
        ]
    )

该命令有效。我在我的 EC2 实例上验证了它。


推荐阅读