這是應該做的伎倆:
# open connection to ec2
conn = get_ec2_conn()
# get a list of all instances
all_instances = conn.get_all_instances()
# get instances with filter of running + with tag `Name`
instances = conn.get_all_instances(filters={'tag-key': 'Name', 'instance-state-name': 'running'})
# make a list of filtered instances IDs `[i.id for i in instances]`
# Filter from all instances the instance that are not in the filtered list
instances_to_delete = [to_del for to_del in all_instances if to_del.id not in [i.id for i in instances]]
# run over your `instances_to_delete` list and terminate each one of them
for instance in instances_to_delete:
conn.stop_instances(instance.id)
而且在boto3:
# open connection to ec2
conn = get_ec2_conn()
# get a list of all instances
all_instances = [i for i in conn.instances.all()]
# get instances with filter of running + with tag `Name`
instances = [i for i in conn.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}, {'Name':'tag-key', 'Values':['Name']}])]
# make a list of filtered instances IDs `[i.id for i in instances]`
# Filter from all instances the instance that are not in the filtered list
instances_to_delete = [to_del for to_del in all_instances if to_del.id not in [i.id for i in instances]]
# run over your `instances_to_delete` list and terminate each one of them
for instance in instances_to_delete:
instance.stop()
我正在使用僅支持boto3的AWS Lambda,您會如何推薦將其寫入boto3和Python 2.7的上下文中? –
看看我的更新,這是一種哈克,但這是我與boto3的第一槍,但它的工作:) @TimHolm –
另外,我會嘗試閱讀亞馬遜的文檔http://boto3.readthedocs.io/en/latest/guide/migrationec2的.html#檢查乜情況下,是運行的 –