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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read