com.amazonaws.regions.Region Java Examples

The following examples show how to use com.amazonaws.regions.Region. 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: InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch security groups.
 *
 * @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<SecurityGroup>> fetchSecurityGroups(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	log.info("skipRegionseee" + skipRegions);
	Map<String,List<SecurityGroup>> secGrpList = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"Security Group\" , \"region\":\"" ;
	log.info("sgregion" + RegionUtils.getRegions().toString());
	for(Region region : RegionUtils.getRegions()) {
		try{
			if(!skipRegions.contains(region.getName())){
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				DescribeSecurityGroupsResult rslt =  ec2Client.describeSecurityGroups();
				List<SecurityGroup> secGrpListTemp = rslt.getSecurityGroups();
				if( !secGrpListTemp.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId +" Type : Security Group "+region.getName()+" >> " + secGrpListTemp.size());
					secGrpList.put(accountId+delimiter+accountName+delimiter+region.getName(),secGrpListTemp);
				}

			}
		}catch(Exception e){
			log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"sg",e.getMessage());
		}
	}
	return secGrpList;
}
 
Example #2
Source File: EC2Connector.java    From jenkins-deployment-dashboard-plugin with MIT License 6 votes vote down vote up
@Override
public boolean tagEnvironmentWithVersion(Region region, DeployJobVariables jobVariables) {
    String searchTag = jobVariables.getEnvironment();
    String version = jobVariables.getVersion();
    LOGGER.info("tagEnvironmentWithVersion " + region + " Tag " + searchTag + " version " + version);

    boolean environmentSuccessfulTagged = false;
    ec2.setRegion(region);
    DescribeInstancesResult instances = ec2.describeInstances();
    for (Reservation reservation : instances.getReservations()) {
        for (Instance instance : reservation.getInstances()) {
            for (Tag tag : instance.getTags()) {
                if (tag.getValue().equalsIgnoreCase(searchTag)) {
                    CreateTagsRequest createTagsRequest = new CreateTagsRequest();
                    createTagsRequest.withResources(instance.getInstanceId()).withTags(new Tag(VERSION_TAG, version));
                    LOGGER.info("Create Tag " + version + " for instance " + instance.getInstanceId());
                    ec2.createTags(createTagsRequest);
                    environmentSuccessfulTagged = true;
                }
            }
        }
    }
    return environmentSuccessfulTagged;
}
 
Example #3
Source File: AWSClients.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 6 votes vote down vote up
public AWSClients(
        final Region region,
        final AWSCredentials credentials,
        final String proxyHost,
        final int proxyPort,
        final String pluginUserAgentPrefix,
        final CodePipelineClientFactory codePipelineClientFactory,
        final S3ClientFactory s3ClientFactory) {

    if (region == null) {
        this.region = Region.getRegion(Regions.US_EAST_1);
    } else {
        this.region = region;
    }
    this.clientCfg = new ClientConfiguration().withUserAgentPrefix(pluginUserAgentPrefix);

    if (proxyHost != null && proxyPort > 0) {
        clientCfg.setProxyHost(proxyHost);
        clientCfg.setProxyPort(proxyPort);
    }

    this.codePipelineClient = codePipelineClientFactory.getAWSCodePipelineClient(credentials, clientCfg);
    this.codePipelineClient.setRegion(this.region);

    this.s3ClientFactory = s3ClientFactory;
}
 
Example #4
Source File: GenericApiGatewayClientTest.java    From apigateway-generic-java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute_noApiKey_noCreds() throws IOException {
    client = new GenericApiGatewayClientBuilder()
            .withEndpoint("https://foobar.execute-api.us-east-1.amazonaws.com")
            .withRegion(Region.getRegion(Regions.fromName("us-east-1")))
            .withClientConfiguration(new ClientConfiguration())
            .withHttpClient(new AmazonHttpClient(new ClientConfiguration(), mockClient, null))
            .build();

    GenericApiGatewayResponse response = client.execute(
            new GenericApiGatewayRequestBuilder()
                    .withBody(new ByteArrayInputStream("test request".getBytes()))
                    .withHttpMethod(HttpMethodName.POST)
                    .withResourcePath("/test/orders").build());

    assertEquals("Wrong response body", "test payload", response.getBody());
    assertEquals("Wrong response status", 200, response.getHttpResponse().getStatusCode());

    Mockito.verify(mockClient, times(1)).execute(argThat(new LambdaMatcher<>(
                    x -> (x.getMethod().equals("POST")
                            && x.getFirstHeader("x-api-key") == null
                            && x.getFirstHeader("Authorization") == null
                            && x.getURI().toString().equals("https://foobar.execute-api.us-east-1.amazonaws.com/test/orders")))),
            any(HttpContext.class));
}
 
Example #5
Source File: DirectConnectionInventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch direct connections virtual interfaces.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<VirtualInterface>> fetchDirectConnectionsVirtualInterfaces(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName) {
	
	Map<String,List<VirtualInterface>> virtualInterfacesMap = new LinkedHashMap<>();
	String expPrefix = "{\"errcode\": \"NO_RES_REG\" ,\"accountId\": \""+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"Direct Connections\" , \"region\":\"" ;

	for(Region region : RegionUtils.getRegions()) { 
		try{
			if(!skipRegions.contains(region.getName())){ 
				AmazonDirectConnectClient directConnectClient = (AmazonDirectConnectClient) AmazonDirectConnectClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				List<VirtualInterface> virtualInterfacesList = directConnectClient.describeVirtualInterfaces().getVirtualInterfaces();
				if(!virtualInterfacesList.isEmpty() ) {
					log.debug("Account : " + accountId + " Type : Direct Connections "+ region.getName()+" >> " + virtualInterfacesList.size());
					virtualInterfacesMap.put(accountId+delimiter+accountName+delimiter+region.getName(), virtualInterfacesList);
				}
		   	}
			
		}catch(Exception e){
	   		log.warn(expPrefix+ region.getName()+"\", \"cause\":\"" +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"virtualinterface",e.getMessage());
	   	}
	}
	return virtualInterfacesMap;
}
 
Example #6
Source File: S3Encrypt.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
/**
 * This uses the V2 metadata schema with a key wrap algorithm of 'kms' and a CEK algorithm of AES/GCM/NoPadding.
 */
// snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption]
public void authenticatedEncryption_KmsManagedKey() throws NoSuchAlgorithmException {
    // snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption_builder]
    AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder
            .standard()
            .withRegion(Regions.US_WEST_2)
            .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.AuthenticatedEncryption).withAwsKmsRegion(Region.getRegion(Regions.US_WEST_2)))
            // Can either be Key ID or alias (prefixed with 'alias/')
            .withEncryptionMaterials(new KMSEncryptionMaterialsProvider("alias/s3-kms-key"))
            .build();

    AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build();
    // snippet-end:[s3.java1.s3_encrypt.kms_authenticated_encryption_builder]

    // snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption_put_object]
    s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents");
    s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents");
    System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY));
    System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY));
    // snippet-end:[s3.java1.s3_encrypt.kms_authenticated_encryption_put_object]
}
 
Example #7
Source File: AwsEc2ServiceImpl.java    From crate with Apache License 2.0 6 votes vote down vote up
private AmazonEC2 buildClient(Ec2ClientSettings clientSettings) {
    final AWSCredentialsProvider credentials = buildCredentials(LOGGER, clientSettings);
    final ClientConfiguration configuration = buildConfiguration(LOGGER, clientSettings);
    final AmazonEC2 client = buildClient(credentials, configuration);
    if (Strings.hasText(clientSettings.endpoint)) {
        LOGGER.debug("using explicit ec2 endpoint [{}]", clientSettings.endpoint);
        client.setEndpoint(clientSettings.endpoint);
    } else {
        Region currentRegion = Regions.getCurrentRegion();
        if (currentRegion != null) {
            LOGGER.debug("using ec2 region [{}]", currentRegion);
            client.setRegion(currentRegion);
        }
    }
    return client;
}
 
Example #8
Source File: EC2InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch network ACL.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<NetworkAcl>> fetchNetworkACL(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	
	Map<String,List<NetworkAcl>> networkAclMap = 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<NetworkAcl> networkAclList = ec2Client.describeNetworkAcls().getNetworkAcls();
				
				if(!networkAclList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : EC2 Network Acl "+ region.getName()+" >> " + networkAclList.size());
					networkAclMap.put(accountId+delimiter+accountName+delimiter+region.getName(), networkAclList);
				}
		   	}
		}catch(Exception e){
	   		log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"networkacl",e.getMessage());
	   	}
	}
	return networkAclMap;
}
 
Example #9
Source File: EsInstanceStore.java    From soundwave with Apache License 2.0 6 votes vote down vote up
@Override
public Iterator<EsInstance> getRecentlyTerminatedInstances(Region region,
                                                           int days) throws Exception {

  Preconditions.checkNotNull(region);
  Preconditions.checkArgument(days > 0);

  DateTime start = getStartSinceDay(days);

  QueryBuilder queryBuilder = QueryBuilders.boolQuery()
      .must(QueryBuilders.termQuery("region", region.getName().toLowerCase()))
      .must(QueryBuilders.termQuery("state", "terminated"))
      .must(QueryBuilders.rangeQuery("aws_launch_time").gte(start));

  ScrollableResponse<List<EsInstance>> response = this.retrieveScrollByQuery(queryBuilder,
      EsMapper.getIncludeFields(getInstanceClass()), BATCHSIZE,
      str -> (EsInstance) insertMapper.readValue(str, getInstanceClass()));

  EsIterator<EsInstance>
      iterator =
      new EsIterator<>(response, r -> scrollNext(r.getContinousToken(),
          str -> (EsInstance) insertMapper.readValue(str, getInstanceClass())));

  return iterator;
}
 
Example #10
Source File: EC2InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch egress gateway.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<EgressOnlyInternetGateway>> fetchEgressGateway(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	
	Map<String,List<EgressOnlyInternetGateway>> egressGatewayMap = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"egressgateway\" , \"region\":\"" ;

	for(Region region : RegionUtils.getRegions()) { 
		try{
			if(!skipRegions.contains(region.getName())){
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				List<EgressOnlyInternetGateway> egressGatewayList = ec2Client.describeEgressOnlyInternetGateways(new DescribeEgressOnlyInternetGatewaysRequest()).getEgressOnlyInternetGateways();
				
				if(!egressGatewayList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : EC2 Egress Gateway "+ region.getName()+" >> " + egressGatewayList.size());
					egressGatewayMap.put(accountId+delimiter+accountName+delimiter+region.getName(), egressGatewayList);
				}
		   	}
		}catch(Exception e){
	   		log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
	   		ErrorManageUtil.uploadError(accountId,region.getName(),"egressgateway",e.getMessage());
	   	}
	}
	return egressGatewayMap;
}
 
Example #11
Source File: EC2InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch elastic IP addresses.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<Address>> fetchElasticIPAddresses(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	
	Map<String,List<Address>> elasticIPMap = 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<Address> elasticIPList = ec2Client.describeAddresses().getAddresses();
				
				if(!elasticIPList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : EC2 Elastic IP "+ region.getName()+" >> " + elasticIPList.size());
					elasticIPMap.put(accountId+delimiter+accountName+delimiter+region.getName(), elasticIPList);
				}
		   	}
		}catch(Exception e){
	   		log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"elasticip",e.getMessage());
	   	}
	}
	return elasticIPMap;
}
 
Example #12
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch network intefaces.
 *
 * @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<NetworkInterface>> fetchNetworkIntefaces(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){

	Map<String,List<NetworkInterface>> niMap = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"Network Interface\" , \"region\":\"" ;
	for(Region region : RegionUtils.getRegions()) {
		try{
			if(!skipRegions.contains(region.getName())){
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				DescribeNetworkInterfacesResult  descNIRslt =  ec2Client.describeNetworkInterfaces();
				List<NetworkInterface> niList = descNIRslt.getNetworkInterfaces();
				if(!niList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : Network Interface " +region.getName()+" >> " + niList.size());
					niMap.put(accountId+delimiter+accountName+delimiter+region.getName(),niList);
				}

			}
		}catch(Exception e){
			log.error("Exception fetching Network Interfaces for "+region.getName() + e);
			log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"eni",e.getMessage());
		}
	}
	return niMap;
}
 
Example #13
Source File: EsInstanceStore.java    From soundwave with Apache License 2.0 6 votes vote down vote up
@Override
public Iterator<EsInstance> getRunningInstances(Region region, String[] fields) throws Exception {

  Preconditions.checkNotNull(region);

  //state eq running and in the specificied region
  QueryBuilder queryBuilder = QueryBuilders.boolQuery()
      .must(QueryBuilders.termQuery("state", "running"))
      .must(QueryBuilders.termQuery("region", region.getName().toLowerCase()));

  ScrollableResponse<List<EsInstance>> response = this.retrieveScrollByQuery(queryBuilder,
      fields, BATCHSIZE,
      str -> (EsInstance) insertMapper.readValue(str, getInstanceClass()));

  EsIterator<EsInstance>
      iterator =
      new EsIterator<>(response, r -> scrollNext(r.getContinousToken(),
          str -> (EsInstance) insertMapper.readValue(str, getInstanceClass())));
  return iterator;
}
 
Example #14
Source File: Utilities.java    From dynamodb-geo with Apache License 2.0 6 votes vote down vote up
private synchronized void setupGeoDataManager() {
	if (geoDataManager == null) {
		String accessKey = System.getProperty("AWS_ACCESS_KEY_ID");
		String secretKey = System.getProperty("AWS_SECRET_KEY");
		String tableName = System.getProperty("PARAM1");
		String regionName = System.getProperty("PARAM2");

		Region region = Region.getRegion(Regions.fromName(regionName));
		ClientConfiguration clientConfiguration = new ClientConfiguration().withMaxErrorRetry(20);
		AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

		AmazonDynamoDBClient ddb = new AmazonDynamoDBClient(credentials, clientConfiguration);
		ddb.setRegion(region);

		GeoDataManagerConfiguration config = new GeoDataManagerConfiguration(ddb, tableName);
		geoDataManager = new GeoDataManager(config);
	}
}
 
Example #15
Source File: EncryptionService.java    From cerberus with Apache License 2.0 6 votes vote down vote up
@Autowired
public EncryptionService(
    AwsCrypto awsCrypto,
    @Value("${cerberus.encryption.cmk.arns}") String cmkArns,
    @Qualifier("decryptCryptoMaterialsManager")
        CryptoMaterialsManager decryptCryptoMaterialsManager,
    @Qualifier("encryptCryptoMaterialsManager")
        CryptoMaterialsManager encryptCryptoMaterialsManager,
    Region currentRegion) {
  this.currentRegion = currentRegion;
  this.awsCrypto = awsCrypto;
  log.info("CMK ARNs " + cmkArns);
  this.cmkArnList = splitArns(cmkArns);
  this.decryptCryptoMaterialsManager = decryptCryptoMaterialsManager;
  this.encryptCryptoMaterialsManager = encryptCryptoMaterialsManager;
}
 
Example #16
Source File: Passwords.java    From bender with Apache License 2.0 6 votes vote down vote up
public static String decrypt(String str, Region region) throws UnsupportedEncodingException {
  if (isJUnitTest()) {
    return str;
  }

  AWSKMS kms = AWSKMSClientBuilder.standard().withRegion(region.getName()).build();

  /*
   * The KMS ciphertext is base64 encoded and must be decoded before the request is made
   */
  String cipherString = str;
  byte[] cipherBytes = Base64.decode(cipherString);

  /*
   * Create decode request and decode
   */
  ByteBuffer cipherBuffer = ByteBuffer.wrap(cipherBytes);
  DecryptRequest req = new DecryptRequest().withCiphertextBlob(cipherBuffer);
  DecryptResult resp = kms.decrypt(req);

  /*
   * Convert the response plaintext bytes to a string
   */
  return new String(resp.getPlaintext().array(), Charset.forName("UTF-8"));
}
 
Example #17
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch NAT gateway 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<NatGateway>> fetchNATGatewayInfo(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	Map<String,List<NatGateway>> natGatwayMap =  new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"Nat Gateway\" , \"region\":\"" ;
	for(Region region : RegionUtils.getRegions()){
		try{
			if(!skipRegions.contains(region.getName())){
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				DescribeNatGatewaysResult rslt = ec2Client.describeNatGateways(new DescribeNatGatewaysRequest());
				List<NatGateway> natGatwayList =rslt.getNatGateways();
				if(! natGatwayList.isEmpty() ){
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : Nat Gateway "+region.getName() + " >> "+natGatwayList.size());
					natGatwayMap.put(accountId+delimiter+accountName+delimiter+region.getName(), natGatwayList);
				}

			}
		}catch(Exception e){
			log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"nat",e.getMessage());
		}
	}
	return natGatwayMap;
}
 
Example #18
Source File: AWSClients.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 6 votes vote down vote up
public static AWSClients fromBasicCredentials(
        final Region region,
        final String awsAccessKey,
        final String awsSecretKey,
        final String proxyHost,
        final int proxyPort,
        final String pluginUserAgentPrefix) {

    return new AWSClients(
            region,
            new BasicAWSCredentials(awsAccessKey, awsSecretKey),
            proxyHost,
            proxyPort,
            pluginUserAgentPrefix,
            new CodePipelineClientFactory(),
            new S3ClientFactory());
}
 
Example #19
Source File: Ec2MetadataRegionProvider.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Override
public Region getRegion() {
	Region currentRegion = getCurrentRegion();
	Assert.state(currentRegion != null,
			"There is no EC2 meta data available, because the application is not running "
					+ "in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance");
	return currentRegion;
}
 
Example #20
Source File: MCAWS.java    From aws-big-data-blog with Apache License 2.0 5 votes vote down vote up
public static void putImageS3(String bucketName, String key, String fileName) {
    AmazonS3 s3 = new AmazonS3Client();
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    //Region usWest2 = Region.getRegion(s3Region);
    s3.setRegion(usWest2);
    try {
        File file = new File(fileName);
        s3.putObject(new PutObjectRequest(bucketName, key, file));
    } catch (Exception e) { System.out.println("ERROR ON IMAGE FILE"); }
}
 
Example #21
Source File: JavaKinesisVideoServiceClient.java    From amazon-kinesis-video-streams-producer-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public String createStream(@Nonnull final String streamName,
        @Nonnull final String deviceName,
        @Nonnull final String contentType,
        @Nullable final String kmsKeyId,
        final long retentionPeriodInHours,
        final long timeoutInMillis,
        @Nullable final KinesisVideoCredentialsProvider credentialsProvider)
        throws KinesisVideoException {
    final AmazonKinesisVideo serviceClient = createAmazonKinesisVideoClient(credentialsProvider,
            Region.getRegion(Regions.fromName(configuration.getRegion())),
            configuration.getEndpoint(),
            (int) timeoutInMillis);

    final CreateStreamRequest createStreamRequest = new CreateStreamRequest()
            .withStreamName(streamName)
            .withDeviceName(deviceName)
            .withMediaType(contentType)
            .withKmsKeyId(isNullOrEmpty(kmsKeyId) ? null : kmsKeyId)
            .withDataRetentionInHours((int) retentionPeriodInHours)
            .withTags(null);

    log.debug("calling create stream: " + createStreamRequest.toString());

    final CreateStreamResult createStreamResult;
    try {
        createStreamResult = serviceClient.createStream(createStreamRequest);
    } catch (final AmazonClientException e) {
        // Wrap into an KinesisVideoException object
        log.exception(e, "Service call failed.");
        throw new KinesisVideoException(e);
    }

    log.debug("create stream result: " + createStreamResult.toString());

    return createStreamResult.getStreamARN();
}
 
Example #22
Source File: AWSClients.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 5 votes vote down vote up
public static AWSClients fromDefaultCredentialChain(
        final Region region,
        final String proxyHost,
        final int proxyPort,
        final String pluginUserAgentPrefix) {

    return new AWSClients(region, null, proxyHost, proxyPort, pluginUserAgentPrefix, new CodePipelineClientFactory(), new S3ClientFactory());
}
 
Example #23
Source File: AwsSessionService.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
public AmazonEC2Client getEC2Session(AWSEnvironment environment){
    BasicSessionCredentials creds = credentialCache.getUnchecked(environment);
    AmazonEC2Client ec2 = awsSessionFactory.createEC2Session(creds);
    ec2.setRegion(Region.getRegion(Regions.fromName(environment.getRegion())));
    return ec2;

}
 
Example #24
Source File: EncryptionService.java    From cerberus with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize a Multi-KMS-MasterKeyProvider.
 *
 * <p>For encrypt, KMS in all regions must be available. For decrypt, KMS in at least one region
 * must be available.
 */
public static MasterKeyProvider<KmsMasterKey> initializeKeyProvider(
    List<String> cmkArns, Region currentRegion) {
  List<MasterKeyProvider<KmsMasterKey>> providers =
      getSortedArnListByCurrentRegion(cmkArns, currentRegion).stream()
          .map(KmsMasterKeyProvider::new)
          .collect(Collectors.toList());
  return (MasterKeyProvider<KmsMasterKey>) MultipleProviderFactory.buildMultiProvider(providers);
}
 
Example #25
Source File: AWSEmailProvider.java    From athenz with Apache License 2.0 5 votes vote down vote up
private static AmazonSimpleEmailService initSES() {
    ///CLOVER:OFF
    Region region = Regions.getCurrentRegion();
    if (region == null) {
        region = Region.getRegion(Regions.US_EAST_1);
    }
    return AmazonSimpleEmailServiceClientBuilder.standard().withRegion(region.getName()).build();
    ///CLOVER:ON
}
 
Example #26
Source File: AmazonResourceNameTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void testElasticBeansTalkBuilder() {
	Builder builder = new Builder();
	builder.withService("elasticbeanstalk");
	builder.withRegion(Region.getRegion(Regions.US_EAST_1));
	builder.withResourceType("solutionstack");
	builder.withResourceName("32bit Amazon Linux running Tomcat 7");
	builder.withResourceTypeDelimiter("/");
	assertThat(builder.build().toString()).isEqualTo(
			"arn:aws:elasticbeanstalk:us-east-1::solutionstack/32bit Amazon Linux running Tomcat 7");
}
 
Example #27
Source File: FetchRdsJob.java    From fullstop with Apache License 2.0 5 votes vote down vote up
@Scheduled(fixedRate = 300_000)
public void run() {
    for (final String accountId : allAccountIds.get()) {
        for (final String region : jobsProperties.getWhitelistedRegions()) {
            try {
                final AmazonRDSClient amazonRDSClient = clientProvider.getClient(AmazonRDSClient.class, accountId,
                        Region.getRegion(Regions.fromName(region)));

                Optional<String> marker = Optional.empty();

                do {
                    final DescribeDBInstancesRequest request = new DescribeDBInstancesRequest();
                    marker.ifPresent(request::setMarker);
                    final DescribeDBInstancesResult result = amazonRDSClient.describeDBInstances(request);
                    marker = Optional.ofNullable(trimToNull(result.getMarker()));

                    result.getDBInstances().stream()
                            .filter(DBInstance::getPubliclyAccessible)
                            .filter(dbInstance -> dbInstance.getEndpoint() != null)
                            .forEach(dbInstance -> {
                                final Map<String, Object> metadata = newHashMap();
                                metadata.put("unsecuredDatabase", dbInstance.getEndpoint().getAddress());
                                metadata.put("errorMessages", "Unsecured Database! Your DB can be reached from outside");
                                writeViolation(accountId, region, metadata, dbInstance.getEndpoint().getAddress());

                            });

                } while (marker.isPresent());

            } catch (final Exception e) {
                jobExceptionHandler.onException(e, ImmutableMap.of(
                        "job", this.getClass().getSimpleName(),
                        "aws_account_id", accountId,
                        "aws_region", region));
            }
        }
    }
}
 
Example #28
Source File: Ec2InstanceStore.java    From soundwave with Apache License 2.0 5 votes vote down vote up
@Override
public List<Instance> getInstances(Region region) throws Exception {
  List<Instance> ret = new ArrayList<>();
  List<AvailabilityZone> zones = getAvailabilityZones(region);
  AmazonEC2Client client = getClient(region);
  ExecutorService executor = Executors.newFixedThreadPool(zones.size());
  try {
    List<Callable<List<Instance>>> retrieveFunction = new ArrayList<>();
    for (AvailabilityZone zone : zones) {
      retrieveFunction.add(new Callable<List<Instance>>() {
        @Override
        public List<Instance> call() throws Exception {
          return getInstancesForZone(zone, client);
        }
      });
    }

    List<Future<List<Instance>>> futures = executor.invokeAll(retrieveFunction);
    for (Future<List<Instance>> future : futures) {
      ret.addAll(future.get());
    }

  } finally {
    executor.shutdown();
  }

  return ret;
}
 
Example #29
Source File: ProducerUtils.java    From kinesis-aggregation with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new Kinesis producer for publishing to Kinesis.
 * 
 * @param region The region of the Kinesis stream to publish to.
 * 
 * @return An Amazon Kinesis producer for publishing to a Kinesis stream.
 */
public static AmazonKinesis getKinesisProducer(String region)
{
    ClientConfiguration config = new ClientConfiguration();
    config.setMaxConnections(25);
    config.setConnectionTimeout(60000);
    config.setSocketTimeout(60000);

    AmazonKinesis producer = new AmazonKinesisClient(new DefaultAWSCredentialsProviderChain(), config);
    producer.setRegion(Region.getRegion(Regions.fromName(region)));

    return producer;
}
 
Example #30
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch target groups.
 *
 * @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<TargetGroupVH>> fetchTargetGroups(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	com.amazonaws.services.elasticloadbalancingv2.AmazonElasticLoadBalancing elbClient ;
	Map<String,List<TargetGroupVH>> targetGrpMap = new LinkedHashMap<>();
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"Target Group\" , \"region\":\"" ;
	for(Region region : RegionUtils.getRegions()){
		try{
			if(!skipRegions.contains(region.getName())){
				elbClient = com.amazonaws.services.elasticloadbalancingv2.AmazonElasticLoadBalancingClientBuilder.standard().
					 	withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				String nextMarker = null;
				List<TargetGroupVH> targetGrpList = new ArrayList<>();
				do{
					DescribeTargetGroupsResult  trgtGrpRslt =  elbClient.describeTargetGroups(new DescribeTargetGroupsRequest().withMarker(nextMarker));
					List<TargetGroup> targetGrpListTemp = trgtGrpRslt.getTargetGroups();
					for(TargetGroup tg : targetGrpListTemp) {
						DescribeTargetHealthResult rslt =  elbClient.describeTargetHealth(new DescribeTargetHealthRequest().withTargetGroupArn(tg.getTargetGroupArn()));
						targetGrpList.add(new TargetGroupVH(tg, rslt.getTargetHealthDescriptions()));
					}
					nextMarker = trgtGrpRslt.getNextMarker();
				}while(nextMarker!=null);

				if( !targetGrpList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId +" Type : Target Group " +region.getName() + "-"+targetGrpList.size());
					targetGrpMap.put(accountId+delimiter+accountName+delimiter+region.getName(), targetGrpList);
				}

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