From 1f2057782a5f73e9ad63a7544c92167807f0c310 Mon Sep 17 00:00:00 2001 From: Stepan Stipl Date: Wed, 8 Apr 2015 17:31:54 +0100 Subject: [PATCH] Prefetch subnets info in one call - quite big performance boost in case of lots of resources --- lib/puppet/provider/ec2_instance/v2.rb | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/lib/puppet/provider/ec2_instance/v2.rb b/lib/puppet/provider/ec2_instance/v2.rb index 60908ca8..701a6607 100644 --- a/lib/puppet/provider/ec2_instance/v2.rb +++ b/lib/puppet/provider/ec2_instance/v2.rb @@ -11,12 +11,22 @@ def self.instances regions.collect do |region| begin instances = [] + subnets = Hash.new() + + subnets_response = ec2_client(region).describe_subnets() + subnets_response.data.subnets.each do |subnet| + name_tag = subnet.tags.detect { |tag| tag.key == 'Name' } + if name_tag then + subnets[subnet.subnet_id] = name_tag.value + end + end + ec2_client(region).describe_instances(filters: [ {name: 'instance-state-name', values: ['pending', 'running', 'stopping', 'stopped']} ]).each do |response| response.data.reservations.each do |reservation| reservation.instances.each do |instance| - hash = instance_to_hash(region, instance) + hash = instance_to_hash(region, instance, subnets) instances << new(hash) if has_name?(hash) end end @@ -40,7 +50,7 @@ def self.prefetch(resources) end end - def self.instance_to_hash(region, instance) + def self.instance_to_hash(region, instance, subnets) name_tag = instance.tags.detect { |tag| tag.key == 'Name' } monitoring = instance.monitoring.state == "enabled" ? true : false tags = {} @@ -49,10 +59,8 @@ def self.instance_to_hash(region, instance) end subnet_name = nil if instance.subnet_id - subnet_response = ec2_client(region).describe_subnets(subnet_ids: [instance.subnet_id]) - subnet_name_tag = subnet_response.data.subnets.first.tags.detect { |tag| tag.key == 'Name' } + subnet_name = subnets[instance.subnet_id] ? subnets[instance.subnet_id] : nil end - subnet_name = subnet_name_tag ? subnet_name_tag.value : nil devices = instance.block_device_mappings.collect do |mapping| {