I am trying to find a way to create a new EBS and attach it to a running instance pro grammatically through the AWSJavaSDK. I see ways to do this with command line tools and with rest based calls but no way through the SDK proper.
You should be able to use createVolume to create the item. That looks to return a CreateVolumeResult, which has a Volume object inside.
You would then take the Volume returned from the createVolume call and attachVolume with a matching AttachVolumeRequest.
This is all done after you create one of AWS AmazonEC2Client objects: documentation is all pulled from here.
Workflow of the code would probably look like this (note: pseudo code is used and there may be a few more pieces to hook in but the workflow should look something like this)
AWSCredentials credentials = new AWSCredentials();
AmazonEC2Client client = new AmazonEC2Client(credentials);
CreateVolumeResult request = new CreateVolumeRequest(java.lang.Integer size,
java.lang.String availabilityZone);
CreateVolumeResponse volumeResponse = client.createVolume(request);
AttachVolumeRequest attachRequest = new AttachVolumeRequest(volumeResponse.getVolume().getVolumeId(), java.lang.String instanceId, java.lang.String device);
client.attachVolume(attachRequest);
Please refer the following code to create the EBS volumes using java API.
public void createVolume(String instanceId){
System.out.println("Creating the volume begins...");
CreateVolumeRequest creq = new CreateVolumeRequest(50, "us-west-2a");
CreateVolumeResult cres = ec2.createVolume(creq);
// Create the list of tags we want to create
System.out.println("Setting the tags to the volume...");
ArrayList<Tag> instanceTags = new ArrayList<Tag>();
instanceTags.add(new Tag("Name","Sachin"));
CreateTagsRequest createTagsRequest = new CreateTagsRequest().withTags(instanceTags).withResources(cres.getVolume().getVolumeId());
ec2.createTags(createTagsRequest);
System.out.println("Attaching the volume to the instance....");
AttachVolumeRequest areq = new AttachVolumeRequest(cres.getVolume().getVolumeId(),instanceId, "/dev/sdh");
AttachVolumeResult ares = ec2.attachVolume(areq);
System.out.println("Creating the volume ends...");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With