使用AWS Boto3资源服务我得到了所有ec2实例的列表:
<Style.Triggers>
<EventTrigger RoutedEvent="ToggleButton.Loaded">
<SkipStoryboardToFill BeginStoryboardName="checkedSB" />
<SkipStoryboardToFill BeginStoryboardName="uncheckedSB" />
</EventTrigger>
<DataTrigger Binding="{Binding IsChecked, RelativeSource={RelativeSource Self}}" Value="true">
<DataTrigger.EnterActions>
<BeginStoryboard Name="checkedSB">
<Storyboard Storyboard.TargetProperty="Width">
<DoubleAnimation To="150"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<BeginStoryboard Name="uncheckedSB">
<Storyboard Storyboard.TargetProperty="Width">
<DoubleAnimation To="50"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
</Style.Triggers>
每当我使用我的`ec2_instance'变量做某事时 - 它接缝重新加载整个实例列表..
有没有办法只需拉一次列表然后再处理它(过滤器等)
我做的例子:
获取列表并在过滤某些值后将其显示为菜单:
在我的Aws()课程中:
ec2_instances = ec2.instances.all()
在我的菜单模块中:
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
这需要时间取决于我的互联网连接,但我看到,当我断开我的互联网 - 它无法过滤.. 我只有12个实例,所以过滤它们的循环不应该花费时间..
更新 我将Aws()类更改为模块,我正在使用这两个函数:
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
答案 0 :(得分:2)
对于仍然面临此问题的人
尝试使用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'])