Boto EC2:创建一个带有标记的实例

2024-04-25 03:40:31 发布

您现在位置:Python中文网/ 问答频道 /正文

在创建实例时,是否可以使用boto python API指定标记?我试图避免创建一个实例,获取它,然后添加标记。当我执行以下命令时,将实例预先配置为具有某些标记或指定标记会容易得多:

ec2server.create_instance(
        ec2_conn, ami_name, security_group, instance_type_name, key_pair_name, user_data
    )

Tags: 实例instancename标记命令apitypecreate
3条回答

You can tag instance or volume on creation

来自run_instances docs

You can tag instances and EBS volumes during launch, after launch, or both. For more information, see CreateTags and Tagging Your Amazon EC2 Resources.

Using TagsAWS doc包含一个表,其中包含支持标记和创建时支持标记的资源(从2017年5月1日起,实例和EBS卷都支持)

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

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)

在创建实例之前,无法创建标记。尽管这个函数被称为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.

使用boto 2.9.6,我可以在从run_实例得到响应后立即向实例添加标记。像这样的东西不用睡觉就可以工作:

reservation = my_connection.run_instances(...)
for instance in reservation.instances:
    instance.add_tag('Name', <whatever>)

成功添加标记后,我验证了实例仍处于挂起状态。将这个逻辑封装在一个类似于原始post所请求的函数中是很容易的。

相关问题 更多 >