为什么描述亚马逊EC2实例可能没有结果?

3

我正在尝试检索我的AWS帐户中运行的所有实例(例如实例ID等)。我使用以下代码。但我无法打印出实例ID。当我调试时,我只得到空值。但是我在AWS上有三个正在运行的实例。有人能指出我在这里做错了什么吗?

 DescribeInstancesResult result = ec2.describeInstances();

 List<Reservation> reservations = result.getReservations();

 for (Reservation reservation : reservations) {
      List<Instance> instances = reservation.getInstances();

      for (Instance instance : instances) {
           System.out.println(instance.getInstanceId());
      }
 } 
1个回答

2
这种问题最常见的原因是在初始化客户端时缺少区域规范,详见创建 Amazon EC2 客户端中的创建和初始化 Amazon EC2 客户端一节。
具体来说,在第二步中仅创建了一个EC2客户端而未显式指定区域。

2) Use the AWSCredentials object to create a new AmazonEC2Client instance, as follows:

amazonEC2Client = new AmazonEC2Client(credentials);
这将产生一个客户端与us-east-1通信 - 令人惊讶的是,AWS SDKsAWS管理控制台使用不同的默认值,即使在步骤3中概述了如何指定不同的终端点。

3) By default, the service endpoint is ec2.us-east-1.amazonaws.com. To specify a different endpoint, use the setEndpoint method. For example:

amazonEC2Client.setEndpoint("ec2.us-west-2.amazonaws.com");

The AWS SDK for Java uses US East (N. Virginia) as the default region if you do not specify a region in your code. However, the AWS Management Console uses US West (Oregon) as its default. Therefore, when using the AWS Management Console in conjunction with your development, be sure to specify the same region in both your code and the console. [emphasis mine]

默认设置的不同很容易出错,AWS Management Console 中各自的默认设置实际上随时间而改变 - 如同软件开发中经常发生的一样,我建议在代码中始终明确指定以避免这种微妙的错误源。


一点不错!像魔法般地运作。 - Slartibartfast
1
谢谢!我刚刚浪费了很多时间,纳闷为什么没有结果,结果发现我忘记设置区域了。 - Chris B

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接