如何确定 AWS VPC 子网是否为"public subnet"?



我想知道一个给定的AWS VPC子网是否是"公共子网",即它是否可以直接访问互联网。据我所知,为此我需要检查与该子网关联的路由表是否与互联网网关关联,即它具有"destination_cidr_block"="0.0.0.0/0""gateway_id"="igw-blahblah"的条目。使用Ruby AWS SDK,我这样做:

def is_public_subnet(subnet_id)
    client = AWS::EC2::Client.new
    rt = client.describe_route_tables(:filters => [:name => "association.subnet-id", :values => [subnet_id]])
    if rt[:route_table_set].empty?
        # no route table associated with it. Must be using main route table.
        rt = client.describe_route_tables(:filters => [:name => "association.main", :values => ["true"]])
    end
    rt[:route_table_set][0][:route_set].each do |route|
        if route[:destination_cidr_block] == "0.0.0.0/0"
            if route[:gateway_id].start_with?("igw-")
                return true
            end
         end
    end
    return false
end

我想问一下,在方法和ruby sdk代码方面,是否有更好的方法来做到这一点。

我不能说ruby代码,但这种方法是有效的:如果子网路由到互联网网关,则子网是公共的;如果子网连接到弹性IP,则子网的实例将可访问。

最新更新