Search in sources :

Example 11 with StartInstancesRequest

use of com.amazonaws.services.ec2.model.StartInstancesRequest in project aws-doc-sdk-examples by awsdocs.

the class StartStopInstance method startInstance.

// snippet-start:[ec2.java2.start_stop_instance.start]
public static void startInstance(Ec2Client ec2, String instanceId) {
    StartInstancesRequest request = StartInstancesRequest.builder().instanceIds(instanceId).build();
    ec2.startInstances(request);
    System.out.printf("Successfully started instance %s", instanceId);
}
Also used : StartInstancesRequest(software.amazon.awssdk.services.ec2.model.StartInstancesRequest)

Example 12 with StartInstancesRequest

use of com.amazonaws.services.ec2.model.StartInstancesRequest in project tutorials by eugenp.

the class EC2Application method main.

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();
    // See what key-pairs you've got
    DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
    DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest);
    // Launch an Amazon Instance
    RunInstancesRequest runInstancesRequest = // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html
    new RunInstancesRequest().withImageId("ami-97785bed").withInstanceType(// https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
    "t2.micro").withMinCount(1).withMaxCount(1).withKeyName(// optional - if not present, can't connect to instance
    "baeldung-key-pair").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());
}
Also used : IpRange(com.amazonaws.services.ec2.model.IpRange) DescribeKeyPairsRequest(com.amazonaws.services.ec2.model.DescribeKeyPairsRequest) StartInstancesRequest(com.amazonaws.services.ec2.model.StartInstancesRequest) DescribeKeyPairsResult(com.amazonaws.services.ec2.model.DescribeKeyPairsResult) AmazonEC2(com.amazonaws.services.ec2.AmazonEC2) DescribeInstancesRequest(com.amazonaws.services.ec2.model.DescribeInstancesRequest) CreateSecurityGroupRequest(com.amazonaws.services.ec2.model.CreateSecurityGroupRequest) CreateKeyPairRequest(com.amazonaws.services.ec2.model.CreateKeyPairRequest) MonitorInstancesRequest(com.amazonaws.services.ec2.model.MonitorInstancesRequest) RebootInstancesRequest(com.amazonaws.services.ec2.model.RebootInstancesRequest) DescribeInstancesResult(com.amazonaws.services.ec2.model.DescribeInstancesResult) AWSStaticCredentialsProvider(com.amazonaws.auth.AWSStaticCredentialsProvider) CreateKeyPairResult(com.amazonaws.services.ec2.model.CreateKeyPairResult) AuthorizeSecurityGroupIngressRequest(com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest) StopInstancesRequest(com.amazonaws.services.ec2.model.StopInstancesRequest) IpPermission(com.amazonaws.services.ec2.model.IpPermission) RunInstancesRequest(com.amazonaws.services.ec2.model.RunInstancesRequest) UnmonitorInstancesRequest(com.amazonaws.services.ec2.model.UnmonitorInstancesRequest)

Example 13 with StartInstancesRequest

use of com.amazonaws.services.ec2.model.StartInstancesRequest in project cloudbreak by hortonworks.

the class AwsInstanceConnector method start.

@Override
public List<CloudVmInstanceStatus> start(AuthenticatedContext ac, List<CloudResource> resources, List<CloudInstance> vms) {
    List<CloudVmInstanceStatus> statuses = new ArrayList<>();
    AmazonEC2Client amazonEC2Client = awsClient.createAccess(new AwsCredentialView(ac.getCloudCredential()), ac.getCloudContext().getLocation().getRegion().value());
    for (String group : getGroups(vms)) {
        Collection<String> instances = new ArrayList<>();
        Collection<CloudInstance> cloudInstances = new ArrayList<>();
        for (CloudInstance vm : vms) {
            if (vm.getTemplate().getGroupName().equals(group)) {
                instances.add(vm.getInstanceId());
                cloudInstances.add(vm);
            }
        }
        try {
            instances = removeInstanceIdsWhichAreNotInCorrectState(instances, amazonEC2Client, "Running");
            if (!instances.isEmpty()) {
                amazonEC2Client.startInstances(new StartInstancesRequest().withInstanceIds(instances));
            }
            for (CloudInstance cloudInstance : cloudInstances) {
                statuses.add(new CloudVmInstanceStatus(cloudInstance, InstanceStatus.IN_PROGRESS));
            }
        } catch (RuntimeException e) {
            LOGGER.error("Start instances failed on AWS", e);
            String message = e instanceof AmazonEC2Exception ? ((AmazonEC2Exception) e).getErrorCode() : e.getMessage();
            for (CloudInstance cloudInstance : cloudInstances) {
                statuses.add(new CloudVmInstanceStatus(cloudInstance, InstanceStatus.FAILED, message));
            }
        }
    }
    return statuses;
}
Also used : AmazonEC2Client(com.amazonaws.services.ec2.AmazonEC2Client) AwsCredentialView(com.sequenceiq.cloudbreak.cloud.aws.view.AwsCredentialView) StartInstancesRequest(com.amazonaws.services.ec2.model.StartInstancesRequest) CloudVmInstanceStatus(com.sequenceiq.cloudbreak.cloud.model.CloudVmInstanceStatus) ArrayList(java.util.ArrayList) CloudInstance(com.sequenceiq.cloudbreak.cloud.model.CloudInstance) AmazonEC2Exception(com.amazonaws.services.ec2.model.AmazonEC2Exception)

Example 14 with StartInstancesRequest

use of com.amazonaws.services.ec2.model.StartInstancesRequest in project onebusaway-application-modules by camsys.

the class BundleServerServiceImpl method start.

@Override
public String start(String instanceId) {
    if (!_isAws) {
        return LOCAL_HOST;
    }
    if (LOCAL_HOST.equalsIgnoreCase(instanceId)) {
        return instanceId;
    }
    List<String> instances = new ArrayList<String>();
    instances.add(instanceId);
    StartInstancesRequest startInstancesRequest = new StartInstancesRequest(instances);
    StartInstancesResult startInstancesResult = _ec2.startInstances(startInstancesRequest);
    InstanceStateChange change = null;
    if (!startInstancesResult.getStartingInstances().isEmpty()) {
        change = startInstancesResult.getStartingInstances().get(0);
        _log.info("from state=" + change.getPreviousState() + " to state=" + change.getCurrentState());
        return change.getInstanceId();
    }
    return null;
}
Also used : StartInstancesResult(com.amazonaws.services.ec2.model.StartInstancesResult) StartInstancesRequest(com.amazonaws.services.ec2.model.StartInstancesRequest) ArrayList(java.util.ArrayList) InstanceStateChange(com.amazonaws.services.ec2.model.InstanceStateChange)

Example 15 with StartInstancesRequest

use of com.amazonaws.services.ec2.model.StartInstancesRequest in project cloudbreak by hortonworks.

the class AwsNativeInstanceResourceBuilder method build.

@Override
public List<CloudResource> build(AwsContext context, CloudInstance cloudInstance, long privateId, AuthenticatedContext ac, Group group, List<CloudResource> buildableResource, CloudStack cloudStack) throws Exception {
    if (buildableResource.isEmpty()) {
        throw new CloudConnectorException("Buildable resources cannot be empty!");
    }
    AmazonEc2Client amazonEc2Client = context.getAmazonEc2Client();
    InstanceTemplate instanceTemplate = group.getReferenceInstanceTemplate();
    AwsCloudStackView awsCloudStackView = new AwsCloudStackView(cloudStack);
    CloudResource cloudResource = buildableResource.get(0);
    Optional<Instance> existedOpt = resourceByName(amazonEc2Client, cloudResource.getName());
    Instance instance;
    if (existedOpt.isPresent() && existedOpt.get().getState().getCode() != AWS_INSTANCE_TERMINATED_CODE) {
        instance = existedOpt.get();
        LOGGER.info("Instance exists with name: {} ({}), check the state: {}", cloudResource.getName(), instance.getInstanceId(), instance.getState().getName());
        if (!instanceRunning(instance)) {
            LOGGER.info("Instance is existing but not running, try to start: {}, {}", instance.getInstanceId(), instance.getState());
            amazonEc2Client.startInstances(new StartInstancesRequest().withInstanceIds(instance.getInstanceId()));
        }
    } else {
        LOGGER.info("Create new instance with name: {}", cloudResource.getName());
        TagSpecification tagSpecification = awsTaggingService.prepareEc2TagSpecification(awsCloudStackView.getTags(), com.amazonaws.services.ec2.model.ResourceType.Instance);
        String securityGroupId = getSecurityGroupId(context, group);
        tagSpecification.withTags(new Tag().withKey("Name").withValue(cloudResource.getName()));
        RunInstancesRequest request = new RunInstancesRequest().withInstanceType(instanceTemplate.getFlavor()).withImageId(cloudStack.getImage().getImageName()).withSubnetId(cloudInstance.getSubnetId()).withSecurityGroupIds(singletonList(securityGroupId)).withEbsOptimized(isEbsOptimized(instanceTemplate)).withTagSpecifications(tagSpecification).withIamInstanceProfile(getIamInstanceProfile(group)).withUserData(getUserData(cloudStack, group)).withMinCount(1).withMaxCount(1).withBlockDeviceMappings(blocks(group, cloudStack, ac)).withKeyName(cloudStack.getInstanceAuthentication().getPublicKeyId());
        RunInstancesResult instanceResult = amazonEc2Client.createInstance(request);
        instance = instanceResult.getReservation().getInstances().get(0);
        LOGGER.info("Instance creation inited with name: {} and instance id: {}", cloudResource.getName(), instance.getInstanceId());
    }
    cloudResource.setInstanceId(instance.getInstanceId());
    return buildableResource;
}
Also used : CloudConnectorException(com.sequenceiq.cloudbreak.cloud.exception.CloudConnectorException) CloudInstance(com.sequenceiq.cloudbreak.cloud.model.CloudInstance) Instance(com.amazonaws.services.ec2.model.Instance) StartInstancesRequest(com.amazonaws.services.ec2.model.StartInstancesRequest) TagSpecification(com.amazonaws.services.ec2.model.TagSpecification) AwsCloudStackView(com.sequenceiq.cloudbreak.cloud.aws.view.AwsCloudStackView) RunInstancesResult(com.amazonaws.services.ec2.model.RunInstancesResult) AmazonEc2Client(com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonEc2Client) CloudResource(com.sequenceiq.cloudbreak.cloud.model.CloudResource) Tag(com.amazonaws.services.ec2.model.Tag) RunInstancesRequest(com.amazonaws.services.ec2.model.RunInstancesRequest) InstanceTemplate(com.sequenceiq.cloudbreak.cloud.model.InstanceTemplate)

Aggregations

StartInstancesRequest (com.amazonaws.services.ec2.model.StartInstancesRequest)14 StartInstancesResult (com.amazonaws.services.ec2.model.StartInstancesResult)7 StopInstancesRequest (com.amazonaws.services.ec2.model.StopInstancesRequest)6 AmazonEC2 (com.amazonaws.services.ec2.AmazonEC2)4 StopInstancesResult (com.amazonaws.services.ec2.model.StopInstancesResult)4 ArrayList (java.util.ArrayList)4 AmazonEC2AsyncClient (com.amazonaws.services.ec2.AmazonEC2AsyncClient)3 DescribeInstancesRequest (com.amazonaws.services.ec2.model.DescribeInstancesRequest)3 InstanceStateChange (com.amazonaws.services.ec2.model.InstanceStateChange)3 AWSClientManager (com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManager)3 AWSClientManagerFactory (com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManagerFactory)3 BaseAdapterStage (com.vmware.photon.controller.model.adapters.util.BaseAdapterContext.BaseAdapterStage)3 DefaultAdapterContext (com.vmware.photon.controller.model.adapters.util.BaseAdapterContext.DefaultAdapterContext)3 ComputeState (com.vmware.photon.controller.model.resources.ComputeService.ComputeState)3 Operation (com.vmware.xenon.common.Operation)3 StatelessService (com.vmware.xenon.common.StatelessService)3 AmazonServiceException (com.amazonaws.AmazonServiceException)2 DescribeInstancesResult (com.amazonaws.services.ec2.model.DescribeInstancesResult)2 Instance (com.amazonaws.services.ec2.model.Instance)2 RunInstancesRequest (com.amazonaws.services.ec2.model.RunInstancesRequest)2