python AWS EC2:获取所有未标记的EC2实例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python AWS EC2:获取所有未标记的EC2实例相关的知识,希望对你有一定的参考价值。

import boto3

# setting region, profile from credential provider
session = boto3.Session(
        region_name='eu-west-1',
        profile_name='myprofile'
        )

# declare ec2
ec2 = session.client('ec2')

# get a dictionary of all the instances
response = ec2.describe_instances()

# get the number of objects
obj_number = len(response['Reservations'])

# print the instance-id's with no tags
for objects in xrange(obj_number):
    try:
        z = response['Reservations'][objects]['Instances'][0]['Tags'][0]['Key']
    except KeyError as e:
        untagged_instanceid = response['Reservations'][objects]['Instances'][0]['InstanceId']
        untagged_state = response['Reservations'][objects]['Instances'][0]['State']['Name']
        untagged_keyname = response['Reservations'][objects]['Instances'][0]['KeyName']
        print("InstanceID: {0}, RunningState: {1}, KeyName: {2}".format(untagged_instanceid, untagged_state, untagged_keyname))

# $ python get_untagged_ec2.py
# InstanceID: i-03b7608f2a9784cef, RunningState: running, KeyName: mykey
# InstanceID: i-01383968e138c20a4, RunningState: running, KeyName: mykey
# InstanceID: i-07ad00e454439f0c0, RunningState: running, KeyName: mykey

以上是关于python AWS EC2:获取所有未标记的EC2实例的主要内容,如果未能解决你的问题,请参考以下文章

python 使用Boto自动标记的AWS EC2竞价请求

如何在Python AWS boto API中获取EC2实例ID的容器实例列表

python AWS:从EC2实例元数据中获取临时凭证,并使用它来访问AWS资源

我们如何使用 python boto3 获取挂载到 EC2 实例的所有文件系统(EFS)的列表?

sh AWS CLI:使用标记值描述EC2实例

使用boto3 Python SDK返回AWS EC2可用性区域属性