AWS Boto实例标记

时间:2015-04-23 06:51:30

标签: python amazon-web-services boto

我正在努力为我新创建的EC2实例添加Name标签,

AWS是否有办法识别最后创建的实例?

reservations = ec2.get_all_instances()
instance = reservations[0].instances[0]
create_tags([instance.id], {"Name": tag})

这不是最近部署的实例的标记设置。

1 个答案:

答案 0 :(得分:1)

要命名新创建的实例,您可以在创建vm后立即添加名称标签:

import boto.ec2
conn = boto.ec2.connect_to_region("eu-west-1",aws_access_key_id='key',aws_secret_access_key='sectret')
reservations = conn.run_instances("ami-a10897d6", min_count=1, max_count=1, key_name="key", security_group_ids=["sg-123"], instance_type="t2.micro", subnet_id="subnet-123")
instance = reservations.instances[0]
conn.create_tags([instance.id], {"Name":"foo"})

或者,如果您准确地知道开始时间,则可以将filters参数与*一起用作通配符。一个更动态的例子可能是:

from datetime import datetime
now = datetime.utcnow()
filter_now = "%s*" % (now.strftime("%Y-%m-%dT%H:%M"))
reservations = conn.get_all_instances(filters={"launch_time":filter_now})