Example usage for com.amazonaws.services.ec2.model LaunchSpecification setKeyName

List of usage examples for com.amazonaws.services.ec2.model LaunchSpecification setKeyName

Introduction

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

Prototype


public void setKeyName(String keyName) 

Source Link

Document

The name of the key pair.

Usage

From source file:EC2.java

License:Apache License

public List<String> launch(String workerAMI, String instanceType, int num, double price,
        List<String> securityGroups, String keyName, String userData, String charset)
        throws UnsupportedEncodingException {
    RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();
    requestRequest.setSpotPrice(Double.toString(price));
    requestRequest.setInstanceCount(Integer.valueOf(num));

    LaunchSpecification launchSpecification = new LaunchSpecification();
    launchSpecification.setImageId(workerAMI);
    launchSpecification.setInstanceType(instanceType);
    launchSpecification.setSecurityGroups(securityGroups);
    launchSpecification.setUserData(new String(Base64.encode(userData.getBytes(charset))));
    launchSpecification.setKeyName(keyName); //for test

    requestRequest.setLaunchSpecification(launchSpecification);
    RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);
    List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();

    List<String> spotInstanceRequestIds = new ArrayList<String>();

    for (SpotInstanceRequest requestResponse : requestResponses) {
        System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId());
        spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
    }/*from   ww w  . j  a va  2s .c  o m*/
    return spotInstanceRequestIds;
}

From source file:com.kpbird.aws.Main.java

private void createEC2SpotInstance() {
    try {/*from w  ww .  j  ava 2s .c o m*/
        /// Creating Spot Instance ////

        // Initializes a Spot Instance Request
        RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();
        // Request 1 x t1.micro instance with a bid price of $0.03.
        requestRequest.setSpotPrice(spotPrice);
        requestRequest.setInstanceCount(Integer.valueOf(1));
        LaunchSpecification launchSpecification = new LaunchSpecification();
        launchSpecification.setImageId(imageId);
        launchSpecification.setInstanceType(instanceType);
        launchSpecification.setMonitoringEnabled(true);

        // Add the security group to the request.
        ArrayList<String> securityGroups = new ArrayList<String>();
        securityGroups.add(groupName);
        launchSpecification.setSecurityGroups(securityGroups);

        launchSpecification.setKeyName(keyName);

        // Add the launch specifications to the request.
        requestRequest.setLaunchSpecification(launchSpecification);

        // Call the RequestSpotInstance API.
        RequestSpotInstancesResult requestResult = ec2client.requestSpotInstances(requestRequest);

        List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();

        // Setup an arraylist to collect all of the request ids we want to
        // watch hit the running state.
        ArrayList<String> spotInstanceRequestIds = new ArrayList<String>();

        // Add all of the request ids to the hashset, so we can determine when they hit the
        // active state.
        for (SpotInstanceRequest requestResponse : requestResponses) {
            System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId());
            spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
            log.Info(requestResponse.getInstanceId() + "\t" + requestResponse.getState());
        }

        String instanceId = null;
        boolean isWaiting = true;
        while (isWaiting) {
            log.Info("*** Waiting for Spot Instance Request ***");
            Thread.sleep(5000);
            DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
            describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);

            DescribeSpotInstanceRequestsResult describeResult = ec2client
                    .describeSpotInstanceRequests(describeRequest);
            List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();
            for (SpotInstanceRequest describeResponse : describeResponses) {
                log.Info(describeResponse.getInstanceId() + "\t" + describeResponse.getState() + "\t"
                        + describeResponse.getSpotInstanceRequestId() + "\t"
                        + describeResponse.getStatus().getCode() + "\t"
                        + describeResponse.getStatus().getMessage());
                if (describeResponse.getState().equals("active")) {
                    isWaiting = false;
                    instanceId = describeResponse.getInstanceId();
                    break;
                }
            }

        }
        isWaiting = true;
        while (isWaiting) {
            log.Info("*** Waiting for Instance Running ***");
            Thread.sleep(1000);
            DescribeInstancesResult r = ec2client.describeInstances();
            Iterator<Reservation> ir = r.getReservations().iterator();
            while (ir.hasNext()) {
                Reservation rr = ir.next();
                List<Instance> instances = rr.getInstances();
                for (Instance ii : instances) {
                    log.Info(ii.getImageId() + "\t" + ii.getInstanceId() + "\t" + ii.getState().getName() + "\t"
                            + ii.getPrivateDnsName());
                    if (ii.getState().getName().equals("running") && ii.getInstanceId().equals(instanceId)) {
                        log.Info(ii.getPublicDnsName());
                        String publicDNS = ii.getPublicDnsName();
                        log.Info("Public DNS :" + publicDNS);
                        isWaiting = false;
                    }
                }
            }
        }

        /// Creating Tag for New Instance ////
        log.Info("Creating Tags for New Instance");
        CreateTagsRequest crt = new CreateTagsRequest();
        ArrayList<Tag> arrTag = new ArrayList<Tag>();
        arrTag.add(new Tag().withKey("Name").withValue(instanceName));
        crt.setTags(arrTag);

        ArrayList<String> arrInstances = new ArrayList<String>();
        arrInstances.add(instanceId);
        crt.setResources(arrInstances);
        ec2client.createTags(crt);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.norbl.cbp.ppe.Ec2Wrangler.java

License:Open Source License

/** Note that spot price instances are <i>not</i> available for
 *  cluster instances.<p>/*from w ww  .  j  a  v  a  2  s.com*/
 *
 *  This method blocks until the spot order has been filled.
 *  This is necessary so that we can tag the instances.  Note
 *  when this method returns the instances may not be fully booted.
 *        
  * @param instanceType
  * @param imageID
  * @param availabilityZone
  * @param nInstances
  * @param keyName
  * @param securityGroupName
  * @param networkName
  * @param userData
  * @param spotPrice
  * @return
  * @throws MissingParamsException
  * @throws ImproperParamException 
  */
public String launchSpotInstances(InstanceType instanceType, String imageID, String availabilityZone,
        int nInstances, String keyName, String securityGroupName, String networkName, String userData,
        double spotPrice) throws MissingParamsException, ImproperParamException {

    LaunchSpecification spec = new LaunchSpecification();
    spec.setInstanceType(instanceType);
    spec.setImageId(imageID);
    if (Ec2Location.isValidAvailablityZone(ec2Client, availabilityZone))
        setAvailabilityZone(spec, availabilityZone);
    // else any zone will do, so don't set it.
    spec.setKeyName(keyName);
    List<String> sgs = new ArrayList<String>();
    sgs.add(securityGroupName);
    spec.setSecurityGroups(sgs);
    spec.setUserData(userData);
    if (isHVM(imageID))
        setupClusterPlacementGroup(spec);
    RequestSpotInstancesRequest reqSpot = new RequestSpotInstancesRequest();
    reqSpot.setInstanceCount(new Integer(nInstances));
    reqSpot.setSpotPrice(StringUtil.f2(spotPrice));

    reqSpot.setLaunchSpecification(spec);

    String networkID = NiM.createNetworkID();
    NetworkInfo ni = new NetworkInfo(networkID, networkName);
    NiM.register(ni);
    ni.setState(NetworkInfo.State.spotRequestPending);

    RequestSpotInstancesResult rr = ec2Client.requestSpotInstances(reqSpot);

    // In order to tag the instances, we must wait until the spot
    // orders have been placed.
    HashMap<String, String> sirHt = getSpotInstanceRequestIDs(rr);

    /* D */ if (sirHt.size() != nInstances) {
        ExceptionHandler
                .gui(new RuntimeException("Spot ht.size=" + sirHt.size() + " nInstances=" + nInstances));
    }

    List<String> instanceIDs;
    while ((instanceIDs = getIIDsForSpotRequest(sirHt)).size() < sirHt.size()) {
        //            /* D */ System.out.println("Ec2W waiting for spots: n=" +
        //                    instanceIDs.size() + "/" + sirHt.size() + "/" +
        //                    nInstances);
        try {
            Thread.sleep(ConstantsEc2.SPOT_STATE_NAP_TIME);
        } catch (InterruptedException ix) {
        }
    }

    ni.setState(NetworkInfo.State.pending);
    //         /* D */ System.out.println("Ec2W DONE waiting for spots: n=" +
    //                    instanceIDs.size() + "/" + sirHt.size() + "/" +
    //                    nInstances);

    tagInstances(instanceIDs, networkID, networkName);

    NiM.update(getInstancesAllListed()); // Update the network info

    return (networkID);
}

From source file:DynamicProvisioning.Requests.java

License:Open Source License

public String submitRequests() {
    String request = null;/*from  www  .  j a v  a 2s .  co  m*/
    //==========================================================================//
    //================= Submit a Spot Instance Request =====================//
    //==========================================================================//

    // Initializes a Spot Instance Request
    RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();

    // Request 1 x t1.micro instance with a bid price of $0.03.
    requestRequest.setSpotPrice("0.05");
    requestRequest.setInstanceCount(Integer.valueOf(1));

    // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
    // and the latest Amazon Linux AMI id available. Note, you should always use the latest
    // Amazon Linux AMI id or another of your choosing.
    LaunchSpecification launchSpecification = new LaunchSpecification();
    launchSpecification.setImageId("ami-d93622b8");
    launchSpecification.setInstanceType("t1.micro");

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();

    securityGroups.add("launch-wizard-3");
    launchSpecification.setSecurityGroups(securityGroups);
    launchSpecification.setKeyName("cassandra");
    // Add the launch specifications to the request.
    requestRequest.setLaunchSpecification(launchSpecification);

    // Call the RequestSpotInstance API.
    RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);

    List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();

    // Setup an arraylist to collect all of the request ids we want to watch hit the running
    // state.
    spotInstanceRequestIds = new ArrayList<String>();

    // Add all of the request ids to the hashset, so we can determine when they hit the
    // active state.
    for (SpotInstanceRequest requestResponse : requestResponses) {
        System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId());
        request = requestResponse.getSpotInstanceRequestId();
        spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());

    }
    return request;
}

From source file:hudson.plugins.ec2.SlaveTemplate.java

License:Open Source License

/**
 * Provision a new slave for an EC2 spot instance to call back to Jenkins
 */// w  w w  .  ja va 2s  . com
private EC2AbstractSlave provisionSpot(TaskListener listener) throws AmazonClientException, IOException {
    PrintStream logger = listener.getLogger();
    AmazonEC2 ec2 = getParent().connect();

    try {
        logger.println("Launching " + ami + " for template " + description);
        KeyPair keyPair = getKeyPair(ec2);

        RequestSpotInstancesRequest spotRequest = new RequestSpotInstancesRequest();

        // Validate spot bid before making the request
        if (getSpotMaxBidPrice() == null) {
            // throw new FormException("Invalid Spot price specified: " + getSpotMaxBidPrice(), "spotMaxBidPrice");
            throw new AmazonClientException("Invalid Spot price specified: " + getSpotMaxBidPrice());
        }

        spotRequest.setSpotPrice(getSpotMaxBidPrice());
        spotRequest.setInstanceCount(Integer.valueOf(1));
        spotRequest.setType(getBidType());

        LaunchSpecification launchSpecification = new LaunchSpecification();
        InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification();

        launchSpecification.setImageId(ami);
        launchSpecification.setInstanceType(type);

        if (StringUtils.isNotBlank(getZone())) {
            SpotPlacement placement = new SpotPlacement(getZone());
            launchSpecification.setPlacement(placement);
        }

        if (StringUtils.isNotBlank(getSubnetId())) {
            if (getAssociatePublicIp()) {
                net.setSubnetId(getSubnetId());
            } else {
                launchSpecification.setSubnetId(getSubnetId());
            }

            /* If we have a subnet ID then we can only use VPC security groups */
            if (!securityGroupSet.isEmpty()) {
                List<String> group_ids = getEc2SecurityGroups(ec2);
                if (!group_ids.isEmpty()) {
                    if (getAssociatePublicIp()) {
                        net.setGroups(group_ids);
                    } else {
                        ArrayList<GroupIdentifier> groups = new ArrayList<GroupIdentifier>();

                        for (String group_id : group_ids) {
                            GroupIdentifier group = new GroupIdentifier();
                            group.setGroupId(group_id);
                            groups.add(group);
                        }
                        if (!groups.isEmpty())
                            launchSpecification.setAllSecurityGroups(groups);
                    }
                }
            }
        } else {
            /* No subnet: we can use standard security groups by name */
            if (securityGroupSet.size() > 0)
                launchSpecification.setSecurityGroups(securityGroupSet);
        }

        // The slave must know the Jenkins server to register with as well
        // as the name of the node in Jenkins it should register as. The only
        // way to give information to the Spot slaves is through the ec2 user data
        String jenkinsUrl = Hudson.getInstance().getRootUrl();
        // We must provide a unique node name for the slave to connect to Jenkins.
        // We don't have the EC2 generated instance ID, or the Spot request ID
        // until after the instance is requested, which is then too late to set the
        // user-data for the request. Instead we generate a unique name from UUID
        // so that the slave has a unique name within Jenkins to register to.
        String slaveName = UUID.randomUUID().toString();
        String newUserData = "";

        // We want to allow node configuration with cloud-init and user-data,
        // while maintaining backward compatibility with old ami's
        // The 'new' way is triggered by the presence of '${SLAVE_NAME}'' in the user data 
        // (which is not too much to ask)
        if (userData.contains("${SLAVE_NAME}")) {
            // The cloud-init compatible way
            newUserData = new String(userData);
            newUserData = newUserData.replace("${SLAVE_NAME}", slaveName);
            newUserData = newUserData.replace("${JENKINS_URL}", jenkinsUrl);
        } else {
            // The 'old' way - maitain full backward compatibility
            newUserData = "JENKINS_URL=" + jenkinsUrl + "&SLAVE_NAME=" + slaveName + "&USER_DATA="
                    + Base64.encodeBase64String(userData.getBytes());
        }

        String userDataString = Base64.encodeBase64String(newUserData.getBytes());

        launchSpecification.setUserData(userDataString);
        launchSpecification.setKeyName(keyPair.getKeyName());
        launchSpecification.setInstanceType(type.toString());

        if (getAssociatePublicIp()) {
            net.setAssociatePublicIpAddress(true);
            net.setDeviceIndex(0);
            launchSpecification.withNetworkInterfaces(net);
        }

        boolean hasCustomTypeTag = false;
        HashSet<Tag> inst_tags = null;
        if (tags != null && !tags.isEmpty()) {
            inst_tags = new HashSet<Tag>();
            for (EC2Tag t : tags) {
                inst_tags.add(new Tag(t.getName(), t.getValue()));
                if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) {
                    hasCustomTypeTag = true;
                }
            }
        }
        if (!hasCustomTypeTag) {
            inst_tags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, "spot"));
        }

        if (StringUtils.isNotBlank(getIamInstanceProfile())) {
            launchSpecification.setIamInstanceProfile(
                    new IamInstanceProfileSpecification().withArn(getIamInstanceProfile()));
        }

        spotRequest.setLaunchSpecification(launchSpecification);

        // Make the request for a new Spot instance
        RequestSpotInstancesResult reqResult = ec2.requestSpotInstances(spotRequest);

        List<SpotInstanceRequest> reqInstances = reqResult.getSpotInstanceRequests();
        if (reqInstances.size() <= 0) {
            throw new AmazonClientException("No spot instances found");
        }

        SpotInstanceRequest spotInstReq = reqInstances.get(0);
        if (spotInstReq == null) {
            throw new AmazonClientException("Spot instance request is null");
        }

        /* Now that we have our Spot request, we can set tags on it */
        if (inst_tags != null) {
            for (int i = 0; i < 5; i++) {
                try {
                    updateRemoteTags(ec2, inst_tags, spotInstReq.getSpotInstanceRequestId());
                    break;
                } catch (AmazonServiceException e) {
                    if (e.getErrorCode().equals("InvalidSpotInstanceRequestID.NotFound")) {
                        Thread.sleep(5000);
                        continue;
                    }
                    throw e;
                }
            }

            // That was a remote request - we should also update our local instance data.
            spotInstReq.setTags(inst_tags);
        }

        logger.println("Spot instance id in provision: " + spotInstReq.getSpotInstanceRequestId());

        return newSpotSlave(spotInstReq, slaveName);

    } catch (FormException e) {
        throw new AssertionError(); // we should have discovered all configuration issues upfront
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}