List of usage examples for com.amazonaws.services.ec2.model RunInstancesRequest setSecurityGroups
public void setSecurityGroups(java.util.Collection<String> securityGroups)
[EC2-Classic, default VPC] The names of the security groups.
From source file:integratedtoolkit.connectors.amazon.EC2_2.java
License:Apache License
private RunInstancesResult createMachine(String instanceCode, String diskImage) throws Exception { //Create//from w w w .j a va 2s . c o m RunInstancesRequest runInstancesRequest = new RunInstancesRequest(diskImage, 1, 1); Placement placement = new Placement(placementCode); runInstancesRequest.setPlacement(placement); runInstancesRequest.setInstanceType(instanceCode); runInstancesRequest.setKeyName(keyPairName); ArrayList<String> groupId = new ArrayList<String>(); groupId.add(securityGroupName); runInstancesRequest.setSecurityGroups(groupId); //logger.debug("Requesting creation of VM: placement " + placementCode + ", keypair " + keyPairName + ", instance code " + instanceCode + ", security group " + securityGroupName); return client.runInstances(runInstancesRequest); }
From source file:jp.aws.test.ec2.EC2Instance.java
License:Apache License
/** * EC2/*from w w w . ja va 2 s .c o m*/ * * @param imageId * @param min * @param max * @param instanceType * @param keyPairName * @param availabilityZone * @param securityGroups * @return Vector<Instance> * @throws Exception */ public Vector<Instance> launchEC2Instances(String imageId, int min, int max, String instanceType, String keyPairName, String availabilityZone, Collection<String> securityGroups, String additionalInfo, String userData) throws Exception { Vector<Instance> newInstances = new Vector<Instance>(); if (min <= 0 || max <= 0 || min > max) { return newInstances; } RunInstancesRequest request = new RunInstancesRequest(); request.setImageId(imageId); request.setInstanceType(instanceType); request.setMinCount(min); request.setMaxCount(max); Placement p = new Placement(); if (availabilityZone.toLowerCase().equals("any")) availabilityZone = ""; // ?????? p.setAvailabilityZone(availabilityZone); request.setPlacement(p); request.setSecurityGroups(securityGroups); request.setKeyName(keyPairName);// assign Keypair name for this request request.setUserData(userData); request.setAdditionalInfo(additionalInfo); // RunInstancesResult runInstancesRes = clientManager.ec2().runInstances(request); String reservationId = runInstancesRes.getReservation().getReservationId(); List<Instance> instances = runInstancesRes.getReservation().getInstances(); if (runInstancesRes != null) { for (Instance instance : instances) { // EC2InstanceObject newInstanceObject = new // EC2InstanceObject(); // newInstanceObject.setDnsName(i.getPublicDnsName()); // newInstanceObject.setInstanceId(i.getInstanceId()); // instances.add(newInstanceObject); // newInstances.add(newInstanceObject); newInstances.add(instance); } } return newInstances; }
From source file:net.roboconf.iaas.ec2.IaasEc2.java
License:Apache License
/** * Prepares the request./*from www . j a v a2 s .com*/ * @param machineImageId the ID of the image to use * @param userData the user data to pass * @return a request * @throws UnsupportedEncodingException */ private RunInstancesRequest prepareEC2RequestNode(String machineImageId, String userData) throws UnsupportedEncodingException { RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); String flavor = this.iaasProperties.get(Ec2Constants.VM_INSTANCE_TYPE); if (StringUtils.isBlank(flavor)) flavor = "t1.micro"; runInstancesRequest.setInstanceType(this.iaasProperties.get(Ec2Constants.VM_INSTANCE_TYPE)); if (StringUtils.isBlank(machineImageId)) runInstancesRequest.setImageId(this.iaasProperties.get(Ec2Constants.AMI_VM_NODE)); else runInstancesRequest.setImageId(machineImageId); // FIXME (VZ): why this kernel ID? runInstancesRequest.setKernelId("aki-62695816"); runInstancesRequest.setMinCount(1); runInstancesRequest.setMaxCount(1); runInstancesRequest.setKeyName(this.iaasProperties.get(Ec2Constants.SSH_KEY_NAME)); String secGroup = this.iaasProperties.get(Ec2Constants.SECURITY_GROUP_NAME); if (StringUtils.isBlank(secGroup)) secGroup = "default"; runInstancesRequest.setSecurityGroups(Arrays.asList(secGroup)); /* // Create the block device mapping to describe the root partition. BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping(); blockDeviceMapping.setDeviceName("/dev/sda1"); // Set the delete on termination flag to false. EbsBlockDevice ebs = new EbsBlockDevice(); ebs.setSnapshotId(snapshotId); ebs.setDeleteOnTermination(Boolean.FALSE); blockDeviceMapping.setEbs(ebs); // Add the block device mapping to the block list. ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>(); blockList.add(blockDeviceMapping); // Set the block device mapping configuration in the launch specifications. runInstancesRequest.setBlockDeviceMappings(blockList); */ // The following part enables to transmit data to the VM. // When the VM is up, it will be able to read this data. String encodedUserData = new String(Base64.encodeBase64(userData.getBytes("UTF-8")), "UTF-8"); runInstancesRequest.setUserData(encodedUserData); return runInstancesRequest; }
From source file:net.roboconf.target.ec2.internal.Ec2IaasHandler.java
License:Apache License
/** * Prepares the request.//from w w w . j a v a 2s. c o m * @param targetProperties the target properties * @param userData the user data to pass * @return a request * @throws UnsupportedEncodingException */ private RunInstancesRequest prepareEC2RequestNode(Map<String, String> targetProperties, String userData) throws UnsupportedEncodingException { RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); String flavor = targetProperties.get(Ec2Constants.VM_INSTANCE_TYPE); if (Utils.isEmptyOrWhitespaces(flavor)) flavor = "t1.micro"; runInstancesRequest.setInstanceType(flavor); runInstancesRequest.setImageId(targetProperties.get(Ec2Constants.AMI_VM_NODE)); runInstancesRequest.setMinCount(1); runInstancesRequest.setMaxCount(1); runInstancesRequest.setKeyName(targetProperties.get(Ec2Constants.SSH_KEY_NAME)); String secGroup = targetProperties.get(Ec2Constants.SECURITY_GROUP_NAME); if (Utils.isEmptyOrWhitespaces(secGroup)) secGroup = "default"; runInstancesRequest.setSecurityGroups(Collections.singletonList(secGroup)); String availabilityZone = targetProperties.get(Ec2Constants.AVAILABILITY_ZONE); if (!Utils.isEmptyOrWhitespaces(availabilityZone)) runInstancesRequest.setPlacement(new Placement(availabilityZone)); // The following part enables to transmit data to the VM. // When the VM is up, it will be able to read this data. String encodedUserData = new String(Base64.encodeBase64(userData.getBytes(StandardCharsets.UTF_8)), "UTF-8"); runInstancesRequest.setUserData(encodedUserData); return runInstancesRequest; }
From source file:org.gridgain.grid.spi.cloud.ec2lite.GridEc2LiteCloudSpi.java
License:GNU General Public License
/** * Creates Amazon EC2 run instances request by provided command. * * @param cmd Cloud command./*from w w w . j av a 2 s . c om*/ * @return EC2 run instances request. * @throws GridSpiException If any exception occurs. */ private RunInstancesRequest createRunInstancesRequest(GridCloudCommand cmd) throws GridSpiException { assert cmd != null; Collection<GridCloudResource> rsrcs = cmd.resources(); int num = cmd.number(); assert rsrcs != null && !rsrcs.isEmpty(); assert num > 0; GridCloudResource img = null; Collection<String> grps = new ArrayList<String>(); // Separate image and security groups for (GridCloudResource rsrc : rsrcs) if (rsrc.type() == CLD_IMAGE) img = rsrc; else if (rsrc.type() == CLD_SECURITY_GROUP) grps.add(rsrc.id()); assert img != null; Map<String, String> imgParams = img.parameters(); Map<String, String> cmdParams = cmd.parameters(); if (imgParams == null) throw new GridSpiException( "Unable to process command (image parameters are null) [cmd=" + cmd + ", image=" + img + ']'); RunInstancesRequest req = new RunInstancesRequest(); req.setImageId(img.id()); req.setMinCount(num); req.setMaxCount(num); if (!grps.isEmpty()) req.setSecurityGroups(grps); String val; if (!F.isEmpty(val = imgParams.get(IMG_KERNEL_ID))) req.setKernelId(val); if (!F.isEmpty(val = imgParams.get(IMG_RAMDISK_ID))) req.setRamdiskId(val); Collection<String> userDataList = new LinkedList<String>(); if (cmdParams != null) { if (!F.isEmpty(val = cmdParams.get(INST_TYPE))) req.setInstanceType(val); if (!F.isEmpty(val = cmdParams.get(INST_PLACEMENT))) req.setPlacement(new Placement(val)); if (!F.isEmpty(val = cmdParams.get(INST_KEY_PAIR_NAME))) req.setKeyName(val); if (!F.isEmpty(val = cmdParams.get(INST_MON))) req.setMonitoring(Boolean.parseBoolean(val)); if (!F.isEmpty(val = cmdParams.get(INST_PASS_EC2_KEYS)) && Boolean.parseBoolean(val)) { userDataList.add(GRIDGAIN_ACCESS_KEY_ID_KEY + '=' + accessKeyId); userDataList.add(GRIDGAIN_SECRET_KEY_KEY + '=' + secretAccessKey); } if (!F.isEmpty(val = cmdParams.get(INST_MAIN_S3_BUCKET))) userDataList.add(GRIDGAIN_MAIN_S3_BUCKET_KEY + '=' + val); if (!F.isEmpty(val = cmdParams.get(INST_USER_S3_BUCKET))) userDataList.add(GRIDGAIN_EXT_S3_BUCKET_KEY + '=' + val); if (!F.isEmpty(val = cmdParams.get(INST_JVM_OPTS))) userDataList.add(val); } if (req.isMonitoring() == null) // Monitoring was not set from params, set default value req.setMonitoring(enableMon); if (!userDataList.isEmpty()) req.setUserData(new String(Base64.encodeBase64(F.concat(userDataList, USER_DATA_DELIM).getBytes()))); return req; }
From source file:org.gridgain.grid.util.ec2.GridEc2Helper.java
License:GNU General Public License
/** * @param imgId EC2 image ID./* www . jav a 2 s.c om*/ * @param keyPair Key pair name. * @param secGrps Security groups. * @param instType EC2 Instance type. * @param userData Instances user data. * @param count Instance count. * @param enableMon Enable CloudWatch monitoring. * @return List of started instances' IDs. * @throws GridException Thrown in case of any exception. */ private List<String> startInstances(String imgId, String keyPair, Collection<String> secGrps, String instType, String userData, int count, boolean enableMon) throws GridException { RunInstancesRequest req = new RunInstancesRequest(); req.setImageId(imgId); req.setInstanceType(instType); req.setKeyName(keyPair); req.setMaxCount(count); req.setMinCount(count); req.setMonitoring(enableMon); if (!F.isEmpty(secGrps)) req.setSecurityGroups(secGrps); if (userData != null) req.setUserData(new String(Base64.encodeBase64(userData.getBytes()))); RunInstancesResult res; try { res = ec2.runInstances(req); } catch (AmazonClientException ex) { throw new GridException("Failed to perform EC2 run instances request: " + ex.getMessage(), ex); } List<Instance> running = res.getReservation().getInstances(); if (running == null) throw new GridException("Received unexpected EC2 response (instances have not been started)."); List<String> ids = new ArrayList<String>(); for (Instance inst : running) ids.add(inst.getInstanceId()); if (enableMon) { MonitorInstancesRequest mReq = new MonitorInstancesRequest(); mReq.setInstanceIds(ids); try { ec2.monitorInstances(mReq); } catch (AmazonClientException ex) { throw new GridException("Failed to start instances monitoring.", ex); } } return ids; }
From source file:org.occiware.clouddriver.instance.InstanceOperations.java
License:Apache License
/** * Create one ec2 instance with data instance object. * @param instance/*from www . j av a 2 s .c o m*/ * @throws InstanceOperationException */ public InstanceDO createInstance(InstanceDO instance) throws InstanceOperationException { // Check instance data object before creation. checkInstanceObjCreation(instance); boolean hasPlacement = false; String keyPairName = instance.getKeyPairName(); String imageId = instance.getImage().getImageId(); String instanceType = instance.getInstanceType(); Boolean monitoring = instance.isMonitoring(); String region = instance.getRegionId(); String zone = instance.getZoneId(); List<GroupIdentifierDO> securityGroups = instance.getSecurityGroups(); String name = instance.getName(); String userData = instance.getUserData(); RunInstancesRequest rRequest = new RunInstancesRequest(imageId, 1, 1); rRequest.setInstanceType(instanceType); rRequest.setMonitoring(monitoring); if (keyPairName != null) { rRequest.setKeyName(keyPairName); } if (userData != null) { rRequest.setUserData(userData); } Placement placement = new Placement(); PlacementDO placementDO = instance.getPlacement(); if (placementDO != null && placementDO.getAvailabilityZone() != null) { placement.setAvailabilityZone(placementDO.getAvailabilityZone()); hasPlacement = true; } else { if (zone != null) { if (!zone.trim().isEmpty()) { placement.setAvailabilityZone(region + zone); hasPlacement = true; } } } if (placementDO != null) { String groupName = placementDO.getGroupName(); String tenancy = placementDO.getTenancy(); if (groupName != null) { placement.setGroupName(groupName); hasPlacement = true; } if (tenancy != null) { placement.setTenancy(tenancy); hasPlacement = true; } } if (hasPlacement) { rRequest.setPlacement(placement); } if (securityGroups != null && !securityGroups.isEmpty()) { List<String> securityGroupNames = new ArrayList<>(); for (GroupIdentifierDO secGroup : securityGroups) { securityGroupNames.add(secGroup.getGroupName()); } rRequest.setSecurityGroups(securityGroupNames); } RunInstancesResult runInstancesResult; List<Instance> instances; try { runInstancesResult = ec2Client.getClientInstance().runInstances(rRequest); instances = runInstancesResult.getReservation().getInstances(); } catch (AmazonServiceException ase) { logger.error("Exception thrown from aws : " + ase.getErrorCode() + " --> " + ase.getErrorMessage()); throw new InstanceOperationException(ase); } catch (AmazonClientException ace) { logger.error("Exception thrown from aws : " + ace.getMessage()); throw new InstanceOperationException(ace); } InstanceDO instanceDOToReturn = null; if (instances != null && !instances.isEmpty()) { instanceDOToReturn = InstanceDataFactory.buildInstanceDataFromModel(instances.get(0)); if (instanceDOToReturn != null && name != null && instanceDOToReturn.getInstanceId() != null) { TagsOperation tagOperation = new TagsOperation(ec2Client); tagOperation.createTag(instanceDOToReturn.getInstanceId(), "Name", name); } } return instanceDOToReturn; }
From source file:org.openinfinity.cloud.service.administrator.EC2Wrapper.java
License:Apache License
public Reservation createInstance(String amiId, Integer amount, String keyName, String zone, String instanceType, List<String> securityGroups) { Reservation reservation = null;//w w w . ja va 2s.c o m try { Integer minimumAmount = amount; Integer maximumAmount = amount; if (amiId == null) { return null; } String myAmiId = null; myAmiId = amiId; RunInstancesRequest runInstancesRequest = new RunInstancesRequest(myAmiId, minimumAmount, maximumAmount); runInstancesRequest.setKeyName(keyName); Placement placement = new Placement(); placement.setAvailabilityZone(zone); runInstancesRequest.setPlacement(placement); runInstancesRequest.setSecurityGroups(securityGroups); if (instanceType != null) { runInstancesRequest.setInstanceType(instanceType); } RunInstancesResult result = ec2.runInstances(runInstancesRequest); reservation = result.getReservation(); } catch (AmazonServiceException ase) { String message = ase.getMessage(); LOG.error("Caught Exception: " + message); LOG.error("Response Status Code: " + ase.getStatusCode()); LOG.error("Error Code: " + ase.getErrorCode()); LOG.error("Request ID: " + ase.getRequestId()); ExceptionUtil.throwSystemException(message, ase); } catch (AmazonClientException e) { e.printStackTrace(); ExceptionUtil.throwSystemException(e.getMessage(), e); } return reservation; }