簡體   English   中英

Boto EC2:創建帶有標簽的實例

[英]Boto EC2: Create an instance with tags

boto python API 有沒有辦法在創建實例時指定標簽? 我試圖避免必須創建一個實例,獲取它然后添加標簽。 當我執行以下命令時,讓實例預先配置為具有某些標簽或指定標簽會容易得多:

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

這個答案在撰寫時是准確的,但現在已經過時了。 AWS API 和庫(例如 boto3)現在可以采用“TagSpecification”參數,允許您在運行“create_instances”調用時指定標簽。


在創建實例之前無法創建標簽。 盡管該函數名為 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.

您可以在創建時標記實例或卷

來自run_instances 文檔

您可以在啟動期間、啟動后或同時標記實例和 EBS 卷。 有關更多信息,請參閱CreateTags標記您的 Amazon EC2 資源

使用標簽AWS doc 包含一個表格,其中包含支持標記和支持創建標記的資源(實例和 EBS 卷支持截至 2017 年 5 月 1 日)

這是在 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)

使用 boto 2.9.6,我可以在從 run_instances 獲得響應后立即向實例添加標簽。 這樣的事情無需睡眠即可工作:

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

成功添加標簽后,我驗證了該實例仍處於掛起狀態。 將此邏輯包裝在類似於原始帖子請求的函數中會很容易。

這種方法對我有用:

rsvn = image.run(
  ... standard options ...
)

sleep(1)

for instance in rsvn.instances:
   instance.add_tag('<tag name>', <tag value>)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM