Example usage for com.amazonaws.services.ec2.model Placement withAvailabilityZone

List of usage examples for com.amazonaws.services.ec2.model Placement withAvailabilityZone

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2.model Placement withAvailabilityZone.

Prototype


public Placement withAvailabilityZone(String availabilityZone) 

Source Link

Document

The Availability Zone of the instance.

Usage

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);
    }//from w  w  w .  jav a  2 s  .c  o  m

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