List of usage examples for com.amazonaws.services.ec2.model Image getBlockDeviceMappings
public java.util.List<BlockDeviceMapping> getBlockDeviceMappings()
Any block device mapping entries.
From source file:com.carrotgarden.maven.aws.ecc.CarrotElasticCompute.java
License:BSD License
/** delete AMI image and related EBS snapshots */ public void imageDelete(final String imageId) throws Exception { final Image image = findImage(imageId); if (image == null) { logger.info("missing imageId = " + imageId); return;/*from ww w .j a va 2 s.c o m*/ } else { logger.info("present imageId = " + imageId); } imageUnregister(imageId); for (final BlockDeviceMapping blockDevice : image.getBlockDeviceMappings()) { final EbsBlockDevice elasticDevice = blockDevice.getEbs(); if (elasticDevice == null) { continue; } final String snapshotId = elasticDevice.getSnapshotId(); if (snapshotId == null) { continue; } snapshotDelete(snapshotId); } logger.info("removed imageId = " + imageId); }
From source file:com.carrotgarden.maven.aws.ecc.ElastiCompImageCreate.java
License:BSD License
@Override public void execute() throws MojoFailureException { try {/*from ww w .j a va 2s . c o m*/ getLog().info("image create init [" + imageName() + "]"); final CarrotElasticCompute compute = newElasticCompute(); final Image image = compute.imageCreate( // imageInstanceId(), // imageName(), // imageDescription // ); final ImageState state = ImageState.fromValue(image.getState()); switch (state) { case AVAILABLE: break; default: throw new IllegalStateException("image create failed : \n" + image); } final String imageId = image.getImageId(); /** publish result */ project().getProperties().put(imageResultProperty, image); project().getProperties().put(imageIdResultProperty, imageId); /** tag image */ compute.tagCreate(imageId, amazonTagName(), imageName()); /** tag image devices */ for (final BlockDeviceMapping blockDevice : image.getBlockDeviceMappings()) { final EbsBlockDevice elasticDevice = blockDevice.getEbs(); if (elasticDevice == null) { continue; } final String snapshotId = elasticDevice.getSnapshotId(); if (snapshotId == null) { continue; } compute.tagCreate(snapshotId, amazonTagName(), imageName()); } getLog().info("image create image=\n" + image); getLog().info("image create done [" + imageName() + "]"); } catch (final Exception e) { throw new MojoFailureException("bada-boom", e); } }
From source file:com.cloudera.director.aws.ec2.EC2Provider.java
License:Apache License
/** * Creates block device mappings based on the specified instance template. * * @param template the instance template * @return the block device mappings/* w w w . jav a 2 s . c om*/ */ private List<BlockDeviceMapping> getBlockDeviceMappings(EC2InstanceTemplate template) { // Query the AMI about the root device name & mapping information DescribeImagesResult result = client .describeImages(new DescribeImagesRequest().withImageIds(template.getImage())); if (result.getImages().isEmpty()) { throw new IllegalArgumentException("The description for image " + template.getImage() + " is empty"); } Image templateImage = result.getImages().get(0); String rootDeviceType = templateImage.getRootDeviceType(); if (!DEVICE_TYPE_EBS.equals(rootDeviceType)) { throw new IllegalArgumentException("The root device for image " + template.getImage() + " must be \"" + DEVICE_TYPE_EBS + "\", found: " + rootDeviceType); } List<BlockDeviceMapping> originalMappings = templateImage.getBlockDeviceMappings(); LOG.info(">> Original image block device mappings: {}", originalMappings); if (originalMappings.isEmpty()) { throw new IllegalArgumentException( "The image " + template.getImage() + " has no block device mappings"); } BlockDeviceMapping rootDevice = selectRootDevice(originalMappings, templateImage.getRootDeviceName()); if (rootDevice == null) { throw new IllegalArgumentException("Could not determine root device for image " + template.getImage() + " based on root device name " + templateImage.getRootDeviceName()); } // The encrypted property was added to the block device mapping in version 1.8 of the SDK. // It is a Boolean, but defaults to false instead of being unset, so we set it to null here. rootDevice.getEbs().setEncrypted(null); rootDevice.getEbs().setVolumeSize(template.getRootVolumeSizeGB()); rootDevice.getEbs().setVolumeType(template.getRootVolumeType()); rootDevice.getEbs().setDeleteOnTermination(true); List<BlockDeviceMapping> deviceMappings = Lists.newArrayList(rootDevice); int ebsVolumeCount = template.getEbsVolumeCount(); EBSAllocationStrategy ebsAllocationStrategy = EBSAllocationStrategy.get(template); switch (ebsAllocationStrategy) { case NO_EBS_VOLUMES: // The volumes within an instance should be homogeneous. So we only add // instance store volumes when additional EBS volumes aren't mounted. deviceMappings.addAll(ephemeralDeviceMappings.apply(template.getType())); break; case AS_INSTANCE_REQUEST: LOG.info("EBS volumes will be allocated as part of instance launch request"); List<BlockDeviceMapping> ebsDeviceMappings = getEbsBlockDeviceMapping(ebsVolumeCount, template.getEbsVolumeType(), template.getEbsVolumeSizeGiB(), template.isEnableEbsEncryption()); deviceMappings.addAll(ebsDeviceMappings); break; case AS_SEPARATE_REQUESTS: LOG.info("EBS volumes will be separately allocated after instance launch request"); break; default: throw new IllegalStateException("Invalid EBS allocation strategy " + ebsAllocationStrategy); } LOG.info(">> Block device mappings: {}", deviceMappings); return deviceMappings; }
From source file:com.netflix.simianarmy.aws.janitor.crawler.EBSSnapshotJanitorCrawler.java
License:Apache License
private void refreshSnapshotToAMIs() { snapshotToAMIs.clear();/*from www .j a va 2s . com*/ for (Image image : getAWSClient().describeImages()) { for (BlockDeviceMapping bdm : image.getBlockDeviceMappings()) { EbsBlockDevice ebd = bdm.getEbs(); if (ebd != null && ebd.getSnapshotId() != null) { LOGGER.debug(String.format("Snapshot %s is used to generate AMI %s", ebd.getSnapshotId(), image.getImageId())); Collection<String> amis = snapshotToAMIs.get(ebd.getSnapshotId()); if (amis == null) { amis = new ArrayList<String>(); snapshotToAMIs.put(ebd.getSnapshotId(), amis); } amis.add(image.getImageId()); } } } }
From source file:hudson.plugins.ec2.SlaveTemplate.java
License:Open Source License
private List<BlockDeviceMapping> getAmiBlockDeviceMappings() { /*// w ww . j a va 2 s.com * AmazonEC2#describeImageAttribute does not work due to a bug * https://forums.aws.amazon.com/message.jspa?messageID=231972 */ for (final Image image : getParent().connect().describeImages().getImages()) { if (ami.equals(image.getImageId())) { return image.getBlockDeviceMappings(); } } throw new AmazonClientException("Unable to get AMI device mapping for " + ami); }
From source file:org.excalibur.service.aws.ec2.EC2.java
License:Open Source License
@Override public Instances createInstances(final InstanceTemplate template, final boolean waitForRunningState) { LoginCredentials credentials = template.getLoginCredentials(); KeyPair keyPair = getKeyPair(checkNotNull(credentials.getCredentialName())); checkState(keyPair != null || (!isNullOrEmpty(credentials.getPublicKey()))); if (keyPair == null) { String material = decrypt(credentials.getPublicKey()); keyPair = new KeyPair().setKeyName(credentials.getCredentialName()).setKeyMaterial(material); keyPair.setKeyFingerprint(importKeyPair(keyPair)).setKeyMaterial(null); }//w w w . ja v a 2 s. com checkState(keyPair != null); createSecurityGroupIfDoesNotExist(defaultUserGroupName_); final Image image = getImageById(template.getImageId()); checkNotNull(image, String.format("Image %s does not exist", template.getImageId())); StringBuilder sb = new StringBuilder(); sb.append("#start-data\n").append("#").append(credentials.getPrivateKey()); if (!isNullOrEmpty(credentials.getPublicKey())) { sb.append("\n#").append(credentials.getPublicKey()); } sb.append("\n#end-data"); String userData = Strings2.nullAsEmpty(template.getUserData()) .concat(new String(Base64.encodeBase64(sb.toString().getBytes()))); RunInstancesRequest runInstacesRequest = new RunInstancesRequest() .withInstanceType(template.getInstanceType().getName()).withImageId(template.getImageId()) .withMinCount(template.getMinCount()).withMaxCount(template.getMaxCount()) .withKeyName(keyPair.getKeyName()).withSecurityGroups(defaultUserGroupName_).withUserData(userData); Zone zone = null; final Placement placement = new Placement(); if (template.getGroup() != null && !isNullOrEmpty(template.getGroup().getZone())) { zone = this.getZoneByName(template.getGroup().getZone()); checkState(zone != null, String.format("Invalid zone name [%s] on region [%s]", template.getGroup().getZone(), credentials_.getRegion().getName())); placement.withAvailabilityZone(zone.getName()); if (!isNullOrEmpty(template.getGroup().getGroupName())) { placement.withGroupName(template.getGroup().getGroupName()); this.createPlacementGroupsIfDoNotExist(template.getGroup()); } } if (zone == null) { zone = Lists2.first(listAvailableZonesOfRegion(this.credentials_.getRegion())); placement.withAvailabilityZone(zone.getName()); } checkNotNull(zone); checkState(!isNullOrEmpty(placement.getAvailabilityZone())); runInstacesRequest.withPlacement(placement); BlockDeviceMapping blockDeviceMapping = image.getBlockDeviceMappings().get(0); Integer diskSize = template.getDiskSize() == null ? SystemUtils2.getIntegerProperty("org.excalibur.amazon.default.disk.size", 30) : template.getDiskSize(); EbsBlockDevice disk = new EbsBlockDevice().withSnapshotId(blockDeviceMapping.getEbs().getSnapshotId()) .withVolumeSize(diskSize).withVolumeType("gp2"); runInstacesRequest.withBlockDeviceMappings( new BlockDeviceMapping().withDeviceName(image.getRootDeviceName()).withEbs(disk)); RunInstancesResult result = ec2_.runInstances(runInstacesRequest); template.setStatus(new InstanceTemplateStatus().setStatus(Status.SUCCESS)); Iterable<Instance> ec2Instances = waitForRunningState ? waitForRunningInstacesState(result.getReservation().getInstances()) : describeEC2Instances(result.getReservation().getInstances()); CreateTagsRequest tagsRequest = new CreateTagsRequest(); String instanceName = isNullOrEmpty(template.getInstanceName()) ? UUID.randomUUID().toString() : template.getInstanceName(); tagsRequest.withTags(new Tag().withKey(DEFAULT_INSTANCE_NAME_TAG).withValue(instanceName)); tagsRequest.withTags( new Tag().withKey(DEFAULT_PLATFORM_INSTANCE_USERNAME_TAG).withValue(DEFAULT_PLATFORM_USER_NAME)); tagsRequest.withTags(new Tag().withKey("keyname").withValue(keyPair.getKeyName())); tagsRequest.withResources(Collections2.transform(newArrayList(ec2Instances), INSTANCE_STRING_FUNCTION)); for (org.excalibur.core.cloud.api.domain.Tag tag : template.getTags()) { if (!isNullOrEmpty(tag.getName()) && !isNullOrEmpty(tag.getValue())) { tagsRequest.withTags(new Tag().withKey(tag.getName()).withValue(tag.getValue())); } } ec2_.createTags(tagsRequest); if (template.getMaxCount() > 1) { for (int i = 0; i < result.getReservation().getInstances().size(); i++) { CreateTagsRequest request = new CreateTagsRequest(); request.withResources(result.getReservation().getInstances().get(i).getInstanceId()) .withTags(new Tag().withKey(DEFAULT_INSTANCE_NAME_TAG) .withValue(String.format("%s-%s", instanceName, i + 1))); ec2_.createTags(request); } } // return new Instances(toExcaliburInstances(ec2Instances, keyPair)); Instances instances = this.describeInstances(ec2Instances); // LOG.debug("Waiting instances' ready state...."); ThreadUtils.sleep(30 * 1000); LOG.debug("Created [{}] instance(s) from [{}/{}]", instances.size(), template.getMinCount(), template.getMaxCount()); return instances; }