当前位置:  开发笔记 > 编程语言 > 正文

Boto EC2:使用标签创建实例

如何解决《BotoEC2:使用标签创建实例》经验,为你挑选了2个好方法。



1> 小智..:

在创建实例之前无法创建标记.即使该函数被称为create_instance,它实际上正在做的是保留和实例.然后可以启动或不启动该实例.(通常是,但有时......)

因此,在启动标记之前,您无法添加标记.并且没有办法判断它是否在没有轮询的情况下启动.像这样:

reservation = conn.run_instances( ... )

# NOTE: this isn't ideal, and assumes you're reserving one instance. Use a for loop, ideally.
instance = reservation.instances[0]

# Check up on its status every so often
status = instance.update()
while status == 'pending':
    time.sleep(10)
    status = instance.update()

if status == 'running':
    instance.add_tag("Name","{{INSERT NAME}}")
else:
    print('Instance status: ' + status)
    return None

# Now that the status is running, it's not yet launched. The only way to tell if it's fully up is to try to SSH in.
if status == "running":
    retry = True
    while retry:
        try:
            # SSH into the box here. I personally use fabric
            retry = False
        except:
            time.sleep(10)

# If we've reached this point, the instance is up and running, and we can SSH and do as we will with it. Or, there never was an instance to begin with.


此解决方案的补充可能是使用[conn.create_tags(instance_id_list,tag_dict)](http://boto.readthedocs.org/en/latest/ref/ec2.html#boto.ec2.connection.EC2Connection.create_tags)它允许您使用一个命令将多个标签添加到多个(已创建的!)实例.
轮询循环不是必需的; 您可以在实例仍处于"pending"状态时设置标记.

2> Dmitry Tokar..:

您可以在创建时标记实例或卷

从run_instances文档:

您可以在启动期间,启动后或两者中标记实例和EBS卷.有关更多信息,请参阅CreateTags和标记您的Amazon EC2资源.

使用标签 AWS doc包含一个表,其中包含支持标记和支持标记创建的资源(截至2017年5月1日的实例和EBS卷支持)

下面是在Python中创建时标记实例的代码片段(此页面列出了其他SDK引用):

from pkg_resources import parse_version
import boto3
assert parse_version(boto3.__version__) >= parse_version('1.4.4'), \
    "Older version of boto3 installed {} which doesn't support instance tagging on creation. Update with command 'pip install -U boto3>=1.4.4'".format(boto3.__version__)
import botocore
assert parse_version(botocore.__version__) >= parse_version('1.5.63'), \
   "Older version of botocore installed {} which doesn't support instance tagging on creation. Update with command 'pip install -U botocore>=1.5.63'".format(botocore.__version__)
ec2 = boto3.resource('ec2')
tag_purpose_test = {"Key": "Purpose", "Value": "Test"}
instance = ec2.create_instances(
    ImageId=EC2_IMAGE_ID,
    MinCount=1,
    MaxCount=1,
    InstanceType=EC2_INSTANCE_TYPE,
    KeyName=EC2_KEY_NAME,
    SecurityGroupIds=[EC2_DEFAULT_SEC_GROUP],
    SubnetId=EC2_SUBNET_ID,
    TagSpecifications=[{'ResourceType': 'instance',
                        'Tags': [tag_purpose_test]}])[0]

我用了

Python 2.7.13
boto3 (1.4.4)
botocore (1.5.63)

推荐阅读
coco2冰冰
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有