Reputation: 43
I made a Java program which allows to create instances Programatically.
I need to parse the return object to print the public IP address of the Instance.
However when I output the result of the describeInstances()
function of Amazon's EC2 client, the output is a maze of lists and hash maps and I don't know how to parse it.
Can anybody tell me a more simpler approach to accomplish this?
I tried to convert the Ec2.describeInstances().getReservations()
result to a string and then manipulate the string to output the Public IP address.
Is there any simpler way to accomplish this?
Code:
DescribeAddressesRequest add =new DescribeAddressesRequest();
String Desc= client.describeInstances().getReservations().get(1).toString();
Upvotes: 0
Views: 1027
Reputation: 191681
You need an Instance
class
getPublicIpAddress()
The public IPv4 address assigned to the instance, if applicable
I don't know the API, but from a Reservation, you get to an Instance.
getInstances()
One or more instances
for (Reservation r : client.describeInstances().getReservations()) {
for (Instance i : r.getInstances()) {
String ipv4 = i.getPublicIpAddress();
}
}
Upvotes: 1
Reputation: 200476
The SDK doesn't return HashMaps it returns actual Java classes. I'm not sure how you are getting HashMaps out of it. Converting the returned object to a String and manipulating that is definitely not the recommended approach.
If you look at the API docs you will see that describeInstances()
returns a DescribeInstancesResult which contains a list of Reservation objects, which each contain a list of Instance objects. The Instance object has a getPublicIpAddress()
method. So you could do something like the following:
DescribeInstancesRequest request = new DescribeInstancesRequest();
String ipAddress = client.describeInstances(request) // You pass the request here
.getReservations().get(0) // Get the first reservation
.getInstances().get(0) // Get the first instance in the reservation
.getPublicIpAddress(); // Get the public IP address of the instance
I assume you're adding some criteria, like the reservation ID, to the DescribeInstancesRequest
object so that you can expect only one instance to be in the response.
Note that the public IP address might not be assigned immediately. You may have to do this in a loop, checking if the IP address has been assigned yet.
Upvotes: 1