Java AWS SDK Create and Run EC2 Instance

Today I’ll show how to create and run Amazon EC2 instance with public IP and tags using Java AWS SDK. The Subnet, VPC and the Security Group for that EC2 instance were created previously via AWS Console.

Prerequisites

In order to run this code you only need to create an AWS account and you have to set up your AWS credentials. You need to have accessKey and secretKey for running this code.

Java Code

 

public class EC2Application {

    private static final AWSCredentials AWS_CREDENTIALS;

    static {
        // Your accesskey and secretkey
        AWS_CREDENTIALS = new BasicAWSCredentials(
                "AAAAAAAAAAAAAAAAAAAAA",
                "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
        );
    }

    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)
                .build();
        
        // Launch an Amazon EC2 Instance
        RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-777777")
                .withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
                .withMinCount(1)
                .withMaxCount(1)
                .withNetworkInterfaces(new InstanceNetworkInterfaceSpecification()
                        .withAssociatePublicIpAddress(true)
                        .withDeviceIndex(0)
                        .withSubnetId("subnet-777777")
                        .withGroups("sg-777777"));

        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()
                .withResources(instance.getInstanceId())
                .withTags(new Tag("Name", "codeflex-ec2"));
        ec2Client.createTags(createTagsRequest);

        // Starting the Instance
        StartInstancesRequest startInstancesRequest = new StartInstancesRequest().withInstanceIds(instanceId);

        ec2Client.startInstances(startInstancesRequest);

Now if you go to the Amazon Console you’ll see that the instance with name codeflex-ec2 is initializing and it’s state will become running in a minute or so.

Rebooting EC2 instance

This is how you reboot your EC2 instance:

        RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest()
                .withInstanceIds(instanceId);
        ec2Client.rebootInstances(rebootInstancesRequest);

 

Stopping your EC2 instance

        StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()
                .withInstanceIds(instanceId);

        ec2Client.stopInstances(stopInstancesRequest)
                .getStoppingInstances()
                .get(0)
                .getPreviousState()
                .getName();

5 COMMENTS

  1. Hello codeflex.co, can you please paste the complete code with import files and pom dependencies here ? or if you can please share your Github for me to clone and download the same …. Will really appreciate a prompt response, thanks ….

  2. Yeah , me too, getting multiple errors in compilation, hence requesting codeflex to share his project in Github completely.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.