我已设法启动,停止并检查以前从JAVA API创建的EC2实例的状态.但是,我很难获得此实例的公共DNS地址.由于我使用StartInstancesRequest启动实例并使用StartInstancesResponse获取响应,因此无法检索实际的Instance对象.我的起始代码如下,它有效:
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; }
除了通过JSch连接到这个实例的任何帮助,将不胜感激.
非常感谢!
解决方法
这是一种可以解决问题的方法.在调用之前,最好检查实例是否处于运行状态.
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; }