List of usage examples for com.amazonaws.services.ec2.model RunInstancesRequest withSubnetId
public RunInstancesRequest withSubnetId(String subnetId)
[EC2-VPC] The ID of the subnet to launch the instance into.
From source file:com.hazelcast.simulator.provisioner.AwsProvisioner.java
License:Open Source License
private List<Instance> createInstances(int instanceCount) { RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); runInstancesRequest.withImageId(awsAmi).withInstanceType(awsBoxId).withMinCount(instanceCount) .withMaxCount(instanceCount).withKeyName(awsKeyName); if (subNetId.isEmpty()) { runInstancesRequest.withSecurityGroups(securityGroup); } else {//from w ww. j a v a 2s .c om runInstancesRequest.withSubnetId(subNetId); } RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest); List<Instance> checkedInstances = new ArrayList<Instance>(); List<Instance> instances = runInstancesResult.getReservation().getInstances(); for (Instance instance : instances) { if (waitForInstanceStatusRunning(instance)) { addInstanceToAgentsFile(instance); checkedInstances.add(instance); componentRegistry.addAgent(instance.getPublicIpAddress(), instance.getPrivateIpAddress()); } else { LOGGER.warn("Timeout waiting for running status id=" + instance.getInstanceId()); } } return checkedInstances; }
From source file:com.rmn.qa.aws.AwsVmManager.java
License:Open Source License
public List<Instance> launchNodes(final String amiId, final String instanceType, final int numberToStart, final String userData, final boolean terminateOnShutdown) throws NodesCouldNotBeStartedException { RunInstancesRequest runRequest = new RunInstancesRequest(); runRequest.withImageId(amiId).withInstanceType(instanceType).withMinCount(numberToStart) .withMaxCount(numberToStart).withUserData(userData); if (terminateOnShutdown) { runRequest.withInstanceInitiatedShutdownBehavior("terminate"); }/*w w w . j av a 2 s.c o m*/ log.info("Setting image id: " + runRequest.getImageId()); log.info("Setting instance type: " + runRequest.getInstanceType()); Properties awsProperties = getAwsProperties(); String subnetKey = awsProperties.getProperty(region + "_subnet_id"); if (subnetKey != null) { log.info("Setting subnet: " + subnetKey); runRequest.withSubnetId(subnetKey); } String securityGroupKey = awsProperties.getProperty(region + "_security_group"); if (securityGroupKey != null) { String[] splitSecurityGroupdIds = securityGroupKey.split(","); List securityGroupIdsAryLst = new ArrayList(); for (int i = 0; i < splitSecurityGroupdIds.length; i++) { log.info("Setting security group(s): " + splitSecurityGroupdIds[i]); securityGroupIdsAryLst.add(splitSecurityGroupdIds[i]); } runRequest.setSecurityGroupIds(securityGroupIdsAryLst); } String keyName = awsProperties.getProperty(region + "_key_name"); if (keyName != null) { log.info("Setting keyname:" + keyName); runRequest.withKeyName(keyName); } log.info("Sending run request to AWS..."); RunInstancesResult runInstancesResult = getResults(runRequest, 0); log.info("Run request result returned. Adding tags"); // Tag the instances with the standard RMN AWS data List<Instance> instances = runInstancesResult.getReservation().getInstances(); if (instances.size() == 0) { throw new NodesCouldNotBeStartedException(String.format( "Error starting up nodes -- count was zero and did not match expected count of %d", numberToStart)); } associateTags(new Date().toString(), instances); return instances; }
From source file:com.rmn.qa.aws.AwsVmManager.java
License:Open Source License
/** * Attempts to run the {@link com.amazonaws.services.ec2.model.RunInstancesRequest RunInstancesRequest}, falling * back on alternative subnets if capacity is full in the current region. * * @param request//from w w w . j av a 2 s . co m * @param requestNumber * * @return * * @throws NodesCouldNotBeStartedException */ private RunInstancesResult getResults(final RunInstancesRequest request, int requestNumber) throws NodesCouldNotBeStartedException { RunInstancesResult runInstancesResult; try { AmazonEC2Client localClient = getClient(); if (localClient == null) { throw new RuntimeException("The client is not initialized"); } runInstancesResult = localClient.runInstances(request); } catch (AmazonServiceException e) { // If there is insufficient capacity in this subnet / availability zone, then we want to try other // configured subnets if ("InsufficientInstanceCapacity".equals(e.getErrorCode()) || "VolumeTypeNotAvailableInZone".equals(e.getErrorCode())) { log.error(String.format("Insufficient capacity in subnet [%s]: %s", request.getSubnetId(), e)); requestNumber = requestNumber + 1; Properties awsProperties = getAwsProperties(); String fallBackSubnetId = awsProperties .getProperty(region + "_subnet_fallback_id_" + requestNumber); // Make sure and only try to recursively loop so as long as we have a valid fallback subnet id. Logic // to also // prevent an accidental infinite loop if (fallBackSubnetId != null && requestNumber < 5) { log.info("Setting fallback subnet: " + fallBackSubnetId); // Modify the original request with the new subnet ID we're trying to fallback on request.withSubnetId(fallBackSubnetId); } else { throw new NodesCouldNotBeStartedException( "Sufficient resources were not available in any of the availability zones"); } return getResults(request, requestNumber); } else { // We got an error other than insufficient capacity, and should just throw it for the caller to handle throw e; } } return runInstancesResult; }
From source file:com.urbancode.terraform.tasks.aws.helpers.AWSHelper.java
License:Apache License
/** * Launches a single instance with given parameters. * The REQUIRED parameters are amiId;/* w w w . jav a 2s .c om*/ * You should always pass in a keyPair also, unless you know exactly what you are doing. Chances * are that you won't be able to get into your instance and it will be useless. * If groups is null, the instance will be launched with the default security group. * Subnet is only required if you're launching into a VPC. * * This will return the instanceId of the instance launched. * * @param amiId * @param subnetId * @param keyPair * @param size * @param userData * @param groups * @param ec2Client * @return instanceId */ public String launchAmi(String amiId, String subnetId, String keyPair, String size, String userData, List<String> groups, List<BlockDeviceMapping> blockMaps, String ariId, String akiId, String zone, String privateIp, AmazonEC2 ec2Client) { String instanceId = null; RunInstancesRequest request = new RunInstancesRequest().withImageId(amiId).withMinCount(1).withMaxCount(1); if (subnetId != null && !subnetId.isEmpty()) { // launch in VPC request = request.withSubnetId(subnetId); } else if (zone != null && !zone.isEmpty()) { // launch in EC2 Placement placement = new Placement().withAvailabilityZone(zone); request = request.withPlacement(placement); } else { log.error("No place to launch the instance specified." + "\nPlease specify either a subnet or region"); } if (keyPair != null) { request = request.withKeyName(keyPair); } if (size != null) { request = request.withInstanceType(size); } if (userData != null) { request = request.withUserData(Base64.encodeBase64String(userData.getBytes())); } if (groups != null && !groups.isEmpty()) { request = request.withSecurityGroupIds(groups); } if (blockMaps != null && !blockMaps.isEmpty()) { request = request.withBlockDeviceMappings(blockMaps); } if (ariId != null && !ariId.isEmpty()) { request = request.withRamdiskId(ariId); } if (akiId != null && !akiId.isEmpty()) { request = request.withKernelId(akiId); } if (privateIp != null && !privateIp.isEmpty()) { request = request.withPrivateIpAddress(privateIp); } RunInstancesResult result = ec2Client.runInstances(request); List<Instance> instances = result.getReservation().getInstances(); if (instances == null) { instanceId = null; log.error("List of instances is null!"); } else if (instances.size() == 0) { instanceId = null; log.error("List of instances is empty!"); } else if (instances.size() == 1) { instanceId = instances.get(0).getInstanceId(); log.info("Created instance with Id: " + instanceId); } else if (instances.size() > 1) { log.error("Too many instances! This is not supported!"); } return instanceId; }
From source file:com.vmware.photon.controller.model.adapters.awsadapter.AWSInstanceService.java
License:Open Source License
private void createInstance(AWSAllocation aws) { if (aws.computeRequest.isMockRequest) { AdapterUtils.sendPatchToProvisioningTask(this, aws.computeRequest.taskReference); return;//from w w w . jav a 2 s.co m } DiskState bootDisk = aws.childDisks.get(DiskType.HDD); if (bootDisk == null) { AdapterUtils.sendFailurePatchToProvisioningTask(this, aws.computeRequest.taskReference, new IllegalStateException("AWS bootDisk not specified")); return; } if (bootDisk.bootConfig != null && bootDisk.bootConfig.files.length > 1) { AdapterUtils.sendFailurePatchToProvisioningTask(this, aws.computeRequest.taskReference, new IllegalStateException("Only 1 configuration file allowed")); return; } URI imageId = bootDisk.sourceImageReference; if (imageId == null) { aws.error = new IllegalStateException("AWS ImageId not specified"); aws.stage = AWSStages.ERROR; handleAllocation(aws); return; } // This a single disk state with a bootConfig. There's no expectation // that it does exists, but if it does, we only support cloud configs at // this point. String cloudConfig = null; if (bootDisk.bootConfig != null && bootDisk.bootConfig.files.length > 0) { cloudConfig = bootDisk.bootConfig.files[0].contents; } String instanceType = aws.child.description.instanceType; if (instanceType == null) { // fallback to legacy usage of name instanceType = aws.child.description.name; } if (instanceType == null) { aws.error = new IllegalStateException("AWS Instance type not specified"); aws.stage = AWSStages.ERROR; handleAllocation(aws); return; } // let's try one more time for the security group -- just in case it // didn't // get retrieved during the firewall stage // // This will be removed in EN-1251 if (aws.securityGroupId == null) { aws.securityGroupId = getSecurityGroup(aws.amazonEC2Client).getGroupId(); // if we still don't have it kill allocation if (aws.securityGroupId == null) { aws.error = new IllegalStateException("SecurityGroup not found"); aws.stage = AWSStages.ERROR; handleAllocation(aws); return; } } RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId(imageId.toString()) .withInstanceType(instanceType).withMinCount(1).withMaxCount(1).withMonitoring(true) .withSecurityGroupIds(aws.securityGroupId); // use the subnet if provided if (aws.subnetId != null) { runInstancesRequest = runInstancesRequest.withSubnetId(aws.subnetId); } if (cloudConfig != null) { try { runInstancesRequest .setUserData(Base64.getEncoder().encodeToString(cloudConfig.getBytes(Utils.CHARSET))); } catch (UnsupportedEncodingException e) { aws.error = new IllegalStateException("Error encoding user data"); aws.stage = AWSStages.ERROR; handleAllocation(aws); return; } } // handler invoked once the EC2 runInstancesAsync commands completes AsyncHandler<RunInstancesRequest, RunInstancesResult> creationHandler = buildCreationCallbackHandler(this, aws.computeRequest, aws.child, aws.amazonEC2Client, aws.taskExpirationMicros); aws.amazonEC2Client.runInstancesAsync(runInstancesRequest, creationHandler); }
From source file:jp.primecloud.auto.process.aws.AwsInstanceProcess.java
License:Open Source License
public void run(AwsProcessClient awsProcessClient, Long instanceNo) { Instance instance = instanceDao.read(instanceNo); AwsInstance awsInstance = awsInstanceDao.read(instanceNo); ImageAws imageAws = imageAwsDao.read(instance.getImageNo()); PlatformAws platformAws = awsProcessClient.getPlatformAws(); // ?//w ww . j av a2s. com RunInstancesRequest request = new RunInstancesRequest(); request.withMinCount(1); request.withMaxCount(1); request.withImageId(imageAws.getImageId()); request.withKernelId(StringUtils.isEmpty(imageAws.getKernelId()) ? null : imageAws.getKernelId()); request.withRamdiskId(StringUtils.isEmpty(imageAws.getRamdiskId()) ? null : imageAws.getRamdiskId()); request.withKeyName(awsInstance.getKeyName()); request.withInstanceType(awsInstance.getInstanceType()); // UserData Map<String, String> userData = createUserData(instanceNo); request.withUserData(encodeUserData(userData)); // ?VPC?? if (BooleanUtils.isNotTrue(platformAws.getVpc())) { // AvailabilityZone if (StringUtils.isNotEmpty(awsInstance.getAvailabilityZone())) { request.withPlacement(new Placement(awsInstance.getAvailabilityZone())); } // SecurityGroup if (StringUtils.isNotEmpty(awsInstance.getSecurityGroups())) { for (String groupName : StringUtils.split(awsInstance.getSecurityGroups(), ",")) { request.withSecurityGroups(groupName.trim()); } } } // VPC?? else { // Subnet request.withSubnetId(awsInstance.getSubnetId()); // SecurytiGroup List<SecurityGroup> securityGroups = awsCommonProcess.describeSecurityGroupsByVpcId(awsProcessClient, platformAws.getVpcId()); for (String groupName : StringUtils.split(awsInstance.getSecurityGroups(), ",")) { groupName = groupName.trim(); for (SecurityGroup securityGroup : securityGroups) { if (StringUtils.equals(groupName, securityGroup.getGroupName())) { request.withSecurityGroupIds(securityGroup.getGroupId()); break; } } } // PrivateIpAddress if (StringUtils.isNotEmpty(awsInstance.getPrivateIpAddress())) { request.withPrivateIpAddress(awsInstance.getPrivateIpAddress()); } } // BlockDeviceMapping List<BlockDeviceMapping> blockDeviceMappings = createBlockDeviceMappings(awsProcessClient, imageAws, awsInstance); request.withBlockDeviceMappings(blockDeviceMappings); // processLogger.debug(null, instance, "AwsInstanceCreate", new Object[] { awsProcessClient.getPlatform().getPlatformName() }); // ?? RunInstancesResult result = awsProcessClient.getEc2Client().runInstances(request); Reservation reservation = result.getReservation(); if (reservation == null || reservation.getInstances().size() != 1) { // ? throw new AutoException("EPROCESS-000105"); } com.amazonaws.services.ec2.model.Instance instance2 = reservation.getInstances().get(0); // if (log.isInfoEnabled()) { log.info(MessageUtils.getMessage("IPROCESS-100115", instance2.getInstanceId())); } // awsInstance.setInstanceId(instance2.getInstanceId()); awsInstance.setStatus(instance2.getState().getName()); awsInstanceDao.update(awsInstance); }