繁体   English   中英

始终更新的Python AWS boto3实例列表

[英]Python AWS boto3 list of instances always updated

使用AWS Boto3资源服务,我得到了所有我的ec2实例的列表:

ec2_instances = ec2.instances.all()

每次我使用我的`ec2_instance'变量进行操作时-都会重新加载整个实例列表。

有没有一种方法可以只提取列表一次,然后对其进行处理(过滤器等)

我做的事的例子:

在过滤一些值后获取列表并将其显示为菜单:

在我的Aws()类中:

    def load_ec2_instance(self, region):
    """
    Load the EC2 instances a region
    :param region:
    :rtype: list
    :return: a list of the instances in a region or None if there are no instances
    """
    ec2 = self._get_resource("ec2", region)
    ec2_instances = ec2.instances.all()
    counter = collections.Counter(ec2_instances);
    ec2_size = sum(counter.itervalues());
    if ec2_size == 0:
        return None
    return ec2_instances

在我的菜单模块中:

       instances = Aws.get_instance().load_ec2_instance(chosen_region)
       show_environments_menu(instances)

        def show_environments_menu(instances):
            subprocess.call("clear")
            print "Please choose the environment your instance is located in:"
            environments = Aws.get_instance().get_environments_from_instances(instances)
            for i, environment in enumerate(environments):
                print "%d. %s" % (i + 1, environment)

        def get_environments_from_instances(self, instances):
        """
        Get all the environments available from instances lists
        :param list instances: the list of instance
        :rtype: list
        :return: a list of the environments
        """
        environments = []
        for instance in instances:
            tags = instance.tags
            for tag in tags:
                key = tag.get("Key")
                if key == "Environment":
                    environment = tag.get("Value").strip()
                    if environment not in environments:
                        environments.append(environment)
        return environments

这需要时间,具体取决于我的Internet连接,但是我看到断开互联网连接时无法过滤。我只有12个实例,因此用于过滤它们的循环完全不需要时间。

更新:我将Aws()类更改为模块,并且正在使用以下两个函数:

def load_ec2_instances(region):
    """
    Load the EC2 instances a region
    :param region:
    :rtype: list
    :return: a list of the instances in a region or None if there are no instances
    """
    ec2 = _get_resource("ec2", region)
    ec2_instances = ec2.instances.all()
    counter = collections.Counter(ec2_instances);
    ec2_size = sum(counter.itervalues());
    if ec2_size == 0:
        return None
    return ec2_instances


def get_environments_from_instances(instances):
    """
    Get all the environments available from instances lists
    :param list instances: the list of instance
    :rtype: list
    :return: a list of the environments
    """
    environments = []
    for instance in instances:
        tags = instance.tags
        for tag in tags:
            key = tag.get("Key")
            if key == "Environment":
                environment = tag.get("Value").strip()
                if environment not in environments:
                    environments.append(environment)
    return environments

对于仍然面临此问题的任何人

尝试使用ec2客户端而不是资源。 boto3中的资源较高级别,可以为您做更多的工作,而客户端只是向您提供您所要求的。

当您使用客户端时,会得到python字典对象,您可以在内存中对其内容进行操作。 请参见下面的示例。 您可以编辑它以使用列表理解和方法等。

有关描述ec2实例的ec2客户端方法的文档,请参阅EC2.Client.describe_instances

import boto3
ec2 = boto3.client("ec2", region_name = 'us-west-2')
reservations = ec2.describe_instances()['Reservations']
instances = []
for reservation in reservations:
     for instance in reservation['Instances']:
         instances.append(instance)

environments = []
for instance in instances:
    for tag in instance['Tags']:
        if tag['Key'] == 'Environment':
            environments.append(tag['Value'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM