Managing EC2 Instances in Java – 在Java中管理EC2实例

最后修改: 2018年 3月 10日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this article, we’ll learn to control EC2 resources using the Java SDK. If you’re new to EC2 (Elastic Cloud Compute) – this is a platform which provides compute capacity in Amazon’s cloud.

在这篇文章中,我们将学习使用Java SDK控制EC2资源。如果你是第一次接触EC2(Elastic Cloud Compute) – 这是一个在Amazon的云中提供计算能力的平台。

2. Prerequisites

2.先决条件

The Maven dependencies, AWS account settings and client connection needed to use the Amazon AWS SDK for EC2 are the same as in this article here.

使用Amazon AWS SDK for EC2所需的Maven依赖项、AWS账户设置和客户端连接与本文中的相同。

Assuming we’ve created an instance of AWSCredentials, as described in the previous article, we can go ahead and create our EC2 client:

假设我们已经创建了一个AWSCredentials的实例,如前文所述,我们可以继续创建我们的EC2客户端。

AmazonEC2 ec2Client = AmazonEC2ClientBuilder
  .standard()
  .withCredentials(new AWSStaticCredentialsProvider(credentials))
  .withRegion(Regions.US_EAST_1)
  .build();

3. Creating an EC2 Instance

3.创建一个EC2实例

Using the SDK, we can quickly set up what we need to start our first EC2 instance.

使用SDK,我们可以快速设置我们需要的东西,以启动我们的第一个EC2实例。

3.1. Creating a Security Group

3.1.创建一个安全组

Security groups control the network traffic to our EC2 instances. We’re able to use one security group for several EC2 instances.

安全组控制我们的EC2实例的网络流量。我们能够为几个EC2实例使用一个安全组。

Let’s create a security group:

让我们创建一个安全组。

CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest()
  .withGroupName("BaeldungSecurityGroup")
  .withDescription("Baeldung Security Group");
CreateSecurityGroupResult createSecurityGroupResult = ec2Client.createSecurityGroup(
  createSecurityGroupRequest);

Since security groups don’t allow any network traffic by default, we’ll have to configure our security group to allow traffic.

由于安全组默认不允许任何网络流量,我们必须配置我们的安全组以允许流量。

Let’s allow HTTP traffic coming from any IP address:

让我们允许来自任何IP地址的HTTP流量。

IpRange ipRange = new IpRange().withCidrIp("0.0.0.0/0");
IpPermission ipPermission = new IpPermission()
  .withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange }))
  .withIpProtocol("tcp")
  .withFromPort(80)
  .withToPort(80);

Finally, we must attach the ipRange instance to an AuthorizeSecurityGroupIngressRequest and make the request using our EC2 client:

最后,我们必须ipRange实例附加到AuthorizeSecurityGroupIngressRequest并使用我们的EC2客户端提出请求。

AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest 
  = new AuthorizeSecurityGroupIngressRequest()
  .withGroupName("BaeldungSecurityGroup")
  .withIpPermissions(ipPermission);
ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);

3.2. Creating a Key Pair

3.2.创建一个密钥对

When launching an EC2 instance, we need to specify a key pair. We can create a key pair using the SDK:

当启动一个EC2实例时,我们需要指定一个密钥对。 我们可以使用SDK创建一个密钥对:

CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
  .withKeyName("baeldung-key-pair");
CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest);

Let’s get the private key:

让我们得到私钥。

createKeyPairResult.getKeyPair().getKeyMaterial();

We’ve got to make sure to keep this key somewhere secure and safe. If we lose it, we won’t be able to it back (Amazon doesn’t keep it). It’s the only way we can connect to our EC2 instance.

我们必须确保将这把钥匙放在安全的地方。如果我们丢失了它,我们将无法取回它(亚马逊不保留它)。这是我们连接到EC2实例的唯一方法。

3.3. Creating the EC2 Instance

3.3.创建EC2实例

To create the EC2, we’ll use a RunInstancesRequest:

为了创建EC2,我们将使用RunInstancesRequest:

RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
  .withImageId("ami-97785bed")
  .withInstanceType("t2.micro") 
  .withKeyName("baeldung-key-pair") 
  .withMinCount(1)
  .withMaxCount(1)
  .withSecurityGroups("BaeldungSecurityGroup");

Image Id is the AMI image that this instance will use.

图像标识是该实例将使用的AMI图像

An instance type defines the specifications of the instance.

一个实例类型定义了实例的规格。

The key name is optional; if it’s not specified, then we can’t connect to our instance. This is fine if we’re confident we’ve set up our instance correctly, and won’t need to connect.

密钥名称是可选的;如果没有指定,那么我们就不能连接到我们的实例。如果我们确信我们已经正确地设置了我们的实例,并且不需要连接,这就可以了。

Min and max count give bounds as to how many instances will be created. This depends on the availability zone: if AWS cannot create at least the minimum number of instances in the zone, it won’t create any.

最小和最大计数给出了将创建多少个实例的界限。这取决于可用性区域:如果AWS不能在该区域创建至少最小数量的实例,它将不会创建任何实例。

Conversely, if AWS can’t create the maximum number of instances, it will try to create fewer, provided that this number is higher than the minimum number of instances we’ve specified.

相反,如果AWS不能创建最大数量的实例,它将尝试创建更少的实例,只要这个数量高于我们指定的最小实例数量。

Now we can execute the request using the runInstances() method and retrieve the id of the instance created:

现在我们可以使用runInstances()方法执行请求,并检索所创建的实例的id。

String yourInstanceId = ec2Client.runInstances(runInstancesRequest)
  .getReservation().getInstances().get(0).getInstanceId();

4. Managing an EC2 Instance

4.管理一个EC2实例

Using the SDK, we can start, stop, reboot, describe and configure monitoring for our EC2 instances.

使用SDK,我们可以为我们的EC2实例启动、停止、重启、描述和配置监控

4.1. Starting, Stopping and Rebooting an EC2 Instance

4.1.启动、停止和重新启动EC2实例

Starting, stopping and rebooting an instance is relatively straightforward.

启动、停止和重启一个实例是相对直接的。

Starting an instance:

启动一个实例。

StartInstancesRequest startInstancesRequest = new StartInstancesRequest()
  .withInstanceIds(yourInstanceId);

ec2Client.startInstances(request);

Stopping an instance:

停止一个实例:

StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()
  .withInstanceIds(yourInstanceId);
        
ec2Client.stopInstances(request);

Rebooting an instance:

重新启动一个实例。

RebootInstancesRequest request = new RebootInstancesRequest()
  .withInstanceIds(yourInstanceId);
        
RebootInstancesResult rebootInstancesRequest = ec2Client.rebootInstances(request);

From each of these requests, it’s possible to interrogate the previous state of the instance:

从这些请求中,我们可以询问实例的先前状态:

ec2Client.stopInstances(stopInstancesRequest)
  .getStoppingInstances()
  .get(0)
  .getPreviousState()
  .getName()

4.2. Monitoring an EC2 Instance

4.2.监控EC2实例

Let’s see how to start and stop monitoring our EC2 instances:

让我们看看如何启动和停止监控我们的EC2实例。

MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest()
  .withInstanceIds(yourInstanceId);
        
ec2Client.monitorInstances(monitorInstancesRequest);
         
UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest()
  .withInstanceIds(yourInstanceId);

ec2Client.unmonitorInstances(unmonitorInstancesRequest);

4.3. Describing an EC2 Instance

4.3.描述一个EC2实例

Finally, we can describe our EC2 instances:

最后,我们可以描述我们的EC2实例:

DescribeInstancesRequest describeInstancesRequest
 = new DescribeInstancesRequest();
DescribeInstancesResult response = ec2Client
  .describeInstances(describeInstancesRequest);

EC2 instances are grouped into reservations. Reservations are the StartInstancesRequest calls which were used to create one or more EC2 instances:

EC2实例被分组为reservations。保留是用于创建一个或多个EC2实例的StartInstancesRequest调用。

response.getReservations()

From here we can get the actual instances. Let’s get the first instance in the first reservation:

从这里我们可以得到实际的实例。让我们在第一个预订中获得第一个实例。

response.getReservations().get(0).getInstances().get(0)

Now, we can describe our instance:

现在,我们可以描述我们的实例。

// ...
.getImageId()
.getSubnetId()
.getInstanceId()
.getImageId()
.getInstanceType()
.getState().getName()
.getMonitoring().getState()
.getKernelId()
.getKeyName()

5. Conclusion

5.结论

In this quick tutorial, we showed how to manage Amazon EC2 instances using the Java SDK.

在这个快速教程中,我们展示了如何使用Java SDK管理Amazon EC2实例。

As usual, code snippets can be found over on GitHub.

像往常一样,代码片段可以在GitHub上找到over