如何使用boto从正在运行的实例创建EC2映像?

时间:2011-03-10 07:26:39

标签: python amazon-ec2 boto

我正在尝试为我的EC2实例创建一个简单的python备份脚本。此脚本的目的是创建当前计算机的每日/每周快照(请参阅this question on ServerFault)。我正在使用boto python包用于EC2 API,并希望从给定实例创建EBS AMI(如ElasticFox的“创建图像”操作)

# This script will look up all your running EC2 images, find the current one, and back it up by creating an AMI 

# Configuration
accessKeyId = "..."
accessKeySecret = "..."
target = "..."

def resolveIp(target):
    import socket
    ip = repr(socket.gethostbyname_ex(target)[2][0])
    return ip

def find_target(target, connection) :
    ip = resolveIp(target)
    print "Finding instance for " + target + " (IP " + ip + ")"
    reservations = connection.get_all_instances();
    for reservation in reservations:
        instances = reservation.instances
        if len(instances) != 1:
            print "Skipping reservation " + reservation
            continue
        instance = instances[0]
        instanceIp = resolveIp(instance.dns_name)
        if instanceIp == ip:
            return instance

    raise Exception("Can't find instance with IP " + ip)

from boto.ec2.connection import EC2Connection

print "Connecting to EC2"
conn = EC2Connection(accessKeyId, accessKeySecret)
print "Connected to EC2"

instance = find_target(target, conn)
print "Backing up instance '{}'".format(instance)

# Now, I'd like to create a new image out of this instance
# Can you help?

(也报告为an issue on the boto project page,因为我没有找到邮件列表)

1 个答案:

答案 0 :(得分:9)

您需要EC2Connection对象的“create_image”方法。请参阅文档here。您也可以在boto-users Google网上论坛上提问。