How To Create EC2 Instances Using SDK For JAVA ?
Last Updated :
20 Feb, 2024
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"
.png)
- 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.
.png)
- We can also verify the deployment in console as below.
.png)
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.
Similar Reads
How To Change The Key Pair For EC2 Instance
Amazon EC2 provides customizable virtual servers. To securely access them we use key pair. In this article, I will make sure you understand Amazon EC2 and how to secure them using key pairs, and also I will guide you through the step-by-step process to change your key pair of EC2 instances to ensure
5 min read
How to Create AWS EC2 using Terraform?
AWS EC2 (Elastic Compute Cloud) is a web service provided by Amazon Web Services (AWS) that allows users to launch and oversee virtual servers, known as examples, in the cloud. It gives an adaptable and versatile foundation for running different sorts of applications and jobs. With Terraform EC2, cl
13 min read
How To Create Redhat EC2 Instance in AWS
provisioning the Red Hat Enterprise Linux (RHEL) instances on Amazon Web Services (AWS) offers a powerful and versatile solution for hosting and running applications, overseeing the jobs, and utilizing the abilities of both platforms. Red Hat Enterprise Linux is a main Linux distribution eminent for
5 min read
How To Install Java Using Ansible PlayBook ?
In today's dynamic IT landscape, effective management and automation of software installations across various servers are pivotal for maintaining consistency, dependability, and versatility. Ansible, an open-source automation tool, has acquired huge popularity for its simplicity and flexibility in a
7 min read
How to create unit tests in eclipse?
Unit testing, also known as component testing, involves testing small pieces of code to ensure that their actual behavior matches the expected behavior. Eclipse, a widely used IDE for Java development, is also commonly used for testing purposes. In Java, JUnit is the preferred framework for unit tes
6 min read
How to Install Java JDK11 on AWS EC2?
AWS or Amazon web services is a cloud service platform that provides on-demand computational services, databases, storage space, and many more services. EC2 or Elastic Compute Cloud is a scalable computing service launched on the AWS cloud platform. In simpler words, EC2 is nothing but a virtual com
2 min read
How to Create IAM roles for Amazon EC2?
In this article, we will cover how we can easily create an IAM role use it with an EC2 instance, and provide the required permissions with the S3 policies. These IAM Roles are the identities that we are creating in our account so that we can provide specific permissions to the users. So these Roles
7 min read
How to Create AWS Instance Scheduler ?
Sometimes the AWS EC2 instances are created unnecessarily, causing an unwanted bill where the resources were not used and we still have to pay for them. In such scenarios, an instance scheduler comes in handy, to avoid the hassle of redundant and extra instances and to help save money. In this artic
5 min read
How to Connect to Amazon Linux Instance Using SSH?
Pre-requisites: AWS, SSH TOOLS AWS stands for Amazon Web Services, and it is a cloud computing platform provided by Amazon. AWS provides a range of cloud-based services, including computing power, storage, databases, analytics, machine learning, and many other resources that businesses and individua
3 min read
How To Create Spot Instance In Aws-Ec2 In Aws Latest Wizards?
Spot instances are available at up to 90% discount because when instances are not used then the instance available in spot instance at a cheaper rate so that people can utilize. it. When the demand increases then amazon sent a notification your spot instance will disappear after two minutes. We can
6 min read