4

I'm using the below code to get all the available volumes under EC2. But I can't find any Ec2 api to get already attached volumes with an instance. Please let me know how to get all attached volumes using instanceId.

EC2Api ec2Api = computeServiceContext.unwrapApi(EC2Api.class);
List<String> volumeLists = new ArrayList<String>();
if (null != volumeId) {
    volumeLists.add(volumeId);
}
String[] volumeIds = volumeLists.toArray(new String[0]);
LOG.info("the volume IDs got from user is ::"+ Arrays.toString(volumeIds));

Set<Volume> ec2Volumes = ec2Api.getElasticBlockStoreApi().get()
                    .describeVolumesInRegion(region, volumeIds);

Set<Volume> availableVolumes = Sets.newHashSet();
for (Volume volume : ec2Volumes) {
    if (volume.getSnapshotId() == null
            && volume.getStatus() == Volume.Status.AVAILABLE) {
        LOG.debug("available volume with no snapshots ::" + volume.getId());
        availableVolumes.add(volume);
   }
}
grkvlt
  • 2,577
  • 1
  • 21
  • 38
bagui
  • 844
  • 4
  • 18
  • 37

3 Answers3

4

The AWS Java SDK now provides a method to get all the block device mappings for an instance. You can use that to get a list of all the attached volumes:

// First get the EC2 instance from the id
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest().withInstanceIds(instanceId);
DescribeInstancesResult describeInstancesResult = ec2.describeInstances(describeInstancesRequest);
Instance instance = describeInstancesResult.getReservations().get(0).getInstances().get(0);

// Then get the mappings
List<InstanceBlockDeviceMapping> mappingList = instance.getBlockDeviceMappings();
for(InstanceBlockDeviceMapping mapping: mappingList) {
    System.out.println(mapping.getEbs().getVolumeId());
}
Slartibartfast
  • 1,592
  • 4
  • 22
  • 33
3

You can filter the output of the EC2 DescribeVolumes API call. There are various attachment.* filters available, the one you want is filtering by attached instance ID. Try the following code:

Multimap<String, String> filter = ArrayListMultimap.create();
filter.put("attachment.instance-id", instanceId);
filter.put("attachment.status", "attached");
Set<Volume> volumes = ec2Api.getElasticBlockStoreApi().get()
                .describeVolumesInRegionWithFilter(region, volumeIds, filter);

The filter is a Multimap with the keys and values you want to filter on. You can actually specify the same filter multiple times, for example to get all volumes attached to a number of different instances.

grkvlt
  • 2,577
  • 1
  • 21
  • 38
-1

You can use volumeAttachmentApi.listAttachmentsOnServer() to do this.

 NovaApi novaApi = context.unwrapApi(NovaApi.class);VolumeApi volumeApi = novaApi.getVolumeExtensionForZone(region).get();
        VolumeAttachmentApi volumeAttachmentApi = novaApi.getVolumeAttachmentExtensionForZone(region).get();
volumeAttachmentApi.listAttachmentsOnServer(serverId)
Udara S.S Liyanage
  • 6,189
  • 9
  • 33
  • 34