Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in AWS by (19.1k points)

I was trying to create a new EC2 Instance in Eclipse Java using AWS SDK. Can someone provide the code for doing that?

1 Answer

0 votes
by (44.3k points)

Yes, use the below code and change it according to your needs.

package com.ec2application.ec2application;

import com.amazonaws.auth.AWSCredentials;

import com.amazonaws.auth.AWSStaticCredentialsProvider;

import com.amazonaws.auth.BasicAWSCredentials;

import com.amazonaws.regions.Regions;










public class CreateEc2instance


    private static final AWSCredentials AWS_CREDENTIALS;


    static {

        // Your accesskey and secretkey

        AWS_CREDENTIALS = new BasicAWSCredentials(


                "Your secret-key"



    public static void main(String[] args) {


        // Set up the amazon ec2 client

        AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()

                .withCredentials(new AWSStaticCredentialsProvider(AWS_CREDENTIALS))

                .withRegion(Regions.US_EAST_1) //Specify the region the instance should be launched in



        // Launch an Amazon EC2 Instance

        RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-0080e4c5bc078760e")

                .withInstanceType("t2.micro") //Enter the instance type, t2.micro is under free tier




                .withNetworkInterfaces(new InstanceNetworkInterfaceSpecification()

                        .withAssociatePublicIpAddress(true)//true if you want to enable public ip





        RunInstancesResult runInstancesResult = ec2Client.runInstances(runInstancesRequest);


        Instance instance = runInstancesResult.getReservation().getInstances().get(0);

        String instanceId = instance.getInstanceId();

        System.out.println("EC2 Instance Id: " + instanceId);


        // Setting up the tags for the instance

        CreateTagsRequest createTagsRequest = new CreateTagsRequest()


                .withTags(new Tag("Name", "Server"));



        // Starting the Instance

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




If you run this, it will automatically create an instance and you can view that in your AWS management console. But for this to work, you need AWS Toolkit for Eclipse, Download it from the link.

Related questions

0 votes
1 answer
asked Mar 12, 2020 in AWS by chandra (29.3k points)

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Apr 1, 2020 in AWS by chandra (29.3k points)
0 votes
1 answer
asked Jul 10, 2019 in AWS by yuvraj (19.1k points)

Browse Categories