Search in sources :

Example 6 with RunInstancesRequest

use of software.amazon.awssdk.services.ec2.model.RunInstancesRequest in project aws-doc-sdk-examples by awsdocs.

the class CreateInstance method createEC2Instance.

// snippet-start:[ec2.java2.create_instance.main]
public static String createEC2Instance(Ec2Client ec2, String name, String amiId) {
    RunInstancesRequest runRequest = RunInstancesRequest.builder().imageId(amiId).instanceType(InstanceType.T1_MICRO).maxCount(1).minCount(1).build();
    RunInstancesResponse response = ec2.runInstances(runRequest);
    String instanceId = response.instances().get(0).instanceId();
    Tag tag = Tag.builder().key("Name").value(name).build();
    CreateTagsRequest tagRequest = CreateTagsRequest.builder().resources(instanceId).tags(tag).build();
    try {
        ec2.createTags(tagRequest);
        System.out.printf("Successfully started EC2 Instance %s based on AMI %s", instanceId, amiId);
        return instanceId;
    } catch (Ec2Exception e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
    return "";
}
Also used : RunInstancesResponse(software.amazon.awssdk.services.ec2.model.RunInstancesResponse) CreateTagsRequest(software.amazon.awssdk.services.ec2.model.CreateTagsRequest) Ec2Exception(software.amazon.awssdk.services.ec2.model.Ec2Exception) RunInstancesRequest(software.amazon.awssdk.services.ec2.model.RunInstancesRequest) Tag(software.amazon.awssdk.services.ec2.model.Tag)

Example 7 with RunInstancesRequest

use of software.amazon.awssdk.services.ec2.model.RunInstancesRequest in project druid by druid-io.

the class EC2AutoScaler method provision.

@Override
public AutoScalingData provision() {
    try {
        final EC2NodeData workerConfig = envConfig.getNodeData();
        final String userDataBase64;
        if (envConfig.getUserData() == null) {
            userDataBase64 = null;
        } else {
            if (config.getWorkerVersion() == null) {
                userDataBase64 = envConfig.getUserData().getUserDataBase64();
            } else {
                userDataBase64 = envConfig.getUserData().withVersion(config.getWorkerVersion()).getUserDataBase64();
            }
        }
        RunInstancesRequest request = new RunInstancesRequest(workerConfig.getAmiId(), workerConfig.getMinInstances(), workerConfig.getMaxInstances()).withInstanceType(workerConfig.getInstanceType()).withPlacement(new Placement(envConfig.getAvailabilityZone())).withKeyName(workerConfig.getKeyName()).withIamInstanceProfile(workerConfig.getIamProfile() == null ? null : workerConfig.getIamProfile().toIamInstanceProfileSpecification()).withUserData(userDataBase64);
        // leaving it null uses the EC2 default.
        if (workerConfig.getAssociatePublicIpAddress() != null) {
            request.withNetworkInterfaces(new InstanceNetworkInterfaceSpecification().withAssociatePublicIpAddress(workerConfig.getAssociatePublicIpAddress()).withSubnetId(workerConfig.getSubnetId()).withGroups(workerConfig.getSecurityGroupIds()).withDeviceIndex(0));
        } else {
            request.withSecurityGroupIds(workerConfig.getSecurityGroupIds()).withSubnetId(workerConfig.getSubnetId());
        }
        final RunInstancesResult result = amazonEC2Client.runInstances(request);
        final List<String> instanceIds = Lists.transform(result.getReservation().getInstances(), new Function<Instance, String>() {

            @Override
            public String apply(Instance input) {
                return input.getInstanceId();
            }
        });
        log.info("Created instances: %s", instanceIds);
        return new AutoScalingData(Lists.transform(result.getReservation().getInstances(), new Function<Instance, String>() {

            @Override
            public String apply(Instance input) {
                return input.getInstanceId();
            }
        }));
    } catch (Exception e) {
        log.error(e, "Unable to provision any EC2 instances.");
    }
    return null;
}
Also used : AutoScalingData(io.druid.indexing.overlord.autoscaling.AutoScalingData) Instance(com.amazonaws.services.ec2.model.Instance) InstanceNetworkInterfaceSpecification(com.amazonaws.services.ec2.model.InstanceNetworkInterfaceSpecification) Function(com.google.common.base.Function) Placement(com.amazonaws.services.ec2.model.Placement) RunInstancesResult(com.amazonaws.services.ec2.model.RunInstancesResult) RunInstancesRequest(com.amazonaws.services.ec2.model.RunInstancesRequest)

Example 8 with RunInstancesRequest

use of software.amazon.awssdk.services.ec2.model.RunInstancesRequest in project GNS by MobilityFirst.

the class AWSEC2 method createInstanceAndWait.

/**
   * Create an Instance
   *
   * @param ec2
   * @param amiRecord
   * @param key
   * @param securityGroup
   * @return the instanceID string
   */
public static String createInstanceAndWait(AmazonEC2 ec2, AMIRecord amiRecord, String key, SecurityGroup securityGroup) {
    RunInstancesRequest runInstancesRequest;
    if (amiRecord.getVpcSubnet() != null) {
        System.out.println("subnet: " + amiRecord.getVpcSubnet() + " securityGroup: " + securityGroup.getGroupName());
        // new VPC
        runInstancesRequest = new RunInstancesRequest().withMinCount(1).withMaxCount(1).withImageId(amiRecord.getName()).withInstanceType(amiRecord.getInstanceType()).withKeyName(key).withSubnetId(amiRecord.getVpcSubnet()).withSecurityGroupIds(Arrays.asList(securityGroup.getGroupId()));
    } else {
        runInstancesRequest = new RunInstancesRequest(amiRecord.getName(), 1, 1);
        runInstancesRequest.setInstanceType(amiRecord.getInstanceType());
        runInstancesRequest.setSecurityGroups(new ArrayList<>(Arrays.asList(securityGroup.getGroupName())));
        runInstancesRequest.setKeyName(key);
    }
    RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest);
    Instance instance = runInstancesResult.getReservation().getInstances().get(0);
    String createdInstanceId = instance.getInstanceId();
    System.out.println("Waiting for instance " + amiRecord.getName() + " to start");
    long startTime = System.currentTimeMillis();
    do {
        ThreadUtils.sleep(1000);
        if (System.currentTimeMillis() - startTime > 90000) {
            // give it a minute and a half
            System.out.println(createdInstanceId + " timed out waiting for start.");
            return null;
        }
        // regrab the instance data from the server
        instance = findInstance(ec2, createdInstanceId);
        //System.out.print(instance.getState().getName());
        System.out.print(".");
    } while (instance != null && !instance.getState().getName().equals(InstanceStateRecord.RUNNING.getName()));
    System.out.println();
    return createdInstanceId;
}
Also used : Instance(com.amazonaws.services.ec2.model.Instance) RunInstancesResult(com.amazonaws.services.ec2.model.RunInstancesResult) RunInstancesRequest(com.amazonaws.services.ec2.model.RunInstancesRequest)

Example 9 with RunInstancesRequest

use of software.amazon.awssdk.services.ec2.model.RunInstancesRequest in project camel by apache.

the class EC2Producer method createAndRunInstance.

private void createAndRunInstance(AmazonEC2Client ec2Client, Exchange exchange) {
    String ami;
    InstanceType instanceType;
    int minCount;
    int maxCount;
    boolean monitoring;
    String kernelId;
    boolean ebsOptimized;
    Collection securityGroups;
    String keyName;
    String clientToken;
    Placement placement;
    RunInstancesRequest request = new RunInstancesRequest();
    if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.IMAGE_ID))) {
        ami = exchange.getIn().getHeader(EC2Constants.IMAGE_ID, String.class);
        request.withImageId(ami);
    } else {
        throw new IllegalArgumentException("AMI must be specified");
    }
    if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCE_TYPE))) {
        instanceType = exchange.getIn().getHeader(EC2Constants.INSTANCE_TYPE, InstanceType.class);
        request.withInstanceType(instanceType.toString());
    } else {
        throw new IllegalArgumentException("Instance Type must be specified");
    }
    if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCE_MIN_COUNT))) {
        minCount = exchange.getIn().getHeader(EC2Constants.INSTANCE_MIN_COUNT, Integer.class);
        request.withMinCount(minCount);
    } else {
        throw new IllegalArgumentException("Min instances count must be specified");
    }
    if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCE_MAX_COUNT))) {
        maxCount = exchange.getIn().getHeader(EC2Constants.INSTANCE_MAX_COUNT, Integer.class);
        request.withMaxCount(maxCount);
    } else {
        throw new IllegalArgumentException("Max instances count must be specified");
    }
    if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCE_MONITORING))) {
        monitoring = exchange.getIn().getHeader(EC2Constants.INSTANCE_MONITORING, Boolean.class);
        request.withMonitoring(monitoring);
    }
    if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCE_KERNEL_ID))) {
        kernelId = exchange.getIn().getHeader(EC2Constants.INSTANCE_KERNEL_ID, String.class);
        request.withKernelId(kernelId);
    }
    if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCE_EBS_OPTIMIZED))) {
        ebsOptimized = exchange.getIn().getHeader(EC2Constants.INSTANCE_EBS_OPTIMIZED, Boolean.class);
        request.withEbsOptimized(ebsOptimized);
    }
    if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCE_SECURITY_GROUPS))) {
        securityGroups = exchange.getIn().getHeader(EC2Constants.INSTANCE_SECURITY_GROUPS, Collection.class);
        request.withSecurityGroups(securityGroups);
    }
    if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCES_KEY_PAIR))) {
        keyName = exchange.getIn().getHeader(EC2Constants.INSTANCES_KEY_PAIR, String.class);
        request.withKeyName(keyName);
    }
    if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCES_CLIENT_TOKEN))) {
        clientToken = exchange.getIn().getHeader(EC2Constants.INSTANCES_CLIENT_TOKEN, String.class);
        request.withClientToken(clientToken);
    }
    if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCES_PLACEMENT))) {
        placement = exchange.getIn().getHeader(EC2Constants.INSTANCES_PLACEMENT, Placement.class);
        request.withPlacement(placement);
    }
    RunInstancesResult result;
    try {
        result = ec2Client.runInstances(request);
    } catch (AmazonServiceException ase) {
        LOG.trace("Run Instances command returned the error code {}", ase.getErrorCode());
        throw ase;
    }
    LOG.trace("Creating and running instances with ami [{}] and instance type {}", ami, instanceType.toString());
    Message message = getMessageForResponse(exchange);
    message.setBody(result);
}
Also used : Message(org.apache.camel.Message) Endpoint(org.apache.camel.Endpoint) Placement(com.amazonaws.services.ec2.model.Placement) RunInstancesResult(com.amazonaws.services.ec2.model.RunInstancesResult) AmazonServiceException(com.amazonaws.AmazonServiceException) Collection(java.util.Collection) RunInstancesRequest(com.amazonaws.services.ec2.model.RunInstancesRequest) InstanceType(com.amazonaws.services.ec2.model.InstanceType)

Example 10 with RunInstancesRequest

use of software.amazon.awssdk.services.ec2.model.RunInstancesRequest in project photon-model by vmware.

the class TestAWSSetupUtils method provisionAWSVMWithEC2Client.

/**
 * Method to directly provision instances on the AWS endpoint without the knowledge of the local
 * system. This is used to spawn instances and to test that the discovery of items not
 * provisioned by Xenon happens correctly.
 *
 * @throws Throwable
 */
public static List<String> provisionAWSVMWithEC2Client(AmazonEC2AsyncClient client, VerificationHost host, int numberOfInstance, String instanceType, String subnetId, String securityGroupId) throws Throwable {
    host.log("Provisioning %d instances on the AWS endpoint using the EC2 client.", numberOfInstance);
    RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withSubnetId(subnetId).withImageId(EC2_LINUX_AMI).withInstanceType(instanceType).withMinCount(numberOfInstance).withMaxCount(numberOfInstance).withSecurityGroupIds(securityGroupId);
    // handler invoked once the EC2 runInstancesAsync commands completes
    AWSRunInstancesAsyncHandler creationHandler = new AWSRunInstancesAsyncHandler(host);
    client.runInstancesAsync(runInstancesRequest, creationHandler);
    host.waitFor("Waiting for instanceIds to be returned from AWS", () -> {
        return checkInstanceIdsReturnedFromAWS(numberOfInstance, creationHandler.instanceIds);
    });
    return creationHandler.instanceIds;
}
Also used : RunInstancesRequest(com.amazonaws.services.ec2.model.RunInstancesRequest)

Aggregations

RunInstancesRequest (com.amazonaws.services.ec2.model.RunInstancesRequest)12 RunInstancesResult (com.amazonaws.services.ec2.model.RunInstancesResult)10 Instance (com.amazonaws.services.ec2.model.Instance)5 Placement (com.amazonaws.services.ec2.model.Placement)4 AmazonEC2Exception (com.amazonaws.services.ec2.model.AmazonEC2Exception)3 ArrayList (java.util.ArrayList)3 AmazonServiceException (com.amazonaws.AmazonServiceException)2 AmazonEC2 (com.amazonaws.services.ec2.AmazonEC2)2 InstanceNetworkInterfaceSpecification (com.amazonaws.services.ec2.model.InstanceNetworkInterfaceSpecification)2 Function (com.google.common.base.Function)2 UnknownHostException (java.net.UnknownHostException)2 TimeoutException (java.util.concurrent.TimeoutException)2 AWSStaticCredentialsProvider (com.amazonaws.auth.AWSStaticCredentialsProvider)1 AuthorizeSecurityGroupIngressRequest (com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest)1 BlockDeviceMapping (com.amazonaws.services.ec2.model.BlockDeviceMapping)1 CreateKeyPairRequest (com.amazonaws.services.ec2.model.CreateKeyPairRequest)1 CreateKeyPairResult (com.amazonaws.services.ec2.model.CreateKeyPairResult)1 CreateSecurityGroupRequest (com.amazonaws.services.ec2.model.CreateSecurityGroupRequest)1 CreateTagsRequest (com.amazonaws.services.ec2.model.CreateTagsRequest)1 CreateTagsResult (com.amazonaws.services.ec2.model.CreateTagsResult)1