How do I create an AMI image using the AWS Java 2.x SDK?

I need to programmatically create an AMI image of the EC2 instance that the application is running on. According to the AWS java docs there exists a class called CreateImageRequest. I’ve figured out how to instantiate such an object but i don’t know how to execute this request.

I’ve searched for an example on the code example github page of the AWS Java 2.x SDK but unfortunately it doesn’t include an example on how to create an AMI image. I’ve looked at the Amazon SDK developer guide as well but couldn’t find relevant information there either.

This is the code that I have sofar:

public String createEC2InstanceAMI(Ec2Client ec2, String name, String instanceId , boolean noReboot) {
    CreateImageRequest imageRequest = CreateImageRequest.builder()
            .instanceId(instanceId)
            .description("The AMI image for " + name)
            .name(name)
            .noReboot(noReboot)
            .build();
    ec2.runInstances(imageRequest); //This breaks.
}

I tried creating the request using the method runInstances but this requires a RunInstancesRequest object. Ec2Client doesn’t seem to have any other methods that are similar to the runInstances method that i could use to create an AMI image request.

How do I create and register an AMI image with the AWS java SDK v2.x?

>Solution :

ec2.runInstances() is a method for running (creating) new EC2 instances/servers. Obviously that’s not the correct method to call for creating an AMI. I suggest taking a few minutes to look at the SDK documentation.

The method you are looking for would be ec2.createImage().

Leave a Reply