×
☰ See All Chapters

How to use AWS Java SDK to create an EC2 instance

AWS SDK is a programming framework designed to ease application creation using all major programming languages (Java, .NET, Python, and so on) and platforms (Android, iOS, and so on) from any major OS.

AWS also provides plugins or integrated development environment (IDE) toolkits which can be plugged into IDEs like Eclipse or Visual Studio IDE and can work with direct integration with an AWS account and all its resources.

In previous chapter we learnt to launch EC2 instance through AWS console, in this chapter let us see how we can do the same using AWS SDK directly from code. We will learn to use AWS Java SDK and API to create an EC2 instance, start and stop the instance, reboot it, back it up into an image, and restoring it from the backup.

Step 1: Create AWS accessKey and secretKey to connect from SDK to AWS

Click on your account and select Security Credentials.

how-to-use-aws-java-sdk-to-create-an-ec2-instance-0
 

Scroll a bit down and Click on “Create access key”

how-to-use-aws-java-sdk-to-create-an-ec2-instance-1
 

Select the consent check box and click on “Create access Key”

how-to-use-aws-java-sdk-to-create-an-ec2-instance-2
 

Once done, save the access key and secrete key in a secure place. The former serves the same function as a login name, and the latter acts like its password.

how-to-use-aws-java-sdk-to-create-an-ec2-instance-3
 

Step 2: Create java Project using Maven

In the command prompt execute the following maven command to generate Maven supported Java project named as “AWSEC2Example”.

mvn archetype:generate -DgroupId=com.java4coding -DartifactId=AWSEC2Example -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

how-to-use-aws-java-sdk-to-create-an-ec2-instance-4
 

This command creates a new maven Java project with the name “AWSEC2Example”, with complete directory structure.

how-to-use-aws-java-sdk-to-create-an-ec2-instance-5
 
how-to-use-aws-java-sdk-to-create-an-ec2-instance-6
 

Step 3: Import project into Intellij IDE

In Intellij IDE, Choose File –> New –> Module from Existing Sources –>Select pom.xml from newly created maven project, Click OK.

how-to-use-aws-java-sdk-to-create-an-ec2-instance-7
 
how-to-use-aws-java-sdk-to-create-an-ec2-instance-8
 

Step 4: Add dependencies in pom.xml

Add the maven parent, add the below AWS dependencies in pom.xml file.

pom.xml

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
       
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
   <
modelVersion>4.0.0</modelVersion>
   <
groupId>com.java4coding</groupId>
   <
artifactId>AWSEC2Example</artifactId>
   <
packaging>jar</packaging>
   <
version>1.0-SNAPSHOT</version>
   <
name>AWSEC2Example</name>
   <
url>https://maven.apache.org</url>
   <
dependencies>
       <
dependency>
           <
groupId>junit</groupId>
           <
artifactId>junit</artifactId>
           <
version>3.8.1</version>
           <
scope>test</scope>
       </
dependency>
       
<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk -->
       
<dependency>
           <
groupId>com.amazonaws</groupId>
           <
artifactId>aws-java-sdk</artifactId>
           <
version>1.12.395</version>
       </
dependency>
   </
dependencies>
</
project>

Step 5: Add AWS credentials to properties file

Right click on main folder and select New>Directory

how-to-use-aws-java-sdk-to-create-an-ec2-instance-9

Now you select resources and press Enter

how-to-use-aws-java-sdk-to-create-an-ec2-instance-10

Now you create awscredentials.properties file inside resources directory and add below property values. Add the accessKey and secretKey value you create in step 1.

application.properties

accessKey=****************
secretKey=**************************

 

Step 5: Create main class

Create a Java main class, in this class we are creating EC2 instance. EC2 instance has to be created with security group and key pair. We are creating security group and key pair and same we are using for EC2. When we create security group or key pair and if these does exists already we get exception, hence we are deleting them before creating. Also if the  security group or key pair is used by any other EC2 instance we get exception while deleting security group or key pair. In such case you must delete the EC2 instance or unbind the security group and key pair from EC2 instance from AWS console.

AWSEC2Demo.java

package com.java4coding;

import com.amazonaws.auth.*;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.*;

import java.util.Arrays;

public class AWSEC2Demo {
   
public static void main(String[] args) {
       
System.out.println("---------------Started--------------");
       
//DefaultAWSCredentialsProviderChain credentialsProvider = new DefaultAWSCredentialsProviderChain();
       
AWSCredentialsProvider provider = new PropertiesFileCredentialsProvider(
               
"F:\\My_Programs\\AWS\\AWSEC2Example\\src\\main\\resources\\awscredentials.properties");

       
AmazonEC2 amazonEC2Client = AmazonEC2Client.builder()
               .withRegion(
Regions.US_WEST_2)
               .withCredentials(
provider)
               .build();

       
// Delete security group if exists ------------------------------------
       System.out.println("Deleting security group if exists--------------");
       
DeleteSecurityGroupRequest deleteSecurityGroupRequest = new DeleteSecurityGroupRequest();
       
deleteSecurityGroupRequest.withGroupName("JavaSecurityGroup");
       
amazonEC2Client.deleteSecurityGroup(deleteSecurityGroupRequest);
       
System.out.println("Deleting security group done--------------");

       
// Create security Group ------------------------------------
       
System.out.println("Creating security group--------------");
       
CreateSecurityGroupRequest csgr = new CreateSecurityGroupRequest();
       
csgr.withGroupName("JavaSecurityGroup").withDescription("My security group");
       
CreateSecurityGroupResult createSecurityGroupResult =
               
amazonEC2Client.createSecurityGroup(csgr);
       
IpPermission ipPermission =
               
new IpPermission();

       
IpRange ipRange1 = new IpRange().withCidrIp("111.111.111.111/32");
       
IpRange ipRange2 = new IpRange().withCidrIp("150.150.150.150/32");

       
ipPermission.withIpv4Ranges(Arrays.asList(new IpRange[]{ipRange1, ipRange2}))
               .withIpProtocol(
"tcp")
               .withFromPort(
22)
               .withToPort(
22);

       
AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest =
               
new AuthorizeSecurityGroupIngressRequest();

       
authorizeSecurityGroupIngressRequest.withGroupName("JavaSecurityGroup")
               .withIpPermissions(
ipPermission);
       
amazonEC2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
       
System.out.println("Done creating security group--------------");

       
//  Delete key pair if exists ------------------------------------
       
System.out.println("Deleting key pair if exists--------------");
       
DeleteKeyPairRequest deleteKeyPairRequest = new DeleteKeyPairRequest();
       
deleteKeyPairRequest.withKeyName("ec2keyName");
       
amazonEC2Client.deleteKeyPair(deleteKeyPairRequest);
       
System.out.println("Deleting key pair done--------------");

       
//Create a Key Pair----------------
       
System.out.println("Creating key pair done--------------");
       
CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest();
       
createKeyPairRequest.withKeyName("ec2keyName");
       
CreateKeyPairResult createKeyPairResult =
               
amazonEC2Client.createKeyPair(createKeyPairRequest);
       
KeyPair keyPair = new KeyPair();
       
keyPair = createKeyPairResult.getKeyPair();
       
String privateKey = keyPair.getKeyMaterial();
       
System.out.println("Done creating key pair--------------");

       
//Run an Amazon EC2 Instance------------
       
RunInstancesRequest runInstancesRequest =
               
new RunInstancesRequest();
       
runInstancesRequest.withImageId("ami-a9d09ed1")
               .withInstanceType(
InstanceType.T1Micro)
               .withMinCount(
1)
               .withMaxCount(
1)
               .withKeyName(
"ec2keyName")
               .withSecurityGroups(
"JavaSecurityGroup");
       
RunInstancesResult result = amazonEC2Client.runInstances(
               
runInstancesRequest);
       
System.out.println(result);
       
System.out.println("---------------DONE---------------");
   }
}

 

Intellij Project Structure

how-to-use-aws-java-sdk-to-create-an-ec2-instance-11
 

Step 6: Run the application

Right click on AWSEC2Demo.java and select Run ‘AWSEC2Demo.main()’

how-to-use-aws-java-sdk-to-create-an-ec2-instance-12
Step 6: Verify EC2 instance from AWS Console
 

Login to AWS console and make sure you select the same region US_WEST_2  you have used in the program, otherwise you will not be able to see the EC2 instance you created from program.

how-to-use-aws-java-sdk-to-create-an-ec2-instance-13
 

Navigate EC2 console and you can see the EC2 instance created from the above example.

how-to-use-aws-java-sdk-to-create-an-ec2-instance-14
 

All Chapters
Author