com.amazonaws.services.ec2.model.RunInstancesRequest Java Examples
The following examples show how to use
com.amazonaws.services.ec2.model.RunInstancesRequest.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BaseTest.java From aws-mock with MIT License | 6 votes |
/** * Run instances with a random AMI ID. * * @param type * instance type * @param minCount * minimum start up instance number * @param maxCount * maximum start up instance number * @return a list of instances started. */ protected final List<Instance> runInstances(final InstanceType type, final int minCount, final int maxCount) { log.info("Run instances: type=" + type + ", minCount=" + minCount + ", maxCount=" + maxCount); RunInstancesRequest request = new RunInstancesRequest(); String imageId = randomAMI(); request.withImageId(imageId).withInstanceType(type.getName()) .withMinCount(minCount).withMaxCount(maxCount); RunInstancesResult result = amazonEC2Client.runInstances(request); return result.getReservation().getInstances(); }
Example #2
Source File: RunInstancesExample.java From aws-mock with MIT License | 6 votes |
/** * Run some new ec2 instances. * * @param imageId * AMI for running new instances from * @param runCount * count of instances to run * @return a list of started instances */ public static List<Instance> runInstances(final String imageId, final int runCount) { // pass any credentials as aws-mock does not authenticate them at all AWSCredentials credentials = new BasicAWSCredentials("foo", "bar"); AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials); // the mock endpoint for ec2 which runs on your computer String ec2Endpoint = "http://localhost:8000/aws-mock/ec2-endpoint/"; amazonEC2Client.setEndpoint(ec2Endpoint); // instance type String instanceType = "m1.large"; // run 10 instances RunInstancesRequest request = new RunInstancesRequest(); final int minRunCount = runCount; final int maxRunCount = runCount; request.withImageId(imageId).withInstanceType(instanceType) .withMinCount(minRunCount).withMaxCount(maxRunCount); RunInstancesResult result = amazonEC2Client.runInstances(request); return result.getReservation().getInstances(); }
Example #3
Source File: VmManagerTest.java From SeleniumGridScaler with GNU General Public License v2.0 | 6 votes |
@Test // Happy path test flow for launching nodes public void testLaunchNodes() throws NodesCouldNotBeStartedException{ MockAmazonEc2Client client = new MockAmazonEc2Client(null); RunInstancesResult runInstancesResult = new RunInstancesResult(); Reservation reservation = new Reservation(); reservation.setInstances(Arrays.asList(new Instance())); runInstancesResult.setReservation(reservation); client.setRunInstances(runInstancesResult); Properties properties = new Properties(); String region = "east", uuid="uuid",browser="chrome",os="windows"; Integer threadCount = 5,maxSessions=5; MockManageVm manageEC2 = new MockManageVm(client,properties,region); String userData = "userData"; manageEC2.setUserData(userData); List<Instance> instances = manageEC2.launchNodes(uuid,os,browser,null,threadCount,maxSessions); RunInstancesRequest request = client.getRunInstancesRequest(); Assert.assertEquals("Min count should match thread count requested", threadCount, request.getMinCount()); Assert.assertEquals("Max count should match thread count requested", threadCount, request.getMaxCount()); Assert.assertEquals("User data should match", userData, request.getUserData()); Assert.assertTrue("No security group should be set", request.getSecurityGroupIds().isEmpty()); Assert.assertNull("No subnet should be set", request.getSubnetId()); Assert.assertNull("No key name should be set", request.getKeyName()); }
Example #4
Source File: EC2CommunicationTest.java From development with Apache License 2.0 | 6 votes |
@Test public void testCreateInstanceSecurityGroupsMultiple() throws Exception { parameters.put(PropertyHandler.SECURITY_GROUP_NAMES, new Setting( PropertyHandler.SECURITY_GROUP_NAMES, "security_group1, security_group2")); ec2mock.createRunInstancesResult("instance3"); ec2mock.createDescribeImagesResult("image1"); ec2mock.createDescribeSubnetsResult("subnet-a77430d0"); ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0", "security_group1,security_group2"); ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4"); Image image = ec2comm.resolveAMI("image1"); ec2comm.createInstance(image); String result = ph.getAWSInstanceId(); assertEquals("instance3", result); ArgumentCaptor<RunInstancesRequest> arg1 = ArgumentCaptor .forClass(RunInstancesRequest.class); verify(ec2).runInstances(arg1.capture()); RunInstancesRequest rir = arg1.getValue(); // Network interfaces and an instance-level security groups may not be // specified on the same request.. assertEquals(2, rir.getNetworkInterfaces().get(0).getGroups().size()); // assertEquals("security_group1", rir.getSecurityGroups().get(0)); // assertEquals("security_group2", rir.getSecurityGroups().get(1)); }
Example #5
Source File: ExceptionHandleAwsClientWrapper.java From primecloud-controller with GNU General Public License v2.0 | 6 votes |
protected AutoException handleException(AmazonServiceException exception, Method method, Object[] args) { Object request = null; if (method.getParameterTypes().length > 0) { request = args[0]; } // UserDataにはパスワードが含まれているためマスクする if (request instanceof RunInstancesRequest) { ((RunInstancesRequest) request).setUserData(null); } String str = StringUtils.reflectToString(request); return new AutoException("EAWS-000003", exception, method.getName(), exception.getErrorCode(), exception.getMessage(), str); }
Example #6
Source File: MockAmazonEc2Client.java From SeleniumGridScaler with GNU General Public License v2.0 | 5 votes |
@Override public RunInstancesResult runInstances(RunInstancesRequest runInstancesRequest) throws AmazonServiceException, AmazonClientException { if(throwRunInstancesError != null) { AmazonClientException exceptionToThrow = throwRunInstancesError; if(!throwExceptionsInRunInstancesIndefinitely) { throwRunInstancesError = null; } throw exceptionToThrow; } this.runInstancesRequest = runInstancesRequest; return runInstancesResult; }
Example #7
Source File: EC2Impl.java From aws-sdk-java-resources with Apache License 2.0 | 5 votes |
@Override public List<Instance> createInstances(String imageId, Integer minCount, Integer maxCount, ResultCapture<RunInstancesResult> extractor) { RunInstancesRequest request = new RunInstancesRequest() .withImageId(imageId) .withMinCount(minCount) .withMaxCount(maxCount); return createInstances(request, extractor); }
Example #8
Source File: EC2Impl.java From aws-sdk-java-resources with Apache License 2.0 | 5 votes |
@Override public List<Instance> createInstances(RunInstancesRequest request, ResultCapture<RunInstancesResult> extractor) { ActionResult result = service.performAction("CreateInstances", request, extractor); if (result == null) return null; return CodecUtils.transform(result.getResources(), InstanceImpl.CODEC); }
Example #9
Source File: SubnetImpl.java From aws-sdk-java-resources with Apache License 2.0 | 5 votes |
@Override public List<Instance> createInstances(RunInstancesRequest request, ResultCapture<RunInstancesResult> extractor) { ActionResult result = resource.performAction("CreateInstances", request, extractor); if (result == null) return null; return CodecUtils.transform(result.getResources(), InstanceImpl.CODEC); }
Example #10
Source File: VmManagerTest.java From SeleniumGridScaler with GNU General Public License v2.0 | 5 votes |
@Test // Test launching an IE node works correctly public void testLaunchNodesIe() throws NodesCouldNotBeStartedException { MockAmazonEc2Client client = new MockAmazonEc2Client(null); RunInstancesResult runInstancesResult = new RunInstancesResult(); Reservation reservation = new Reservation(); reservation.setInstances(Arrays.asList(new Instance())); runInstancesResult.setReservation(reservation); client.setRunInstances(runInstancesResult); Properties properties = new Properties(); String region = "east", uuid="uuid",browser="internet explorer",os=null; Integer threadCount = 5,maxSessions=5; MockManageVm manageEC2 = new MockManageVm(client,properties,region); String userData = "userData"; String securityGroup="securityGroup",subnetId="subnetId",keyName="keyName",windowsImage="windowsImage"; properties.setProperty(region + "_security_group",securityGroup); properties.setProperty(region + "_subnet_id",subnetId); properties.setProperty(region + "_key_name", keyName); properties.setProperty(region + "_windows_node_ami", windowsImage); manageEC2.setUserData(userData); manageEC2.launchNodes(uuid,os,browser,null,threadCount,maxSessions); RunInstancesRequest request = client.getRunInstancesRequest(); Assert.assertEquals("Min count should match thread count requested",threadCount,request.getMinCount()); Assert.assertEquals("Max count should match thread count requested",threadCount,request.getMaxCount()); Assert.assertEquals("User data should match",userData,request.getUserData()); Assert.assertEquals("Image id should match",windowsImage,request.getImageId()); List<String> securityGroups = request.getSecurityGroupIds(); Assert.assertEquals("Only one security group should be set",1,securityGroups.size()); Assert.assertEquals("Only one security group should be set", securityGroup, securityGroups.get(0)); Assert.assertEquals("Subnet ids should match", subnetId, request.getSubnetId()); Assert.assertEquals("Key names should match", keyName, request.getKeyName()); }
Example #11
Source File: VmManagerTest.java From SeleniumGridScaler with GNU General Public License v2.0 | 5 votes |
@Test // Test the optional fields for launching a node are indeed optional public void testLaunchNodesOptionalFieldsSet() throws NodesCouldNotBeStartedException { MockAmazonEc2Client client = new MockAmazonEc2Client(null); RunInstancesResult runInstancesResult = new RunInstancesResult(); Reservation reservation = new Reservation(); reservation.setInstances(Arrays.asList(new Instance())); runInstancesResult.setReservation(reservation); client.setRunInstances(runInstancesResult); Properties properties = new Properties(); String region = "east", uuid="uuid",browser="chrome",os=null; Integer threadCount = 5,maxSessions=5; MockManageVm manageEC2 = new MockManageVm(client,properties,region); String userData = "userData"; String securityGroup="securityGroup",subnetId="subnetId",keyName="keyName",linuxImage="linuxImage"; properties.setProperty(region + "_security_group",securityGroup); properties.setProperty(region + "_subnet_id",subnetId); properties.setProperty(region + "_key_name", keyName); properties.setProperty(region + "_linux_node_ami", linuxImage); manageEC2.setUserData(userData); manageEC2.launchNodes(uuid,os,browser,null,threadCount,maxSessions); RunInstancesRequest request = client.getRunInstancesRequest(); Assert.assertEquals("Min count should match thread count requested",threadCount,request.getMinCount()); Assert.assertEquals("Max count should match thread count requested",threadCount,request.getMaxCount()); Assert.assertEquals("User data should match",userData,request.getUserData()); Assert.assertEquals("Image id should match",linuxImage,request.getImageId()); List<String> securityGroups = request.getSecurityGroupIds(); Assert.assertEquals("Only one security group should be set",1,securityGroups.size()); Assert.assertEquals("Only one security group should be set", securityGroup, securityGroups.get(0)); Assert.assertEquals("Subnet ids should match", subnetId, request.getSubnetId()); Assert.assertEquals("Key names should match", keyName, request.getKeyName()); }
Example #12
Source File: Ec2IaasHandler.java From roboconf-platform with Apache License 2.0 | 5 votes |
/** * Prepares the request. * @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; }
Example #13
Source File: Ec2IaasHandler.java From roboconf-platform with Apache License 2.0 | 5 votes |
@Override public String createMachine( TargetHandlerParameters parameters ) throws TargetException { this.logger.fine( "Creating a new machine on AWS." ); // For IaaS, we only expect root instance names to be passed if( InstanceHelpers.countInstances( parameters.getScopedInstancePath()) > 1 ) throw new TargetException( "Only root instances can be passed in arguments." ); String rootInstanceName = InstanceHelpers.findRootInstancePath( parameters.getScopedInstancePath()); // Deal with the creation String instanceId; try { AmazonEC2 ec2 = createEc2Client( parameters.getTargetProperties()); String userData = UserDataHelpers.writeUserDataAsString( parameters.getMessagingProperties(), parameters.getDomain(), parameters.getApplicationName(), rootInstanceName ); RunInstancesRequest runInstancesRequest = prepareEC2RequestNode( parameters.getTargetProperties(), userData ); RunInstancesResult runInstanceResult = ec2.runInstances( runInstancesRequest ); instanceId = runInstanceResult.getReservation().getInstances().get( 0 ).getInstanceId(); } catch( Exception e ) { this.logger.severe( "An error occurred while creating a new machine on EC2. " + e.getMessage()); throw new TargetException( e ); } return instanceId; }
Example #14
Source File: EC2Mockup.java From development with Apache License 2.0 | 5 votes |
public void createRunInstancesResult(String... instanceIds) { Collection<Instance> instances = new ArrayList<Instance>(); for (int i = 0; i < instanceIds.length; i++) { instances.add(new Instance().withInstanceId(instanceIds[i])); } Reservation reservation = new Reservation().withInstances(instances); RunInstancesResult result = new RunInstancesResult() .withReservation(reservation); doReturn(result).when(ec2).runInstances(any(RunInstancesRequest.class)); }
Example #15
Source File: V1ItemFactory.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
RunInstancesRequest small() { return new RunInstancesRequest() .withAdditionalInfo(randomS(50)) .withDisableApiTermination(true) .withMaxCount(5) .withBlockDeviceMappings(blockDeviceMappings(3)) .withCpuOptions(new CpuOptionsRequest().withCoreCount(5).withThreadsPerCore(5)) .withElasticGpuSpecification(new ElasticGpuSpecification().withType(randomS(50))) .withNetworkInterfaces(networkInterfaces(3)); }
Example #16
Source File: V1ItemFactory.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
RunInstancesRequest huge() { return new RunInstancesRequest() .withAdditionalInfo(randomS(50)) .withDisableApiTermination(true) .withMaxCount(5) .withBlockDeviceMappings(blockDeviceMappings(100)) .withCpuOptions(new CpuOptionsRequest().withCoreCount(5).withThreadsPerCore(5)) .withElasticGpuSpecification(new ElasticGpuSpecification().withType(randomS(50))) .withNetworkInterfaces(networkInterfaces(100)); }
Example #17
Source File: CreateInstance.java From aws-doc-sdk-examples with Apache License 2.0 | 5 votes |
public static void main(String[] args) { final String USAGE = "To run this example, supply an instance name and AMI image id\n" + "Ex: CreateInstance <instance-name> <ami-image-id>\n"; if (args.length != 2) { System.out.println(USAGE); System.exit(1); } String name = args[0]; String ami_id = args[1]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); RunInstancesRequest run_request = new RunInstancesRequest() .withImageId(ami_id) .withInstanceType(InstanceType.T1Micro) .withMaxCount(1) .withMinCount(1); RunInstancesResult run_response = ec2.runInstances(run_request); String reservation_id = run_response.getReservation().getInstances().get(0).getInstanceId(); Tag tag = new Tag() .withKey("Name") .withValue(name); CreateTagsRequest tag_request = new CreateTagsRequest() .withTags(tag); CreateTagsResult tag_response = ec2.createTags(tag_request); System.out.printf( "Successfully started EC2 instance %s based on AMI %s", reservation_id, ami_id); }
Example #18
Source File: EC2ProcessorTest.java From development with Apache License 2.0 | 5 votes |
@Test public void process_CREATION_REQUESTED() throws Exception { ph.setOperation(Operation.EC2_CREATION); ph.setState(FlowState.CREATION_REQUESTED); InstanceStatus result = ec2proc.process(); assertFalse(result.isReady()); assertEquals(FlowState.CREATING, ph.getState()); verify(ec2).runInstances(any(RunInstancesRequest.class)); }
Example #19
Source File: EC2CommunicationTest.java From development with Apache License 2.0 | 5 votes |
@Test public void testCreateInstance() throws Exception { ec2mock.createRunInstancesResult("instance1"); ec2mock.createDescribeImagesResult("image1"); ec2mock.createDescribeSubnetsResult("subnet-a77430d0"); ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0", "security_group1,security_group2"); ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4"); Image image = ec2comm.resolveAMI("image1"); ec2comm.createInstance(image); String result = ph.getAWSInstanceId(); assertEquals("instance1", result); ArgumentCaptor<RunInstancesRequest> arg1 = ArgumentCaptor .forClass(RunInstancesRequest.class); verify(ec2).runInstances(arg1.capture()); RunInstancesRequest rir = arg1.getValue(); assertEquals("image1", rir.getImageId()); assertEquals("type1", rir.getInstanceType()); assertEquals("key_pair", rir.getKeyName()); assertEquals(1, rir.getMinCount().intValue()); assertEquals(1, rir.getMaxCount().intValue()); ArgumentCaptor<CreateTagsRequest> arg2 = ArgumentCaptor .forClass(CreateTagsRequest.class); verify(ec2).createTags(arg2.capture()); CreateTagsRequest ctr = arg2.getValue(); for (Tag t : ctr.getTags()) { if (t.getKey().equalsIgnoreCase("Name")) { assertEquals("name1", t.getValue()); } else if (t.getKey().equalsIgnoreCase("SubscriptionId")) { assertEquals("subId", t.getValue()); } else if (t.getKey().equalsIgnoreCase("OrganizationId")) { assertEquals("orgId", t.getValue()); } } parameters.put("USERDATA_URL", new Setting("USERDATA_URL", "userdata")); }
Example #20
Source File: EC2CommunicationTest.java From development with Apache License 2.0 | 5 votes |
@Test public void testCreateInstanceUserData() throws Exception { String userData = "line1\nline2\n"; String userDataBase64 = Base64.encodeBase64String(userData.getBytes()); File myFile = createUserDataFile(userData); try { URL fileUrl = myFile.toURI().toURL(); parameters.put(PropertyHandler.USERDATA_URL, new Setting( PropertyHandler.USERDATA_URL, fileUrl.toString())); ec2mock.createRunInstancesResult("instance2"); ec2mock.createDescribeImagesResult("image1"); ec2mock.createDescribeSubnetsResult("subnet-a77430d0"); ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0", "security_group1,security_group2"); ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4"); Image image = ec2comm.resolveAMI("image1"); ec2comm.createInstance(image); String result = ph.getAWSInstanceId(); assertEquals("instance2", result); ArgumentCaptor<RunInstancesRequest> arg1 = ArgumentCaptor .forClass(RunInstancesRequest.class); verify(ec2).runInstances(arg1.capture()); RunInstancesRequest rir = arg1.getValue(); assertEquals(userDataBase64, rir.getUserData()); } finally { myFile.delete(); } }
Example #21
Source File: ExceptionHandleAwsClientWrapper.java From primecloud-controller with GNU General Public License v2.0 | 5 votes |
protected AutoException handleException(AmazonClientException exception, Method method, Object[] args) { Object request = null; if (method.getParameterTypes().length > 0) { request = args[0]; } // UserDataにはパスワードが含まれているためマスクする if (request instanceof RunInstancesRequest) { ((RunInstancesRequest) request).setUserData(null); } String str = StringUtils.reflectToString(request); return new AutoException("EAWS-000001", exception, method.getName(), str); }
Example #22
Source File: EC2CommunicationTest.java From development with Apache License 2.0 | 5 votes |
@Test public void testCreateInstanceSecurityGroups() throws Exception { parameters.put(PropertyHandler.SECURITY_GROUP_NAMES, new Setting( PropertyHandler.SECURITY_GROUP_NAMES, "security_group")); ec2mock.createRunInstancesResult("instance3"); ec2mock.createDescribeImagesResult("image1"); ec2mock.createDescribeSubnetsResult("subnet-a77430d0"); ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0", "security_group"); ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4"); Image image = ec2comm.resolveAMI("image1"); ec2comm.createInstance(image); String result = ph.getAWSInstanceId(); assertEquals("instance3", result); ArgumentCaptor<RunInstancesRequest> arg1 = ArgumentCaptor .forClass(RunInstancesRequest.class); verify(ec2).runInstances(arg1.capture()); RunInstancesRequest rir = arg1.getValue(); // Network interfaces and an instance-level security groups may not be // specified on the same request.. assertEquals(1, rir.getNetworkInterfaces().get(0).getGroups().size()); /* * assertEquals("security_group", * rir.getNetworkInterfaces().get(0).getGroups().get(0)); */ }
Example #23
Source File: EC2Impl.java From aws-sdk-java-resources with Apache License 2.0 | 4 votes |
@Override public List<Instance> createInstances(RunInstancesRequest request) { return createInstances(request, null); }
Example #24
Source File: EC2Application.java From tutorials with MIT License | 4 votes |
public static void main(String[] args) { // Set up the client AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .withRegion(Regions.US_EAST_1) .build(); // Create a security group CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup") .withDescription("Baeldung Security Group"); ec2Client.createSecurityGroup(createSecurityGroupRequest); // Allow HTTP and SSH traffic IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0"); IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 })) .withIpProtocol("tcp") .withFromPort(80) .withToPort(80); IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 })) .withIpProtocol("tcp") .withFromPort(22) .withToPort(22); AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest() .withGroupName("BaeldungSecurityGroup") .withIpPermissions(ipPermission1, ipPermission2); ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); // Create KeyPair CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest() .withKeyName("baeldung-key-pair"); CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest); String privateKey = createKeyPairResult .getKeyPair() .getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key // See what key-pairs you've got DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest(); DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest); // Launch an Amazon Instance RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html .withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html .withMinCount(1) .withMaxCount(1) .withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance .withSecurityGroups("BaeldungSecurityGroup"); String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId(); // Start an Instance StartInstancesRequest startInstancesRequest = new StartInstancesRequest() .withInstanceIds(yourInstanceId); ec2Client.startInstances(startInstancesRequest); // Monitor Instances MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest() .withInstanceIds(yourInstanceId); ec2Client.monitorInstances(monitorInstancesRequest); UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest() .withInstanceIds(yourInstanceId); ec2Client.unmonitorInstances(unmonitorInstancesRequest); // Reboot an Instance RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest() .withInstanceIds(yourInstanceId); ec2Client.rebootInstances(rebootInstancesRequest); // Stop an Instance StopInstancesRequest stopInstancesRequest = new StopInstancesRequest() .withInstanceIds(yourInstanceId); ec2Client.stopInstances(stopInstancesRequest) .getStoppingInstances() .get(0) .getPreviousState() .getName(); // Describe an Instance DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest); System.out.println(response.getReservations() .get(0) .getInstances() .get(0) .getKernelId()); }
Example #25
Source File: Ec2Util.java From s3-bucket-loader with Apache License 2.0 | 4 votes |
public List<Instance> launchEc2Instances(AmazonEC2Client ec2Client, Properties props) throws Exception { Integer totalExpectedWorkers = Integer.valueOf(props.getProperty("master.workers.total")); // disk size Collection<BlockDeviceMapping> blockDevices = new ArrayList<BlockDeviceMapping>(); blockDevices.add( new BlockDeviceMapping() .withDeviceName(props.getProperty("master.workers.ec2.disk.deviceName")) .withEbs(new EbsBlockDevice() .withVolumeType(VolumeType.valueOf(props.getProperty("master.workers.ec2.disk.volumeType"))) .withDeleteOnTermination(true) .withVolumeSize(Integer.valueOf(props.getProperty("master.workers.ec2.disk.size.gigabytes"))))); // create our run request for the total workers we expect RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); runInstancesRequest.withImageId(props.getProperty("master.workers.ec2.ami.id")) .withInstanceType(props.getProperty("master.workers.ec2.instanceType")) .withMinCount(totalExpectedWorkers) .withMaxCount(totalExpectedWorkers) .withBlockDeviceMappings(blockDevices) .withKeyName(props.getProperty("master.workers.ec2.keyName")) .withSecurityGroupIds(props.getProperty("master.workers.ec2.securityGroupId")) .withInstanceInitiatedShutdownBehavior(ShutdownBehavior.valueOf(props.getProperty("master.workers.ec2.shutdownBehavior"))) .withSubnetId(props.getProperty("master.workers.ec2.subnetId")) .withUserData(Base64.encodeAsString(readFile(props.getProperty("master.workers.ec2.userDataFile")).getBytes())); // launch logger.debug("Launching " + totalExpectedWorkers + " EC2 instances, " + "it may take few minutes for workers to come up...: \n" + "\tamiId:" + runInstancesRequest.getImageId() +"\n"+ "\tsecGrpId:" + runInstancesRequest.getSecurityGroupIds().get(0) +"\n"+ "\tsubnetId:" + runInstancesRequest.getSubnetId() +"\n"+ "\tinstanceType:" + runInstancesRequest.getInstanceType() +"\n"+ "\tshutdownBehavior:" + runInstancesRequest.getInstanceInitiatedShutdownBehavior() +"\n"+ "\tkeyName:" + runInstancesRequest.getKeyName() ); // as the instances come up, assuming the "userData" above launches the worker we will be good // they will auto register w/ us the master RunInstancesResult result = ec2Client.runInstances(runInstancesRequest); Reservation reservation = result.getReservation(); return reservation.getInstances(); }
Example #26
Source File: V1Ec2MarshallerBenchmark.java From aws-sdk-java-v2 with Apache License 2.0 | 4 votes |
public RunInstancesRequest getReq() { return req; }
Example #27
Source File: V1Ec2MarshallerBenchmark.java From aws-sdk-java-v2 with Apache License 2.0 | 4 votes |
public RunInstancesRequest getValue() { return request; }
Example #28
Source File: MockAmazonEc2Client.java From SeleniumGridScaler with GNU General Public License v2.0 | 4 votes |
public RunInstancesRequest getRunInstancesRequest() { return runInstancesRequest; }
Example #29
Source File: AwsVmManager.java From SeleniumGridScaler with GNU General Public License v2.0 | 4 votes |
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"); } log.info("Setting image id: " + runRequest.getImageId()); log.info("Setting instance type: " + runRequest.getInstanceType()); 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; }
Example #30
Source File: SubnetImpl.java From aws-sdk-java-resources with Apache License 2.0 | 4 votes |
@Override public List<Instance> createInstances(RunInstancesRequest request) { return createInstances(request, null); }