如何仅显示boto3 instance.create_image()返回的AMI id

时间:2019-05-20 08:28:14

标签: amazon-web-services aws-sdk boto3 ec2-ami

下面是一个boto3代码,用于从给定的ec2实例创建一个ami。 如何修改输出以仅提取创建的AMI id的值?

import boto3

ec2 = boto3.resource('ec2')

instance = ec2.Instance('xxxxxxxxxxx')
image = instance.create_image(
                BlockDeviceMappings=[
                {
                    'DeviceName': '/dev/sda1',
                    'Ebs': {
                        'DeleteOnTermination': True,
                    }
                }
            ],


        Name='xxxxxxxxxxxxxxxxxxxx'
)
image.wait_until_exists('self',Filters=[{'Name':'state','Values':['available']}])
print("Image Created ",image)

以上代码的输出为:

Image Created  ec2.Image(id='ami-0c59fddbexxxxxxxxxx')

1 个答案:

答案 0 :(得分:2)

您可以使用id单独获得ami id:

#Boto3 code to create an ami from ec2 instance
import boto3

ec2 = boto3.resource('ec2')
instance = ec2.Instance('yourec2id')
image = instance.create_image(
                BlockDeviceMappings=[
                {
                    'DeviceName': '/dev/xvda',
                    'Ebs': {
                        'DeleteOnTermination': True,
                    }
                }
            ],
        Name='yourec2id'
)
image.wait_until_exists('self',Filters=[{'Name':'state','Values':['available']}])
print("Image Created ",image.id)

输出:

Image Created  ami-xxxx