com.amazonaws.services.ec2.AmazonEC2 Java Examples

The following examples show how to use com.amazonaws.services.ec2.AmazonEC2. 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: EncryptedSnapshotService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private CreateVolumeRequest prepareCreateVolumeRequest(AuthenticatedContext ac, AwsInstanceView awsInstanceView, AmazonEC2 client, CloudStack cloudStack) {
    String availabilityZone = prepareDescribeAvailabilityZonesResult(ac, client);

    TagSpecification tagSpecification = new TagSpecification()
            .withResourceType(com.amazonaws.services.ec2.model.ResourceType.Volume)
            .withTags(prepareTagList(ac, cloudStack, awsInstanceView));

    CreateVolumeRequest createVolumeRequest = new CreateVolumeRequest()
            .withSize(VOLUME_SIZE)
            .withAvailabilityZone(availabilityZone)
            .withTagSpecifications(tagSpecification)
            .withEncrypted(true);
    if (awsInstanceView.isKmsEnabled()) {
        createVolumeRequest = createVolumeRequest.withKmsKeyId(awsInstanceView.getKmsKey());
    }
    return createVolumeRequest;
}
 
Example #2
Source File: UnusedElasticIPAutofix.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@Override
public FixResult executeFix(Map<String, String> issue, Map<String, Object> clientMap,
		Map<String, String> ruleParams) {

	try {
		AmazonEC2 amazonEC2 = (AmazonEC2) clientMap.get(PacmanSdkConstants.CLIENT);

		ReleaseAddressRequest request = new ReleaseAddressRequest().withAllocationId(issue.get(PacmanSdkConstants.ALLOCATION_ID));
		amazonEC2.releaseAddress(request);
		if (LOGGER.isDebugEnabled())
			LOGGER.debug(String.format(ELASTIC_IP_ALLOCATION_ID_RELEASED, issue.get(PacmanSdkConstants.RESOURCE_ID),
					issue.get(PacmanSdkConstants.ALLOCATION_ID)));
		return new FixResult(PacmanSdkConstants.STATUS_SUCCESS_CODE,
				String.format(ELASTIC_IP_ALLOCATION_ID_RELEASED, issue.get(PacmanSdkConstants.RESOURCE_ID),
						issue.get(PacmanSdkConstants.ALLOCATION_ID)));
	} catch (Exception e) {
		LOGGER.error(String.format(ELASTIC_IP_ALLOCATION_ID_RELEASE_FAILED,
				issue.get(PacmanSdkConstants.RESOURCE_ID), issue.get(PacmanSdkConstants.ALLOCATION_ID)), e.getMessage());
		return new FixResult(PacmanSdkConstants.STATUS_FAILURE_CODE,
				String.format(ELASTIC_IP_ALLOCATION_ID_RELEASE_FAILED, issue.get(PacmanSdkConstants.RESOURCE_ID),
						issue.get(PacmanSdkConstants.ALLOCATION_ID), e.getMessage()));
	}

}
 
Example #3
Source File: PublicAccessAutoFix.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Apply security groups to ec 2.
 *
 * @param amazonEC2 the amazon EC 2
 * @param sgIdToBeAttached the sg id to be attached
 * @param resourceId the resource id
 * @return true, if successful
 * @throws Exception the exception
 */
public static boolean applySecurityGroupsToEc2(AmazonEC2 amazonEC2, Set<String> sgIdToBeAttached, String resourceId) throws Exception {
    boolean applysgFlg = false;
    try {
    	ModifyInstanceAttributeRequest modifyInstanceAttributeRequest = new ModifyInstanceAttributeRequest();
    	modifyInstanceAttributeRequest.setInstanceId(resourceId);
    	modifyInstanceAttributeRequest.setGroups(sgIdToBeAttached);
    	amazonEC2.modifyInstanceAttribute(modifyInstanceAttributeRequest);
        applysgFlg = true;
    } catch (Exception e) {
        logger.error("Apply Security Group operation failed for ec2 {}" , resourceId );
     throw new Exception(e);
    }
    return applysgFlg;
}
 
Example #4
Source File: EC2Utils.java    From amazon-kinesis-connectors with Apache License 2.0 6 votes vote down vote up
/**
 * Return the DNS name of one Amazon EC2 instance with the provided filter name and value.
 * 
 * @param ec2Client
 *        an Amazon EC2 instance
 * @param filterName
 *        the name of the filter
 * @param filterValue
 *        the value of the filter
 * @return the public DNS name of an instance with the filter name and value. Null if none exist.
 */
public static String getEndpointForFirstActiveInstanceWithTag(AmazonEC2 ec2Client,
        String filterName,
        String filterValue) {
    DescribeInstancesRequest describeInstancesRequest =
            new DescribeInstancesRequest().withFilters(new Filter().withName(filterName).withValues(filterValue));
    DescribeInstancesResult describeInstancesResult = ec2Client.describeInstances(describeInstancesRequest);

    List<Reservation> reservations = describeInstancesResult.getReservations();
    for (Reservation reservation : reservations) {
        List<Instance> ec2Instances = reservation.getInstances();
        for (Instance ec2Instance : ec2Instances) {
            if (InstanceStateName.Running.toString().equals(ec2Instance.getState().getName())) {
                return ec2Instance.getPublicDnsName();
            }
        }
    }
    return null;
}
 
Example #5
Source File: ReleaseAddress.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args)
{
    final String USAGE =
        "To run this example, supply an allocation ID.\n" +
        "Ex: ReleaseAddress <allocation_id>\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String alloc_id = args[0];

    final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();

    ReleaseAddressRequest request = new ReleaseAddressRequest()
        .withAllocationId(alloc_id);

    ReleaseAddressResult response = ec2.releaseAddress(request);

    System.out.printf(
        "Successfully released elastic IP address %s", alloc_id);
}
 
Example #6
Source File: EC2InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch route tables.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<RouteTable>> fetchRouteTables(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	
	Map<String,List<RouteTable>> routeTableMap = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + InventoryConstants.ERROR_PREFIX_EC2 ;

	for(Region region : RegionUtils.getRegions()) { 
		try{
			if(!skipRegions.contains(region.getName())){ 
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				List<RouteTable> routeTableList = ec2Client.describeRouteTables().getRouteTables();
				
				if(!routeTableList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : EC2 Route table "+ region.getName()+" >> " + routeTableList.size());
					routeTableMap.put(accountId+delimiter+accountName+delimiter+region.getName(), routeTableList);
				}
		   	}
		}catch(Exception e){
	   		log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"routetable",e.getMessage());
	   	}
	}
	return routeTableMap;
}
 
Example #7
Source File: EC2InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch internet gateway.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<InternetGateway>> fetchInternetGateway(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	
	Map<String,List<InternetGateway>> internetGatewayMap = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"internetgateway\" , \"region\":\"" ;

	for(Region region : RegionUtils.getRegions()) { 
		try{
			if(!skipRegions.contains(region.getName())){ 
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				List<InternetGateway> internetGatewayList = ec2Client.describeInternetGateways().getInternetGateways();
				
				if(!internetGatewayList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : EC2 Internet Gateway "+ region.getName()+" >> " + internetGatewayList.size());
					internetGatewayMap.put(accountId+delimiter+accountName+delimiter+region.getName(), internetGatewayList);
				}
		   	}
		}catch(Exception e){
	   		log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"internetgateway",e.getMessage());
	   	}
	}
	return internetGatewayMap;
}
 
Example #8
Source File: CreateKeyPair.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args)
{
    final String USAGE =
        "To run this example, supply a key pair name\n" +
        "Ex: CreateKeyPair <key-pair-name>\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String key_name = args[0];

    final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();

    CreateKeyPairRequest request = new CreateKeyPairRequest()
        .withKeyName(key_name);

    CreateKeyPairResult response = ec2.createKeyPair(request);

    System.out.printf(
        "Successfully created key pair named %s",
        key_name);
}
 
Example #9
Source File: EC2InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch DHCP options.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<DhcpOptions>> fetchDHCPOptions(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	
	Map<String,List<DhcpOptions>> dhcpOptionsMap = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"dhcpoption\" , \"region\":\"" ;

	for(Region region : RegionUtils.getRegions()) { 
		try{
			if(!skipRegions.contains(region.getName())){ 
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				List<DhcpOptions> dhcpOptionsList = ec2Client.describeDhcpOptions().getDhcpOptions();
				
				if(!dhcpOptionsList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : EC2 DHCP Options "+ region.getName()+" >> " + dhcpOptionsList.size());
					dhcpOptionsMap.put(accountId+delimiter+accountName+delimiter+region.getName(), dhcpOptionsList);
				}
		   	}
		}catch(Exception e){
	   		log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
	   		ErrorManageUtil.uploadError(accountId,region.getName(),"dhcpoption",e.getMessage());
	   	}
	}
	return dhcpOptionsMap;
}
 
Example #10
Source File: EC2InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch peering connections.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<VpcPeeringConnection>> fetchPeeringConnections(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	
	Map<String,List<VpcPeeringConnection>> peeringConnectionMap = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"peeringconnection\" , \"region\":\"" ;

	for(Region region : RegionUtils.getRegions()) { 
		try{
			if(!skipRegions.contains(region.getName())){ 
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				List<VpcPeeringConnection> peeringConnectionList = ec2Client.describeVpcPeeringConnections().getVpcPeeringConnections();
				
				if(!peeringConnectionList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : EC2 Peering Connections "+ region.getName()+" >> " + peeringConnectionList.size());
					peeringConnectionMap.put(accountId+delimiter+accountName+delimiter+region.getName(), peeringConnectionList);
				}
		   	}
		}catch(Exception e){
	   		log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
	   		ErrorManageUtil.uploadError(accountId,region.getName(),"peeringconnection",e.getMessage());
	   	}
	}
	return peeringConnectionMap;
}
 
Example #11
Source File: EC2InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch customer gateway.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<CustomerGateway>> fetchCustomerGateway(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	
	Map<String,List<CustomerGateway>> customerGatewayMap = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"customergateway\" , \"region\":\"" ;

	for(Region region : RegionUtils.getRegions()) { 
		try{
			if(!skipRegions.contains(region.getName())){ 
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				List<CustomerGateway> customerGatewayList = ec2Client.describeCustomerGateways().getCustomerGateways();
				
				if(!customerGatewayList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : EC2 Customer Gateway "+ region.getName()+" >> " + customerGatewayList.size());
					customerGatewayMap.put(accountId+delimiter+accountName+delimiter+region.getName(), customerGatewayList);
				}
		   	}
		}catch(Exception e){
	   		log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
	   		ErrorManageUtil.uploadError(accountId,region.getName(),"customergateway",e.getMessage());
	   	}
	}
	return customerGatewayMap;
}
 
Example #12
Source File: EC2InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch VPN connections.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<VpnConnection>> fetchVPNConnections(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	
	Map<String,List<VpnConnection>> vpnConnectionMap = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"vpnconnection\" , \"region\":\"" ;

	for(Region region : RegionUtils.getRegions()) { 
		try{
			if(!skipRegions.contains(region.getName())){ 
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				List<VpnConnection> vpnConnectionsList = ec2Client.describeVpnConnections().getVpnConnections();
				if(!vpnConnectionsList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : EC2 VPN Connections"+ region.getName()+" >> " + vpnConnectionsList.size());
					vpnConnectionMap.put(accountId+delimiter+accountName+delimiter+region.getName(), vpnConnectionsList);
				}
		   	}
		}catch(Exception e){
	   		log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
	   		ErrorManageUtil.uploadError(accountId,region.getName(),"vpnconnection",e.getMessage());
	   	}
	}
	return vpnConnectionMap;
}
 
Example #13
Source File: EC2InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch reserved instances.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<ReservedInstances>> fetchReservedInstances(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	
	Map<String,List<ReservedInstances>> reservedInstancesMap = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + InventoryConstants.ERROR_PREFIX_EC2 ;

	for(Region region : RegionUtils.getRegions()) { 
		try{
			if(!skipRegions.contains(region.getName())){ 
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				List<ReservedInstances> reservedInstancesList = ec2Client.describeReservedInstances().getReservedInstances();
				if(!reservedInstancesList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : reservedinstance"+ region.getName()+" >> " + reservedInstancesList.size());
					reservedInstancesMap.put(accountId+delimiter+accountName+delimiter+region.getName(), reservedInstancesList);
				}
		   	}
		}catch(Exception e){
	   		log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
	   		ErrorManageUtil.uploadError(accountId,region.getName(),"reservedinstance",e.getMessage());
	   	}
	}
	return reservedInstancesMap;
}
 
Example #14
Source File: AwsSetup.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private void validateExistingIGW(AwsNetworkView awsNetworkView, AmazonEC2 amazonEC2Client) {
    if (awsNetworkView.isExistingIGW()) {
        DescribeInternetGatewaysRequest describeInternetGatewaysRequest = new DescribeInternetGatewaysRequest();
        describeInternetGatewaysRequest.withInternetGatewayIds(awsNetworkView.getExistingIgw());
        DescribeInternetGatewaysResult describeInternetGatewaysResult = amazonEC2Client.describeInternetGateways(describeInternetGatewaysRequest);
        if (describeInternetGatewaysResult.getInternetGateways().size() < 1) {
            throw new CloudConnectorException(String.format(IGW_DOES_NOT_EXIST_MSG, awsNetworkView.getExistingIgw()));
        } else {
            InternetGateway internetGateway = describeInternetGatewaysResult.getInternetGateways().get(0);
            InternetGatewayAttachment attachment = internetGateway.getAttachments().get(0);
            if (attachment != null && !attachment.getVpcId().equals(awsNetworkView.getExistingVpc())) {
                throw new CloudConnectorException(String.format(IGWVPC_DOES_NOT_EXIST_MSG, awsNetworkView.getExistingIgw(),
                        awsNetworkView.getExistingVpc()));
            }
        }
    }
}
 
Example #15
Source File: EC2CommunicationTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void testEC2SetupNoProxy() throws Exception {
    // Ask for connection
    AmazonEC2 client = ec2comm.getEC2();
    assertNotNull(client);
    assertNotNull(credProvider);
    assertNotNull(clientConfig);

    assertEquals(-1, clientConfig.getProxyPort());
    assertNull(clientConfig.getProxyHost());
    verify(ec2).setEndpoint("ec2.test.amazonaws.com");

    // Test again for validating cached value
    AmazonEC2 newClient = ec2comm.getEC2();
    assertTrue(client == newClient);

}
 
Example #16
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch subnets.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @param accountName the account name
 * @return the map
 */
public static Map<String,List<Subnet>> fetchSubnets(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName) {
	Map<String,List<Subnet>> subnets = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"Subnet\" , \"region\":\"" ;
	for(Region region : RegionUtils.getRegions()){
		try{
			if(!skipRegions.contains(region.getName())){
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				DescribeSubnetsResult rslt = ec2Client.describeSubnets();
				List<Subnet> subnetsTemp =rslt.getSubnets();
				if(! subnetsTemp.isEmpty() ){
					log.debug(InventoryConstants.ACCOUNT + accountId +" Type : Subnet "+region.getName() + " >> "+subnetsTemp.size());
					subnets.put(accountId+delimiter+accountName+delimiter+region.getName(),subnetsTemp);
				}

			}
		}catch(Exception e){
			log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"subnet",e.getMessage());
		}
	}

	return subnets;
}
 
Example #17
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch volumet info.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @param accountName the account name
 * @return the map
 */
public static Map<String,List<Volume>> fetchVolumetInfo(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName) {
	Map<String,List<Volume>> volumeList = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"Volume\" , \"region\":\"" ;
	for(Region region : RegionUtils.getRegions()){
		try{
			if(!skipRegions.contains(region.getName())){
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				DescribeVolumesResult  rslt = ec2Client.describeVolumes(); // No need to paginate as all volumes will be returned.
				List<Volume> volumeListTemp = rslt.getVolumes();

				if( !volumeListTemp.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId +" Type : Volume "+region.getName() + " >> "+volumeListTemp.size());
					volumeList.put(accountId+delimiter+accountName+delimiter+region.getName(),volumeListTemp);
				}
			}

		}catch(Exception e){
			log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"volume",e.getMessage());
		}
	}
	return volumeList;
}
 
Example #18
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch snapshots.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @param accountName the account name
 * @return the map
 */
public static Map<String,List<Snapshot>> fetchSnapshots(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName) {
	Map<String,List<Snapshot>> snapShots = new LinkedHashMap<>();
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"Snapshot\" , \"region\":\"" ;
	for(Region region : RegionUtils.getRegions()){
		try{
			if(!skipRegions.contains(region.getName())){
				AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				List<Snapshot> snapShotsList = ec2Client.describeSnapshots(new DescribeSnapshotsRequest().withOwnerIds(accountId)).getSnapshots();// No need to paginate as all results will be returned
				if( !snapShotsList.isEmpty() ){
					log.debug(InventoryConstants.ACCOUNT + accountId +" Type : Snapshot " +region.getName() + " >> "+snapShotsList.size());
					snapShots.put(accountId+delimiter+accountName+delimiter+region.getName(),snapShotsList);
				}
			}

		}catch(Exception e){
			log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"snapshot",e.getMessage());
		}
	}
	return snapShots;
}
 
Example #19
Source File: EC2InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch network ACL test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchNetworkACLTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeNetworkAclsResult describeNetworkAclsResult = new DescribeNetworkAclsResult();
    List<NetworkAcl> networkAclList = new ArrayList<>();
    networkAclList.add(new NetworkAcl());
    describeNetworkAclsResult.setNetworkAcls(networkAclList);
    when(ec2Client.describeNetworkAcls()).thenReturn(describeNetworkAclsResult);
    assertThat(ec2InventoryUtil.fetchNetworkACL(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #20
Source File: EC2InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch internet gateway test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchInternetGatewayTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeInternetGatewaysResult describeInternetGatewaysResult = new DescribeInternetGatewaysResult();
    List<InternetGateway> internetGatewayList = new ArrayList<>();
    internetGatewayList.add(new InternetGateway());
    describeInternetGatewaysResult.setInternetGateways(internetGatewayList);
    when(ec2Client.describeInternetGateways()).thenReturn(describeInternetGatewaysResult);
    assertThat(ec2InventoryUtil.fetchInternetGateway(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #21
Source File: EC2InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch DHCP options test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchDHCPOptionsTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeDhcpOptionsResult describeDhcpOptionsResult = new DescribeDhcpOptionsResult();
    List<DhcpOptions> dhcpOptionsList = new ArrayList<>();
    dhcpOptionsList.add(new DhcpOptions());
    describeDhcpOptionsResult.setDhcpOptions(dhcpOptionsList);
    when(ec2Client.describeDhcpOptions()).thenReturn(describeDhcpOptionsResult);
    assertThat(ec2InventoryUtil.fetchDHCPOptions(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #22
Source File: EC2InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch VPN connections test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchVPNConnectionsTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeVpnConnectionsResult describeVpnConnectionsResult = new DescribeVpnConnectionsResult();
    List<VpnConnection> vpnConnectionsList = new ArrayList<>();
    vpnConnectionsList.add(new VpnConnection());
    describeVpnConnectionsResult.setVpnConnections(vpnConnectionsList);
    when(ec2Client.describeVpnConnections()).thenReturn(describeVpnConnectionsResult);
    assertThat(ec2InventoryUtil.fetchVPNConnections(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #23
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch volumet info test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchVolumetInfoTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeVolumesResult describeVolumesResult = new DescribeVolumesResult();
    List<Volume> volumeList = new ArrayList<>();
    volumeList.add(new Volume());
    describeVolumesResult.setVolumes(volumeList);
    when(ec2Client.describeVolumes()).thenReturn(describeVolumesResult);
    assertThat(inventoryUtil.fetchVolumetInfo(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #24
Source File: AWSProvider.java    From testgrid with Apache License 2.0 6 votes vote down vote up
/**
 *
 * Logs are retrieved via aws api that looks similar to this cli command:
 * aws ec2 get-console-output --instance-id i-123456789abcd --output text
 *
 * This won't contain the entire ec2 instance console (system) log.
 * It'll be truncated to last {@link #EC2_SYSTEM_LOG_NO_OF_LINES} lines.
 *
 * @param instance the ec2 instance object
 * @param amazonEC2 AmazonEC2 command handler
 * @return return string will be of following format:
 * <pre>
 *  ${ec2-nickname} logs {
 *      <br/>
 *      ${truncated-logs}
 *      <br/>
 *  }
 * </pre>
 */
private String getEC2InstanceConsoleLogs(Instance instance, AmazonEC2 amazonEC2) {
    String decodedOutput;
    String instanceName = instance.getTags().stream()
            .filter(t -> t.getKey().equals("Name"))
            .map(com.amazonaws.services.ec2.model.Tag::getValue)
            .findAny().orElse("<name-empty>");
    try {
        GetConsoleOutputRequest consoleOutputRequest = new GetConsoleOutputRequest(instance.getInstanceId());
        final GetConsoleOutputResult consoleOutputResult = amazonEC2.getConsoleOutput(consoleOutputRequest);
        decodedOutput = consoleOutputResult.getDecodedOutput();
        decodedOutput = reduceLogVerbosity(decodedOutput);

    } catch (NullPointerException e) {
        String error = e.getMessage() +
                (e.getStackTrace().length > 0 ? "at " + e.getStackTrace()[0].toString() : "");
        decodedOutput = "Error occurred while retrieving instance console logs for " + instance.getInstanceId() +
                ". Error: " + error;
    }

    return instanceName + " logs {\n" +
            decodedOutput + "\n" +
            "}\n";
}
 
Example #25
Source File: AWSProvider.java    From testgrid with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<String> getInstanceName(String region, String instanceId) {
    final AmazonEC2 amazonEC2 = AmazonEC2ClientBuilder.standard()
            .withCredentials(new PropertiesFileCredentialsProvider(configFilePath.toString()))
            .withRegion(region)
            .build();

    List<String> instanceIds = new ArrayList<>();
    instanceIds.add(instanceId);

    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(instanceIds);

    DescribeInstancesResult result = amazonEC2.describeInstances(request);
    Optional<String> tagOptional = result.getReservations()
            .stream()
            .flatMap(reservation -> reservation.getInstances().stream())
            .flatMap(instance -> instance.getTags().stream())
            .filter(tag -> NAME_ENTRY.equals(tag.getKey()))
            .findFirst()
            .map(Tag::getValue);
    return tagOptional;
}
 
Example #26
Source File: ExamplePlugin.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Override
// @HystrixCommand(fallback = my coole exception)
// command for account id and client type -> generate new credentials
public void processEvent(final CloudTrailEvent event) {

    final String parameters = event.getEventData().getRequestParameters();
    final String instanceId = getFromParameters(parameters);

    final AmazonEC2 client = getClientForAccount(
            event.getEventData().getUserIdentity().getAccountId(),
            Region.getRegion(Regions.fromName(event.getEventData().getAwsRegion())));

    final DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(Collections.singleton(instanceId));

    // try
    final DescribeInstancesResult result = client.describeInstances(request);
    // catch credentials are old
    // throw new my coole exception ( account id, CLIENTTYPE.EC2, exception) -> this will trigger hystrix

    LOG.info("SAVING RESULT INTO MAGIC DB", result);
}
 
Example #27
Source File: DeleteKeyPair.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args)
{
    final String USAGE =
        "To run this example, supply a key pair name\n" +
        "Ex: DeleteKeyPair <key-pair-name>\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String key_name = args[0];

    final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();

    DeleteKeyPairRequest request = new DeleteKeyPairRequest()
        .withKeyName(key_name);

    DeleteKeyPairResult response = ec2.deleteKeyPair(request);

    System.out.printf(
        "Successfully deleted key pair named %s", key_name);
}
 
Example #28
Source File: AutoDetectingStackNameProvider.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private AutoDetectingStackNameProvider(
		AmazonCloudFormation amazonCloudFormationClient, AmazonEC2 amazonEc2Client,
		InstanceIdProvider instanceIdProvider) {
	this.amazonCloudFormationClient = amazonCloudFormationClient;
	this.amazonEc2Client = amazonEc2Client;
	this.instanceIdProvider = instanceIdProvider;
	afterPropertiesSet();
}
 
Example #29
Source File: AutoResubmitIntegrationTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    EC2Api ec2Api = spy(EC2Api.class);
    Registry.setEc2Api(ec2Api);

    AmazonEC2 amazonEC2 = mock(AmazonEC2.class);
    when(ec2Api.connect(anyString(), anyString(), Mockito.nullable(String.class))).thenReturn(amazonEC2);

    final Instance instance = new Instance()
            .withState(new InstanceState().withName(InstanceStateName.Running))
            .withPublicIpAddress("public-io")
            .withInstanceId("i-1");

    when(amazonEC2.describeInstances(any(DescribeInstancesRequest.class))).thenReturn(
            new DescribeInstancesResult().withReservations(
                    new Reservation().withInstances(
                            instance
                    )));

    when(amazonEC2.describeSpotFleetInstances(any(DescribeSpotFleetInstancesRequest.class)))
            .thenReturn(new DescribeSpotFleetInstancesResult()
                    .withActiveInstances(new ActiveInstance().withInstanceId("i-1")));

    DescribeSpotFleetRequestsResult describeSpotFleetRequestsResult = new DescribeSpotFleetRequestsResult();
    describeSpotFleetRequestsResult.setSpotFleetRequestConfigs(Arrays.asList(
            new SpotFleetRequestConfig()
                    .withSpotFleetRequestState("active")
                    .withSpotFleetRequestConfig(
                            new SpotFleetRequestConfigData().withTargetCapacity(1))));
    when(amazonEC2.describeSpotFleetRequests(any(DescribeSpotFleetRequestsRequest.class)))
            .thenReturn(describeSpotFleetRequestsResult);
}
 
Example #30
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch instances test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchInstancesTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeInstancesResult describeInstancesResult = new DescribeInstancesResult();
    List<Instance> instanceList = new ArrayList<>();
    instanceList.add(new Instance());
    List<Reservation> reservations = new ArrayList<>();
    Reservation reservation = new Reservation();
    reservation.setInstances(instanceList);
    reservations.add(reservation);
    describeInstancesResult.setReservations(reservations );
    when(ec2Client.describeInstances(anyObject())).thenReturn(describeInstancesResult);
    assertThat(inventoryUtil.fetchInstances(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName","").size(), is(1));
    
}