Open In App

How To Create EC2 Instances Using SDK For JAVA ?

Last Updated : 20 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The AWS SDK for Java provides various functionalities to use AWS services using APIs. It provides support for building Java applications easily with the help of the SDK. Using the SDK makes it easier to procure AWS services directly from Java code. Creating and provisioning EC2 instances from Java is possible through the SDK. Let’s see how to perform the creation of EC2 in Java.

Primary Terminologies

  • AWS SDK for Java: API Collection provides support for using AWS services from Java applications.
  • EC2: The elastic compute service in AWS provides infrastructure for virtual machines and instances.

Prerequisites

  • JAVA environment installed on the development machine.
  • Maven must be installed on the Java version installed.
  • AWS Single Sign-On access with user creation.
  • AWS CLI is installed with the latest version.

Steps to create an EC2 instance using the SDK for Java

Step 1: Setup the environment

  • Before starting setup, the SDK should be as described in AWS SDK SETUP FOR JAVA.
  • As we will be using Single Sign On for credentials, we will create a user in the AWS IAM identity center with the PowerUserAccess role.
  • After completing all the steps from setup configure sso in AWS CLI, Run the below command to configure
aws configure sso
  • Provide the required details as created in the setup steps. For the profile name give “default”

SSO Configuration

  • Now login to sso using below command.
aws sso login
  • Now we are ready to start.

Step 2: Create project

  • Create a new Java project with the help of Maven in your desired IDE.
  • You should add dependency for AWS SDK in pom.xml along with version under properties.
    <properties>
<aws.java.sdk.version>2.24.5</aws.java.sdk.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>${aws.java.sdk.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
  • Now add SDK module dependencies in dependencies section. We will add ec2 dependency. As we are using sso we will also add “sso” and “ssooidc” dependency.
  • Finally the pom.xml file should look like below.
<?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>com.gfg.ec2</groupId>
<artifactId>gfgec2</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<aws.java.sdk.version>2.24.5</aws.java.sdk.version>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>${aws.java.sdk.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>ec2</artifactId>
</dependency>

<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>sso</artifactId>
</dependency>

<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>ssooidc</artifactId>
</dependency>

</dependencies>
</project>

Step 3: Add code for creating instance.

  • Import all the required modules in the class file. we will be using following packages.
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.InstanceType;
import software.amazon.awssdk.services.ec2.model.RunInstancesRequest;
import software.amazon.awssdk.services.ec2.model.RunInstancesResponse;
import software.amazon.awssdk.services.ec2.model.Tag;
import software.amazon.awssdk.services.ec2.model.CreateTagsRequest;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;

  • First in the main method create a instance of Ec2Client. specify region for building the client.
Region region = Region.AP_SOUTH_1;
Ec2Client ec2 = Ec2Client.builder()
.region(region)
.build();

  • In the next step create a method for creating a instance with provide name and AMI image. For this article we are using image with id “ami-0449c34f967dbf18a”. You can also use your own AMI id.
  • Now create a request instance for creating instance with desired instance type. we are using t2.micro as type. Run the request and save the response in variable.
RunInstancesRequest runRequest = RunInstancesRequest.builder()
.imageId(amiId)
.instanceType(InstanceType.T2_MICRO)
.maxCount(1)
.minCount(1)
.build();
RunInstancesResponse response = ec2.runInstances(runRequest);

  • Add the tag to the instance using below code if required .
Tag tag = Tag.builder()
.key("Name")
.value(name)
.build();
CreateTagsRequest tagRequest = CreateTagsRequest.builder()
.resources(instanceId)
.tags(tag)
.build();

  • Finally run the tag request. The completed code should look like below. Specify your desired name for instance in place of “gfginstance”.
package com.gfg.ec2;

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.InstanceType;
import software.amazon.awssdk.services.ec2.model.RunInstancesRequest;
import software.amazon.awssdk.services.ec2.model.RunInstancesResponse;
import software.amazon.awssdk.services.ec2.model.Tag;
import software.amazon.awssdk.services.ec2.model.CreateTagsRequest;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;

public class Main {
public static void main(String[] args) {
String name = "gfginstance";
String amiId = "ami-0449c34f967dbf18a";
Region region = Region.AP_SOUTH_1;
Ec2Client ec2 = Ec2Client.builder()
.region(region)
.build();

String instanceId = createEC2Instance(ec2, name, amiId);
System.out.println("The Instance ID is " + instanceId);
ec2.close();
}

public static String createEC2Instance(Ec2Client ec2, String name, String amiId) {
RunInstancesRequest runRequest = RunInstancesRequest.builder()
.imageId(amiId)
.instanceType(InstanceType.T2_MICRO)
.maxCount(1)
.minCount(1)
.build();

RunInstancesResponse response = ec2.runInstances(runRequest);
String instanceId = response.instances().get(0).instanceId();
Tag tag = Tag.builder()
.key("Name")
.value(name)
.build();

CreateTagsRequest tagRequest = CreateTagsRequest.builder()
.resources(instanceId)
.tags(tag)
.build();

try {
ec2.createTags(tagRequest);
System.out.println("Successfully started EC2 Instance based on AMI "+amiId);
return instanceId;

} catch (Ec2Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

return "";
}
}
  • Run the code you should see output as below.

Running Code

  • We can also verify the deployment in console as below.

Instance Created

Conclusion

Thus, we have created a EC2 instance using AWS SDK for JAVA. AWS SDK makes it easy to procure EC2 instances directly from java code. AWS SDK can be further explored for more featureful EC2 configurations and deployments.

How to Create EC2 Instances using SDK for JAVA – FAQ’s

What is the AWS SDK for Java?

The AWS SDK for Java is a set of tools and libraries for Java developers to interact with Amazon Web Services (AWS) programmatically, allowing seamless integration with AWS services, including EC2.

What are the prerequisites for creating EC2 instances using Java SDK?

You need an AWS account, AWS access key ID, and secret access key. Ensure your IAM roles have the necessary permissions for EC2 actions.

Can I create EC2 instances with different configurations using the Java SDK?

Yes, the Java SDK allows you to create EC2 instances with various configurations, including specifying instance types, AMIs, security groups, IAM roles, key pairs, and more.

What are some best practices for using the AWS SDK for Java when working with EC2 instances?

Follow best practices for secure and efficient code. Ensure proper error handling, use asynchronous operations where needed, and organize your code for readability and maintainability.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads