0
votes

There is an existing subnet say subnet-11223344. In my code I want to know the VPC it belongs to.

I am referring 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); 

This returns null.

1
How do I create a Subnet (with existing Id ) for that?abc123
You need to create "DescribeSubnetRequest" object to which you set subnetID. Here is an example programcreek.com/java-api-examples/…kosa
Your code creates an empty Subnet object locally in memory, then modifies the subnet ID of that local object. There's no magic going on under the covers that calls out to the EC2 service to retrieve the actual subnet whose ID you just set. All of the subnet's other properties, including vpcid, will be null (or zero for non-object types) because the Subnet() constructor doesn't set any property values at all.jarmod

1 Answers

0
votes

Here's an example of a general purpose solution provided by 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(); 
}