[英]Get Public DNS of Amazon EC2 Instance from JAVA API
I have managed to start, stop and check the status of a previously created EC2 instance from JAVA API. 我已设法启动,停止并检查以前从JAVA API创建的EC2实例的状态。 However, i'm having difficulty on getting the public dns address of this instance.
但是,我很难获得此实例的公共DNS地址。 Since I start the instance with StartInstancesRequest and get the response with StartInstancesResponse, i couldn't be able to retrieve the actual Instance object.
由于我使用StartInstancesRequest启动实例并使用StartInstancesResponse获取响应,因此无法检索实际的Instance对象。 My starting code is given below, it works:
我的起始代码如下,它有效:
BasicAWSCredentials oAWSCredentials = new BasicAWSCredentials(sAccessKey, sSecretKey);
AmazonEC2 ec2 = new AmazonEC2Client(oAWSCredentials);
ec2.setEndpoint("https://eu-west-1.ec2.amazonaws.com");
List<String> instanceIDs = new ArrayList<String>();
instanceIDs.add("i-XXXXXXX");
StartInstancesRequest startInstancesRequest = new StartInstancesRequest(instanceIDs);
try {
StartInstancesResult response = ec2.startInstances(startInstancesRequest);
System.out.println("Sent! "+response.toString());
}catch (AmazonServiceException ex){
System.out.println(ex.toString());
return false;
}catch(AmazonClientException ex){
System.out.println(ex.toString());
return false;
}
Besides any help through connecting to this instance via JSch will be appreciated. 除了通过JSch连接到这个实例的任何帮助,将不胜感激。
Thanks a lot! 非常感谢!
Here's a method that would do the trick. 这是一种可以解决问题的方法。 It would be best to check that the instance is in the running state before calling this.
在调用之前,最好检查实例是否处于运行状态。
String getInstancePublicDnsName(String instanceId) {
DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
List<Reservation> reservations = describeInstancesRequest.getReservations();
Set<Instance> allInstances = new HashSet<Instance>();
for (Reservation reservation : reservations) {
for (Instance instance : reservation.getInstances()) {
if (instance.getInstanceId().equals(instanceId))
return instance.getPublicDnsName();
}
}
return null;
}
You can now use a filter when using describeInstances
, so you don't pull info for all your instances. 现在,您可以在使用
describeInstances
时使用过滤器,因此您不会为所有实例提取信息。
private String GetDNS(String aInstanceId)
{
DescribeInstancesRequest request = new DescribeInstancesRequest();
request.withInstanceIds(aInstanceId);
DescribeInstancesResult result = amazonEC2.describeInstances(request);
for (Reservation reservations : result.getReservations())
{
for (Instance instance : reservations.getInstances())
{
if (instance.getInstanceId().equals(aInstanceId))
{
return instance.getPublicDnsName();
}
}
}
return null;
}
Using aws-java-sdk-1.9.35.jar
. 使用
aws-java-sdk-1.9.35.jar
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.