Monitor and troubleshoot Java applications and services with Datadog: 

>> Try it free!

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
  .standard()
  .withCredentials(new AWSStaticCredentialsProvider(credentials))
  .withRegion(Regions.US_EAST_1)
  .build();

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()
  .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:

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:

AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest 
  = new AuthorizeSecurityGroupIngressRequest()
  .withGroupName("BaeldungSecurityGroup")
  .withIpPermissions(ipPermission);
ec2Client.authorizeSecurityGroupIngress(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()
  .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.

3.3. Creating the EC2 Instance

To create the EC2, we’ll use a 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.

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)
  .getReservation().getInstances().get(0).getInstanceId();

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()
  .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

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

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

ec2Client.unmonitorInstances(unmonitorInstancesRequest);

4.3. Describing an EC2 Instance

Finally, we can describe our EC2 instances:

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:

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

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.

Monitor and troubleshoot Java applications and services with Datadog: 

>> Try it free!

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of