I recently wanted to automate the creation of developer VMs in AWS using EC2 instances. To improve the developer experience (DX), I didn't like the developers having to shut down their instances to save money and lose their work. I wanted them to be able to hibernate their instances and return to where they left off. Unfortunately, I couldn't find an example of this using the AWS Java SDK v2. So after some experimentation, I created this example.
There are two requirements for hibernating an EC2 instance. First, the EBS drive must be encrypted. Second, the hibernate option must be enabled. Both of these requirements must be met when the instance is created.
Ec2Client ec2 = Ec2Client.builder()
.region(Region.US_EAST_2)
.build();
RunInstancesRequest runRequest = RunInstancesRequest.builder()
.imageId("ami-081f2c86d8b025c4b")
.instanceType(InstanceType.T3_MEDIUM)
.maxCount(1)
.minCount(1)
.keyName("dev-key")
.blockDeviceMappings(BlockDeviceMapping.builder()
.deviceName("/dev/xvda")
.ebs(EbsBlockDevice.builder()
.volumeSize(40)
.deleteOnTermination(true)
.encrypted(true)
.build())
.build())
.hibernationOptions(HibernationOptionsRequest.builder().configured(true).build())
.securityGroups("devvm-default-sg")
.build();
RunInstancesResponse response = ec2.runInstances(runRequest);
String instanceId = response.instances().get(0).instanceId();
software.amazon.awssdk.services.ec2.model.Tag nameTag = software.amazon.awssdk.services.ec2.model.Tag.builder()
.key("Name").value("hibernate example")
.build();
CreateTagsRequest tagRequest = CreateTagsRequest.builder()
.resources(instanceId)
.tags(nameTag)
.build();
ec2.createTags(tagRequest);
You can find a complete example at https://github.com/cjudd/ec2hibernate.