查找EC2实例的所有附加卷

时间:2014-09-11 13:47:49

标签: java amazon-ec2 jclouds

我使用以下代码获取EC2下的所有可用卷。但我无法找到任何Ec2 api来获取已附加卷的实例。请让我知道如何使用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);
   }
}

3 个答案:

答案 0 :(得分:3)

您可以过滤EC2 DescribeVolumes API调用的输出。可以使用各种attachment.*过滤器,您想要的过滤器按附加的实例ID进行过滤。请尝试以下代码:

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);

filterMultimap,其中包含您要过滤的键和值。您实际上可以多次指定相同的过滤器,例如,将所有卷附加到许多不同的实例。

答案 1 :(得分:3)

AWS Java SDK现在提供了一种获取实例的所有块设备映射的方法。您可以使用它来获取所有附加卷的列表:

// 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());
}

答案 2 :(得分:-1)

您可以使用volumeAttachmentApi.listAttachmentsOnServer()来执行此操作。

 NovaApi novaApi = context.unwrapApi(NovaApi.class);VolumeApi volumeApi = novaApi.getVolumeExtensionForZone(region).get();
        VolumeAttachmentApi volumeAttachmentApi = novaApi.getVolumeAttachmentExtensionForZone(region).get();
volumeAttachmentApi.listAttachmentsOnServer(serverId)