如何使用aws java SDK从子网ID获取VPC ID?

时间:2017-06-29 16:11:55

标签: java amazon-web-services amazon-ec2 aws-sdk

现有子网称为subnet-11223344。在我的代码中,我想知道它所属的VPC。

我指的是java SDK http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/ec2/model/Subnet.html

// I am not sure if this actually refres to a subnet that I want
Subnet subnet = new Subnet().withSubnetId("subnet-11223344");
String vpcId = subnet.getVpcId();
System.out.println("VPC id"+vpcId); 

返回null。

1 个答案:

答案 0 :(得分:0)

以下是ProgramCreek提供的通用解决方案示例:

public List<Subnet> getSubnets(List<String> subnetIds, AmazonEC2 ec2Client) { 
    DescribeSubnetsRequest request = new DescribeSubnetsRequest(); 

    if (subnetIds != null && !subnetIds.isEmpty()) { 
        request = request.withSubnetIds(subnetIds); 
    } 
    DescribeSubnetsResult result = ec2Client.describeSubnets(request); 

    return result.getSubnets(); 
}