Java and EC2: the AWS SDK in a few words

Welcome back you guys for this tutorial, and I’m super excited to present you the AWS Java SDK for EC2.

Java is a statically typed language and allows us to take control over insidious bugs that otherwise would be evident only at runtime: leaving you guys no other choice than working for long hours on a friday night, if something goes wrong in that particular day. And if it can… it will!

The Java programming language

This tutorial is based on Intellij Idea, a super smart IDE that contains a lot of features and useful stuff that can make life easier for all of you, even if you are an experienced one.

But let’s not joke anymore, we can begin by creating our dependency file, ‘pom.xml‘ which wil import our SDK. I won’t go into the details of Intellij in that it’s just a question of finding the right place to click, if you have the right details from this tutorial.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cloud.benedict</groupId>
    <artifactId>aws-ec2-java-sdk-tut</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-ec2</artifactId>
            <version>1.11.563</version>
        </dependency>
    </dependencies>

</project>

And here are the details, when you create a new Maven project, you will be asked to put a group id, an artifact id and a version: you will find them above. Then simply edit your ‘pom.xml‘ and add the build section and the dependencies section.

The first thing to do is to create a class that will retrive our credentials and build an EC2 Java client in ‘GetEc2Client.java‘, like so:

import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;


public class GetEc2Client {


    private AWSCredentials credentials;


    public GetEc2Client() {

        try {
            this.credentials = new ProfileCredentialsProvider().getCredentials();
        } catch (Exception e) {
            throw new AmazonClientException(
                    "Cannot load the credentials, please configure your AWS CLI.", e);
        }

    }


    public AmazonEC2 getClient() {

        return AmazonEC2ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(this.credentials))
                .withRegion("us-west-2")
                .build();

    }

}

The next thing is to create a security group which will act as a firewall and filter your instances’ connections, in this case it will only allow SSH ones. Here we have a file called ‘CreateSecurityGroup.java‘:

import java.util.Collections;
import java.util.List;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
import com.amazonaws.services.ec2.model.CreateSecurityGroupResult;
import com.amazonaws.services.ec2.model.IpPermission;


public class CreateSecurityGroup {

    public static void main(String[] args) throws Exception {


        AmazonEC2 ec2 = new GetEc2Client().getClient();


        try {
            CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest(
                    "TutorialSecurityGroup", "Tutorial Security Group");
            CreateSecurityGroupResult result = ec2
                    .createSecurityGroup(securityGroupRequest);
            System.out.println(String.format("Security group created: [%s]",
                    result.getGroupId()));
        } catch (AmazonServiceException ase) {
            System.out.println(ase.getMessage());
        }


        String ipAddr = new GetMyIp().getIp();
        List<String> ipRanges = Collections.singletonList(ipAddr);


        IpPermission ipPermission = new IpPermission()
                .withIpProtocol("tcp")
                .withFromPort(new Integer(22))
                .withToPort(new Integer(22))
                .withIpRanges(ipRanges);

        List<IpPermission> ipPermissions = Collections.singletonList(ipPermission);

        try {
            AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest(
                    "TutorialSecurityGroup", ipPermissions);
            ec2.authorizeSecurityGroupIngress(ingressRequest);
            System.out.println(String.format("Ingress port authroized: [%s]",
                    ipPermissions.toString()));
        } catch (AmazonServiceException ase) {
            System.out.println(ase.getMessage());
        }
    }

}

We will also need something to determine our public IP address, and here it comes ‘GetMyIp.java‘, take note of the fact that you might be in a different kind of network, and have a different IP mask:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

public class GetMyIp {

    private String ipAddress;

    public GetMyIp() throws Exception{

        this.ipAddress = "0.0.0.0/0";

        URL whatismyip = new URL("http://checkip.amazonaws.com");
        BufferedReader in = new BufferedReader(new InputStreamReader(
                whatismyip.openStream()));

        this.ipAddress = in.readLine() + "/32";

    }

    public String getIp() {
        return this.ipAddress;
    }

}

We also have to generate a private key to SSH into our instances, we will create a file called ‘CreateKeyPair.java‘.

Run it and copy the output in a file called ‘TutorialKeyName.pem‘ which you’ll put inside a folder you like, better inside the folder in which you’ll issue the SSH command, so you won’t have to specify the path.

import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
import com.amazonaws.services.ec2.model.CreateKeyPairResult;
import com.amazonaws.services.ec2.model.KeyPair;


public class CreateKeyPair {

    public static void main(String[] args) {


        AmazonEC2 ec2 = new GetEc2Client().getClient();

        CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest();
        createKeyPairRequest.withKeyName("TutorialKeyName");

        CreateKeyPairResult createKeyPairResult =
                ec2.createKeyPair(createKeyPairRequest);

        KeyPair keyPair = new KeyPair();
        keyPair = createKeyPairResult.getKeyPair();

        System.out.println(keyPair.getKeyMaterial());

    }

}

And now comes the cool part, in this file called ‘LaunchInstances.java‘ we can initiate our instances and then we can SSH into them:

import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.*;


public class LaunchInstances {

    public static void main(String[] args) {


        AmazonEC2 ec2 = new GetEc2Client().getClient();

        RunInstancesRequest runInstancesRequest = new RunInstancesRequest();

        runInstancesRequest.withImageId("ami-a9d09ed1")
                .withInstanceType(InstanceType.T1Micro)
                .withMinCount(1)
                .withMaxCount(1)
                .withKeyName("TutorialKeyName")
                .withSecurityGroups("TutorialSecurityGroup");

        RunInstancesResult result = ec2.runInstances(runInstancesRequest);

        System.out.println(result.toString());

    }

}

Please take note of the output and copy the relative IP address, you will use it inside your favourite shell, open it and issue a command like that, simply replace the IP, which is fake:

C:\Users\benedict>ssh -i TutorialKeyName.pem ec2-user@00.000.000.000

Note that the login user is called ‘ec2-user‘ in that we have instanced an Amazon Linux image, had it been Ubuntu it would have been called, you guessed it, ‘ubuntu‘. Every distro has a default username, you can discover how to find them on this complete guide by AWS.

Now it’s time to show our instances, we can create and run a file called ‘ShowInstances.java‘, then simply take note of the relative instance id, from the output. Copy and paste it in a sheet of your favourite editor.

You’ll also see some useful information about them, for example you’ll see if they’re running. Not finished yet… We have to stop, start, reboot and terminate our instances, you will be asked for an instance id. And here we have ‘StopInstances.java‘:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.StopInstancesRequest;


public class StopInstances {

    public static void main(String[] args) throws IOException {


        System.out.print("Enter your instance id: ");
        BufferedReader reader =
                new BufferedReader(new InputStreamReader(System.in));

        String instanceId = reader.readLine();


        AmazonEC2 ec2 = new GetEc2Client().getClient();

        StopInstancesRequest stopRequest = new StopInstancesRequest()
                .withInstanceIds(instanceId);

        ec2.stopInstances(stopRequest);

    }

}

Consider that if you stop and restart an instance, it will probably get a different IP address, you will have to SSH into a different host. Then it comes ‘StartInstances.java‘, which will be run after:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.StartInstancesRequest;


public class StartInstances {

    public static void main(String[] args) throws IOException {


        System.out.print("Enter your instance id: ");
        BufferedReader reader =
                new BufferedReader(new InputStreamReader(System.in));

        String instanceId = reader.readLine();


        AmazonEC2 ec2 = new GetEc2Client().getClient();

        StartInstancesRequest request = new StartInstancesRequest()
                .withInstanceIds(instanceId);

        ec2.startInstances(request);

    }

}

Then we will have ‘RebootInstances.java‘, and we will run it:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.RebootInstancesRequest;
import com.amazonaws.services.ec2.model.RebootInstancesResult;


public class RebootInstances {

    public static void main(String[] args) throws IOException {


        System.out.print("Enter your instance id: ");
        BufferedReader reader =
                new BufferedReader(new InputStreamReader(System.in));

        String instanceId = reader.readLine();


        AmazonEC2 ec2 = new GetEc2Client().getClient();

        RebootInstancesRequest request = new RebootInstancesRequest()
                .withInstanceIds(instanceId);

        RebootInstancesResult response =
                ec2.rebootInstances(request);

    }

}

And finally ‘TerminateInstances.java‘, which you will run at the end of this tutorial:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.TerminateInstancesRequest;


public class TerminateInstances {

    public static void main(String[] args) throws IOException {


        System.out.print("Enter your instance id: ");
        BufferedReader reader =
                new BufferedReader(new InputStreamReader(System.in));

        String instanceId = reader.readLine();


        AmazonEC2 ec2 = new GetEc2Client().getClient();

        TerminateInstancesRequest termianteRequest = new TerminateInstancesRequest()
                .withInstanceIds(instanceId);

        ec2.terminateInstances(termianteRequest);

    }

}

For the purpose of completing this tutorial you’re gonna have to install the AWS CLI on your machine and it will also have to be configured. If you’re new to AWS please consider this tutorial on how to do it, and you will learn much more else.

In this tutorial you learned how to build and manage EC2 instances on AWS by means of the Java SDK. Should you need the full code of it please go to this GitHub repository and you can clone it onto your machine. Feel free to contact me if you need further assistance.

Thanks again for following me and I’ll see you next time, till then, enjoy your coding and goodbye.

Did you like this post? Please comment here below and share it on your preferred social networks, thank you!

Published by

Mirko Benedetti

Hi there, my name is Mirko Benedetti and I'm a Software Developer. Excellence is what I consider to be our ultimate goal, and passion for technology constantly drives me to it. I began programming self-taught at a very young age; since then I learned a lot and every day I love learning new things. Here is my Linkedin Curriculum, feel free to connect.

2 thoughts on “Java and EC2: the AWS SDK in a few words”

  1. Thank you Beatriz,
    I’m looking forward to write onother one.
    Other topics will follow…
    See you

Leave a Reply

Give me your opinion, I will be grateful.