Course – LS – All

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:


1. Overview

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.

2. Prerequisites

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.

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

AmazonEC2 ec2Client = AmazonEC2ClientBuilder
  .withCredentials(new AWSStaticCredentialsProvider(credentials))

3. Creating an EC2 Instance

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

3.1. Creating a Security Group

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

Let’s create a security group:

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

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:

IpRange ipRange = new IpRange().withCidrIp("");
IpPermission ipPermission = new IpPermission()
  .withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange }))

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

AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest 
  = new AuthorizeSecurityGroupIngressRequest()

3.2. Creating a Key Pair

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

CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest);

Let’s get the private key:


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.

3.3. Creating the EC2 Instance

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

RunInstancesRequest runInstancesRequest = new RunInstancesRequest()

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

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.

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.

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

String yourInstanceId = ec2Client.runInstances(runInstancesRequest)

4. Managing an EC2 Instance

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

4.1. Starting, Stopping and Rebooting an EC2 Instance

Starting, stopping and rebooting an instance is relatively straightforward.

Starting an instance:

StartInstancesRequest startInstancesRequest = new StartInstancesRequest()


Stopping an instance:

StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()

Rebooting an instance:

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

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


4.2. Monitoring an EC2 Instance

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

MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest()
UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest()


4.3. Describing an EC2 Instance

Finally, we can describe our EC2 instances:

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

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


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


Now, we can describe our instance:

// ...

5. Conclusion

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

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

Course – LS – All

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!