Java Code Examples for com.amazonaws.services.ec2.AmazonEC2#terminateInstances()

The following examples show how to use com.amazonaws.services.ec2.AmazonEC2#terminateInstances() . 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: EC2Api.java    From ec2-spot-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Auto handle instance not found exception if any and assume those instances as already terminated
 *
 * @param ec2
 * @param instanceIds
 */
public void terminateInstances(final AmazonEC2 ec2, final Set<String> instanceIds) {
    final List<String> temp = new ArrayList<>(instanceIds);
    while (temp.size() > 0) {
        // terminateInstances is idempotent so it can be called until it's successful
        try {
            ec2.terminateInstances(new TerminateInstancesRequest(temp));
            // clear as removed so we can finish
            temp.clear();
        } catch (AmazonEC2Exception exception) {
            // if we cannot find instance, that's fine assume them as terminated
            // remove from request and try again
            if (exception.getErrorCode().equals(NOT_FOUND_ERROR_CODE)) {
                final List<String> notFoundInstanceIds = parseInstanceIdsFromNotFoundException(exception.getMessage());
                if (notFoundInstanceIds.isEmpty()) {
                    // looks like we cannot parse correctly, rethrow
                    throw exception;
                }
                temp.removeAll(notFoundInstanceIds);
            }
        }
    }
}
 
Example 2
Source File: Ec2IaasHandler.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void terminateMachine( TargetHandlerParameters parameters, String machineId ) throws TargetException {

	this.logger.fine( "Terminating machine '" + machineId + "'." );
	cancelMachineConfigurator( machineId );
	try {
		AmazonEC2 ec2 = createEc2Client( parameters.getTargetProperties());
		TerminateInstancesRequest terminateInstancesRequest = new TerminateInstancesRequest();
		terminateInstancesRequest.withInstanceIds( machineId );
		ec2.terminateInstances( terminateInstancesRequest );

	} catch( Exception e ) {
		this.logger.severe( "An error occurred while terminating a machine on Amazon EC2. " + e.getMessage());
		throw new TargetException( e );
	}
}