Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all the attached volumes for an EC2 instance

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);
   }
}
like image 716
bagui Avatar asked Oct 11 '25 10:10

bagui


1 Answers

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());
}
like image 63
Slartibartfast Avatar answered Oct 15 '25 09:10

Slartibartfast