Module: Awspec::Helper::Finder::Subnet

Included in:
Awspec::Helper::Finder
Defined in:
lib/awspec/helper/finder/subnet.rb

Defined Under Namespace

Classes: SubnetCache

Instance Method Summary collapse

Instance Method Details

#find_subnet(subnet_id) ⇒ Object

Try to locate a Aws::EC2::Types::Subnet with a given subnet ID.

A subnet ID might be multiple things, like the Aws::EC2::Types::Subnet.subnet_id, or a IPv4 CIDR or the value for the Name tag associated with the subnet.

Returns a instance of Aws::EC2::Types::Subnet or nil.



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/awspec/helper/finder/subnet.rb', line 97

def find_subnet(subnet_id)
  cache = SubnetCache.instance

  if cache.empty?
    res = ec2_client.describe_subnets

    res.subnets.each do |sub|
      cache.add_by_cidr(sub.cidr_block, sub.subnet_id)
      cache.add_subnet(sub)
      next if sub.tags.empty?

      sub.tags.each do |tag|
        if tag[:key].eql?('Name')
          cache.add_by_tag(tag[:value], sub.subnet_id)
          break
        end
      end
    end
  end

  id_key = subnet_id.to_sym
  return cache.subnet_by_id(id_key) if subnet_id.start_with?('subnet-') && cache.has_subnet?(id_key)
  return cache.subnet_by_cidr(id_key) if cache.is_cidr?(subnet_id) && cache.has_cidr?(id_key)

  cache.subnet_by_tag(id_key)
end