com.amazonaws.auth.profile.ProfileCredentialsProvider Java Examples

The following examples show how to use com.amazonaws.auth.profile.ProfileCredentialsProvider. 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: ContextCredentialsAutoConfiguration.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
private List<AWSCredentialsProvider> resolveCredentialsProviders(
		AwsCredentialsProperties properties) {
	List<AWSCredentialsProvider> providers = new ArrayList<>();

	if (StringUtils.hasText(properties.getAccessKey())
			&& StringUtils.hasText(properties.getSecretKey())) {
		providers.add(new AWSStaticCredentialsProvider(new BasicAWSCredentials(
				properties.getAccessKey(), properties.getSecretKey())));
	}

	if (properties.isInstanceProfile()) {
		providers.add(new EC2ContainerCredentialsProviderWrapper());
	}

	if (properties.getProfileName() != null) {
		providers.add(properties.getProfilePath() != null
				? new ProfileCredentialsProvider(properties.getProfilePath(),
						properties.getProfileName())
				: new ProfileCredentialsProvider(properties.getProfileName()));
	}

	return providers;
}
 
Example #2
Source File: S3.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
public static AmazonS3 buildS3(LocalServerConfig configuration) {
    String region = configuration.getProperty(pRegion);
    String endpoint = configuration.getProperty(pEndpoint);
    String credentialsFile =  configuration.getProperty(pCredentialFile);
    String credentialsProfile =  configuration.getProperty(pCredentialProfile);

    AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard();
    if ( endpoint == null )
        builder.withRegion(region);
    else  {
        // Needed for S3mock
        builder.withPathStyleAccessEnabled(true);
        builder.withEndpointConfiguration(new EndpointConfiguration(endpoint, region));
        builder.withCredentials(new AWSStaticCredentialsProvider(new AnonymousAWSCredentials()));
    }
    if ( credentialsFile != null )
        builder.withCredentials(new ProfileCredentialsProvider(credentialsFile, credentialsProfile));
    return builder.build();
}
 
Example #3
Source File: DeleteFunction.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        if (args.length < 1) {
            System.out.println("Please specify a function name");
            System.exit(1);
        }

        // snippet-start:[lambda.java1.delete.main]
        String functionName = args[0];
        try {
            AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
                    .withCredentials(new ProfileCredentialsProvider())
                    .withRegion(Regions.US_WEST_2).build();

            DeleteFunctionRequest delFunc = new DeleteFunctionRequest();
            delFunc.withFunctionName(functionName);

            //Delete the functiom
            awsLambda.deleteFunction(delFunc);
            System.out.println("The function is deleted");

        } catch (ServiceException e) {
            System.out.println(e);
        }
        // snippet-end:[lambda.java1.delete.main]
    }
 
Example #4
Source File: ListFunctions.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        // snippet-start:[lambda.java1.list.main]
        ListFunctionsResult functionResult = null;

        try {
            AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
                    .withCredentials(new ProfileCredentialsProvider())
                    .withRegion(Regions.US_WEST_2).build();

            functionResult = awsLambda.listFunctions();

            List<FunctionConfiguration> list = functionResult.getFunctions();

            for (Iterator iter = list.iterator(); iter.hasNext(); ) {
                FunctionConfiguration config = (FunctionConfiguration)iter.next();

                System.out.println("The function name is "+config.getFunctionName());
            }

        } catch (ServiceException e) {
            System.out.println(e);
        }
        // snippet-end:[lambda.java1.list.main]
    }
 
Example #5
Source File: ContextCredentialsConfigurationRegistrarTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void credentialsProvider_configWithAllProviders_allCredentialsProvidersConfigured()
		throws Exception {
	// Arrange
	this.context = new AnnotationConfigApplicationContext(
			ApplicationConfigurationWithAllProviders.class);

	// Act
	AWSCredentialsProvider awsCredentialsProvider = this.context
			.getBean(AWSCredentialsProvider.class);

	// Assert
	assertThat(awsCredentialsProvider).isNotNull();

	@SuppressWarnings("unchecked")
	List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils
			.getField(awsCredentialsProvider, "credentialsProviders");
	assertThat(credentialsProviders.size()).isEqualTo(3);
	assertThat(AWSStaticCredentialsProvider.class
			.isInstance(credentialsProviders.get(0))).isTrue();
	assertThat(EC2ContainerCredentialsProviderWrapper.class
			.isInstance(credentialsProviders.get(1))).isTrue();
	assertThat(
			ProfileCredentialsProvider.class.isInstance(credentialsProviders.get(2)))
					.isTrue();
}
 
Example #6
Source File: CreateService.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception
{
	AWSCredentials credentials = null;
	try
	{
		credentials = new ProfileCredentialsProvider().getCredentials();
	}catch(Exception e)
	{
		throw new AmazonClientException("Cannot Load credentials");
	}
	
	AWSServiceDiscovery client = AWSServiceDiscoveryClientBuilder
								.standard()
								.withCredentials(new AWSStaticCredentialsProvider(credentials))
								.withRegion("us-east-1")
								.build();
	
	CreateServiceRequest crequest = new CreateServiceRequest();
	crequest.setName("example-service-01");
	crequest.setDescription("This is an example service request");
	crequest.setNamespaceId("ns-ldmexc5fqajjnhco");//Replace with the namespaceID		
	System.out.println(client.createService(crequest));
}
 
Example #7
Source File: Main.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private static AwsInstanceCloudConnector createConnector() {
    AWSCredentialsProvider baseCredentials = new ProfileCredentialsProvider("default");
    AWSSecurityTokenServiceAsync stsClient = new AmazonStsAsyncProvider(CONFIGURATION, baseCredentials).get();
    AWSCredentialsProvider credentialsProvider = new DataPlaneControllerCredentialsProvider(CONFIGURATION, stsClient, baseCredentials).get();

    Region currentRegion = Regions.getCurrentRegion();
    if (currentRegion == null) {
        currentRegion = Region.getRegion(Regions.US_EAST_1);
    }
    return new AwsInstanceCloudConnector(
            CONFIGURATION,
            AmazonEC2AsyncClientBuilder.standard()
                    .withRegion(currentRegion.getName())
                    .withCredentials(credentialsProvider)
                    .build(),
            AmazonAutoScalingAsyncClientBuilder.standard()
                    .withRegion(currentRegion.getName())
                    .withCredentials(credentialsProvider)
                    .build()
    );
}
 
Example #8
Source File: ListInstances.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception
{
	AWSCredentials credentials = null;
	try
	{
		credentials = new ProfileCredentialsProvider().getCredentials();
	}catch(Exception e)
	{
		throw new AmazonClientException("Cannot Load credentials");
	}
	
	AWSServiceDiscovery client = AWSServiceDiscoveryClientBuilder
								.standard()
								.withCredentials(new AWSStaticCredentialsProvider(credentials))
								.withRegion("us-east-1")
								.build();
	
	ListInstancesRequest lreq = new ListInstancesRequest();
	lreq.setServiceId("srv-l7gkxmjapm5givba");  //Replace with service id
	
	System.out.println(client.listInstances(lreq));
}
 
Example #9
Source File: ContextCredentialsAutoConfigurationTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void credentialsProvider_profileNameConfigured_configuresProfileCredentialsProvider() {
	this.contextRunner.withPropertyValues(
			"cloud.aws.credentials.use-default-aws-credentials-chain:false",
			"cloud.aws.credentials.profile-name:test").run((context) -> {
				AWSCredentialsProvider awsCredentialsProvider = context.getBean(
						AmazonWebserviceClientConfigurationUtils.CREDENTIALS_PROVIDER_BEAN_NAME,
						AWSCredentialsProvider.class);
				assertThat(awsCredentialsProvider).isNotNull();

				@SuppressWarnings("unchecked")
				List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils
						.getField(awsCredentialsProvider, "credentialsProviders");
				assertThat(credentialsProviders).hasSize(1)
						.hasOnlyElementsOfType(ProfileCredentialsProvider.class);
				assertThat(ReflectionTestUtils.getField(credentialsProviders.get(0),
						"profileName")).isEqualTo("test");
			});
}
 
Example #10
Source File: AwsSdkSample.java    From aws-sdk-java-archetype with Apache License 2.0 6 votes vote down vote up
/**
 * The only information needed to create a client are security credentials -
 * your AWS Access Key ID and Secret Access Key. All other
 * configuration, such as the service endpoints have defaults provided.
 *
 * Additional client parameters, such as proxy configuration, can be specified
 * in an optional ClientConfiguration object when constructing a client.
 *
 * @see com.amazonaws.auth.BasicAWSCredentials
 * @see com.amazonaws.auth.PropertiesCredentials
 * @see com.amazonaws.ClientConfiguration
 */
private static void init() throws Exception {
    /*
     * ProfileCredentialsProvider loads AWS security credentials from a
     * .aws/config file in your home directory.
     *
     * These same credentials are used when working with other AWS SDKs and the AWS CLI.
     *
     * You can find more information on the AWS profiles config file here:
     * http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
     */
    File configFile = new File(System.getProperty("user.home"), ".aws/credentials");
    AWSCredentialsProvider credentialsProvider = new ProfileCredentialsProvider(
        new ProfilesConfigFile(configFile), "default");

    if (credentialsProvider.getCredentials() == null) {
        throw new RuntimeException("No AWS security credentials found:\n"
                + "Make sure you've configured your credentials in: " + configFile.getAbsolutePath() + "\n"
                + "For more information on configuring your credentials, see "
                + "http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html");
    }

    ec2 = new AmazonEC2Client(credentialsProvider);
    s3  = new AmazonS3Client(credentialsProvider);
}
 
Example #11
Source File: ContextCredentialsAutoConfigurationTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void credentialsProvider_profileNameAndPathConfigured_configuresProfileCredentialsProvider()
		throws IOException {
	this.contextRunner
			.withPropertyValues(
					"cloud.aws.credentials.use-default-aws-credentials-chain:false",
					"cloud.aws.credentials.profileName:customProfile",
					"cloud.aws.credentials.profilePath:" + new ClassPathResource(
							getClass().getSimpleName() + "-profile", getClass())
									.getFile().getAbsolutePath())
			.run((context) -> {
				AWSCredentialsProvider awsCredentialsProvider = context.getBean(
						AmazonWebserviceClientConfigurationUtils.CREDENTIALS_PROVIDER_BEAN_NAME,
						AWSCredentialsProvider.class);
				assertThat(awsCredentialsProvider).isNotNull();

				@SuppressWarnings("unchecked")
				List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils
						.getField(awsCredentialsProvider, "credentialsProviders");
				assertThat(credentialsProviders).hasSize(1)
						.hasOnlyElementsOfType(ProfileCredentialsProvider.class);

				ProfileCredentialsProvider provider = (ProfileCredentialsProvider) credentialsProviders
						.get(0);
				assertThat(provider.getCredentials().getAWSAccessKeyId())
						.isEqualTo("testAccessKey");
				assertThat(provider.getCredentials().getAWSSecretKey())
						.isEqualTo("testSecretKey");
			});
}
 
Example #12
Source File: AwsModule.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public AWSCredentialsProvider deserializeWithType(
    JsonParser jsonParser, DeserializationContext context, TypeDeserializer typeDeserializer)
    throws IOException {
  Map<String, String> asMap =
      jsonParser.readValueAs(new TypeReference<Map<String, String>>() {});

  String typeNameKey = typeDeserializer.getPropertyName();
  String typeName = asMap.get(typeNameKey);
  if (typeName == null) {
    throw new IOException(
        String.format("AWS credentials provider type name key '%s' not found", typeNameKey));
  }

  if (typeName.equals(AWSStaticCredentialsProvider.class.getSimpleName())) {
    return new AWSStaticCredentialsProvider(
        new BasicAWSCredentials(asMap.get(AWS_ACCESS_KEY_ID), asMap.get(AWS_SECRET_KEY)));
  } else if (typeName.equals(PropertiesFileCredentialsProvider.class.getSimpleName())) {
    return new PropertiesFileCredentialsProvider(asMap.get(CREDENTIALS_FILE_PATH));
  } else if (typeName.equals(
      ClasspathPropertiesFileCredentialsProvider.class.getSimpleName())) {
    return new ClasspathPropertiesFileCredentialsProvider(asMap.get(CREDENTIALS_FILE_PATH));
  } else if (typeName.equals(DefaultAWSCredentialsProviderChain.class.getSimpleName())) {
    return new DefaultAWSCredentialsProviderChain();
  } else if (typeName.equals(EnvironmentVariableCredentialsProvider.class.getSimpleName())) {
    return new EnvironmentVariableCredentialsProvider();
  } else if (typeName.equals(SystemPropertiesCredentialsProvider.class.getSimpleName())) {
    return new SystemPropertiesCredentialsProvider();
  } else if (typeName.equals(ProfileCredentialsProvider.class.getSimpleName())) {
    return new ProfileCredentialsProvider();
  } else if (typeName.equals(EC2ContainerCredentialsProviderWrapper.class.getSimpleName())) {
    return new EC2ContainerCredentialsProviderWrapper();
  } else {
    throw new IOException(
        String.format("AWS credential provider type '%s' is not supported", typeName));
  }
}
 
Example #13
Source File: DeployTask.java    From gradle-beanstalk-plugin with MIT License 5 votes vote down vote up
@TaskAction
protected void deploy() {
    String versionLabel = getVersionLabel();

    AWSCredentialsProviderChain credentialsProvider = new AWSCredentialsProviderChain(new EnvironmentVariableCredentialsProvider(), new SystemPropertiesCredentialsProvider(), new ProfileCredentialsProvider(beanstalk.getProfile()), new EC2ContainerCredentialsProviderWrapper());

    BeanstalkDeployer deployer = new BeanstalkDeployer(beanstalk.getS3Endpoint(), beanstalk.getBeanstalkEndpoint(), credentialsProvider);

    File warFile = getProject().files(war).getSingleFile();
    deployer.deploy(warFile, deployment.getApplication(), deployment.getEnvironment(), deployment.getTemplate(), versionLabel);
}
 
Example #14
Source File: ExamplePlugin.java    From fullstop with Apache License 2.0 5 votes vote down vote up
private AmazonEC2 getClientForAccount(final String accountId, final Region region) {
    final AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClient.builder()
            .withCredentials(new ProfileCredentialsProvider()).build();
    final String roleArn = String.format("arn:aws:iam::%s:role/fullstop-role", accountId);
    final String sessionName = "fullstop-role";
    final AWSCredentialsProvider tempCredentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, sessionName)
            .withStsClient(stsClient)
            .withRoleSessionDurationSeconds(3600)
            .build();
    return AmazonEC2Client.builder().withCredentials(tempCredentialsProvider).withRegion(region.getName()).build();
}
 
Example #15
Source File: LookUpServicewithFilter.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception
{
	AWSCredentials credentials = null;
	try
	{
		credentials = new ProfileCredentialsProvider().getCredentials();
	}catch(Exception e)
	{
		throw new AmazonClientException("Cannot Load credentials");
	}
	
	AWSServiceDiscovery client = AWSServiceDiscoveryClientBuilder
								.standard()
								.withCredentials(new AWSStaticCredentialsProvider(credentials))
								.withRegion("us-east-1")
								.build();
	
	DiscoverInstancesRequest direquest = new DiscoverInstancesRequest();
	direquest.setNamespaceName("my-apps");
	direquest.setServiceName("frontend");
	
	//Use a filter to retrieve the service based on environment and version
	Map<String,String>  filtermap = new HashMap<String,String>();
	filtermap.put("Stage", "Dev"); //Stage - key of the custom attribute, Dev - value of the custom attribute
	filtermap.put("Version", "01");//Version - key of the custom attribute, 01 - value of the custom attribute
	direquest.setQueryParameters(filtermap);
	System.out.println(client.discoverInstances(direquest));
}
 
Example #16
Source File: emr-add-steps.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	AWSCredentials credentials_profile = null;		
	try {
		credentials_profile = new ProfileCredentialsProvider("default").getCredentials();
       } catch (Exception e) {
           throw new AmazonClientException(
                   "Cannot load credentials from .aws/credentials file. " +
                   "Make sure that the credentials file exists and the profile name is specified within it.",
                   e);
       }
	
	AmazonElasticMapReduce emr = AmazonElasticMapReduceClientBuilder.standard()
		.withCredentials(new AWSStaticCredentialsProvider(credentials_profile))
		.withRegion(Regions.US_WEST_1)
		.build();
       
	// Run a bash script using a predefined step in the StepFactory helper class
    StepFactory stepFactory = new StepFactory();
    StepConfig runBashScript = new StepConfig()
    		.withName("Run a bash script") 
    		.withHadoopJarStep(stepFactory.newScriptRunnerStep("s3://jeffgoll/emr-scripts/create_users.sh"))
    		.withActionOnFailure("CONTINUE");

    // Run a custom jar file as a step
    HadoopJarStepConfig hadoopConfig1 = new HadoopJarStepConfig()
       .withJar("s3://path/to/my/jarfolder") // replace with the location of the jar to run as a step
       .withMainClass("com.my.Main1") // optional main class, this can be omitted if jar above has a manifest
       .withArgs("--verbose"); // optional list of arguments to pass to the jar
    StepConfig myCustomJarStep = new StepConfig("RunHadoopJar", hadoopConfig1);

    AddJobFlowStepsResult result = emr.addJobFlowSteps(new AddJobFlowStepsRequest()
	  .withJobFlowId("j-xxxxxxxxxxxx") // replace with cluster id to run the steps
	  .withSteps(runBashScript,myCustomJarStep));
    
         System.out.println(result.getStepIds());

}
 
Example #17
Source File: ContextCredentialsConfigurationRegistrarTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void credentialsProvider_configWithProfileNameAndNoProfilePath_profileCredentialsProviderConfigured()
		throws Exception {
	// Arrange
	this.context = new AnnotationConfigApplicationContext(
			ApplicationConfigurationWithProfileAndDefaultProfilePath.class);

	// Act
	AWSCredentialsProvider awsCredentialsProvider = this.context
			.getBean(AWSCredentialsProvider.class);

	// Assert
	assertThat(awsCredentialsProvider).isNotNull();

	@SuppressWarnings("unchecked")
	List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils
			.getField(awsCredentialsProvider, "credentialsProviders");
	assertThat(credentialsProviders.size()).isEqualTo(1);
	assertThat(
			ProfileCredentialsProvider.class.isInstance(credentialsProviders.get(0)))
					.isTrue();

	ProfileCredentialsProvider provider = (ProfileCredentialsProvider) credentialsProviders
			.get(0);
	assertThat(ReflectionTestUtils.getField(provider, "profileName"))
			.isEqualTo("test");
}
 
Example #18
Source File: SQSResourcesIntegrationTest.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
/**
     * Creates a new Service builder for SQS and uses it to create to Queue.
     * Asserts that the queue created is loaded and has an Arn associated with
     * it.
     */
//    @BeforeClass
    public static void setUp() {

        sqs = ServiceBuilder.forService(SQS.class)
                .withCredentials(new ProfileCredentialsProvider()).build();

        setUpNewQueue();
    }
 
Example #19
Source File: AWSClusterSecurityManager.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
DefaultAWSCredentialsProviderChain(Config config) {
  super(new EnvironmentVariableCredentialsProvider(),
          new SystemPropertiesCredentialsProvider(),
          new ConfigurationCredentialsProvider(config),
          new ProfileCredentialsProvider(),
          new InstanceProfileCredentialsProvider());
}
 
Example #20
Source File: S3UrlGenerator.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@Value.Lazy
AmazonS3 s3Client() {
    return AmazonS3ClientBuilder.standard()
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpointUrl(), null))
            .withCredentials(new ProfileCredentialsProvider(profile()))
            .build();
}
 
Example #21
Source File: AWSClientFactory.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private static AWSCredentialsProvider handleProfile(EnvVars vars) {
	String profile = vars.get(AWS_PROFILE, vars.get(AWS_DEFAULT_PROFILE));
	if (profile != null) {
		return new ProfileCredentialsProvider(profile);
	}
	return null;
}
 
Example #22
Source File: KinesisVideoRendererExampleTest.java    From amazon-kinesis-video-streams-parser-library with Apache License 2.0 5 votes vote down vote up
@Ignore
@Test
public void testExample() throws InterruptedException, IOException {
    KinesisVideoRendererExample example = KinesisVideoRendererExample.builder().region(Regions.US_WEST_2)
            .streamName("render-example-stream")
            .credentialsProvider(new ProfileCredentialsProvider())
            .inputVideoStream(TestResourceUtil.getTestInputStream("vogels_480.mkv"))
            .renderFragmentMetadata(false)
            .build();

    example.execute();
}
 
Example #23
Source File: AWSLambdaConfiguration.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 * @param clientConfiguration clientConfiguration
 * @param environment environment
 */
public AWSLambdaConfiguration(AWSClientConfiguration clientConfiguration, Environment environment) {
    this.clientConfiguration = clientConfiguration;

    this.builder.setCredentials(new AWSCredentialsProviderChain(
        new EnvironmentAWSCredentialsProvider(environment),
        new EnvironmentVariableCredentialsProvider(),
        new SystemPropertiesCredentialsProvider(),
        new ProfileCredentialsProvider(),
        new EC2ContainerCredentialsProviderWrapper()
    ));
}
 
Example #24
Source File: S3Module.java    From Scribengin with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void configure() {

  AWSCredentials credentials = null;
  try {
    credentials = new ProfileCredentialsProvider().getCredentials();
  } catch (Exception e) {
    throw new AmazonClientException("Cannot load the credentials from the credential profiles file. ", e);
  }
  bind(AmazonS3.class).toInstance(new AmazonS3Client(credentials));
  SinkPartitioner sp = new OffsetPartitioner(s3SinkConfig.getOffsetPerPartition());
  bind(SinkPartitioner.class).toInstance(sp);
  bind(S3SinkConfig.class).toInstance(s3SinkConfig);
}
 
Example #25
Source File: TestCredentialsProviderFactory.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testNamedProfileCredentials() throws Throwable {
    final TestRunner runner = TestRunners.newTestRunner(MockAWSProcessor.class);
    runner.setProperty(CredentialPropertyDescriptors.USE_DEFAULT_CREDENTIALS, "false");
    runner.setProperty(CredentialPropertyDescriptors.PROFILE_NAME, "BogusProfile");
    runner.assertValid();

    Map<PropertyDescriptor, String> properties = runner.getProcessContext().getProperties();
    final CredentialsProviderFactory factory = new CredentialsProviderFactory();
    final AWSCredentialsProvider credentialsProvider = factory.getCredentialsProvider(properties);
    Assert.assertNotNull(credentialsProvider);
    assertEquals("credentials provider should be equal", ProfileCredentialsProvider.class,
            credentialsProvider.getClass());
}
 
Example #26
Source File: AwsConfig.java    From cloudwatch-logback-appender with Apache License 2.0 5 votes vote down vote up
public AWSLogs createAWSLogs() {
    AWSLogsClientBuilder builder = AWSLogsClientBuilder.standard();

    if(region!=null) {
        builder.withRegion(region);
    }

    if(clientConfig!=null) {
        builder.withClientConfiguration(clientConfig);
    }

    if(profileName!=null) {
        builder.withCredentials(new ProfileCredentialsProvider(profileName));
    }
    else if(credentials!=null) {
        builder.withCredentials(new AWSStaticCredentialsProvider(credentials));
    }

    return builder.build();
}
 
Example #27
Source File: S3Conf.java    From pentaho-hadoop-shims with Apache License 2.0 5 votes vote down vote up
private AWSCredentials getCredsFromFile( Map<String, String> props, String credentialsFilePath ) {
  try {
    ProfileCredentialsProvider credProvider =
      new ProfileCredentialsProvider( credentialsFilePath, props.get( "profileName" ) );
    return credProvider.getCredentials();
  } catch ( Exception e ) {
    throw new IllegalArgumentException(
      String.format( "Failed to load credentials for profile [%s] from %s",
        props.get( "profileName" ), credentialsFilePath ), e );
  }
}
 
Example #28
Source File: TestCredentialsProviderFactory.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testNamedProfileCredentials() throws Throwable {
    final TestRunner runner = TestRunners.newTestRunner(MockAWSProcessor.class);
    runner.setProperty(CredentialPropertyDescriptors.USE_DEFAULT_CREDENTIALS, "false");
    runner.setProperty(CredentialPropertyDescriptors.PROFILE_NAME, "BogusProfile");
    runner.assertValid();

    Map<PropertyDescriptor, String> properties = runner.getProcessContext().getProperties();
    final CredentialsProviderFactory factory = new CredentialsProviderFactory();
    final AWSCredentialsProvider credentialsProvider = factory.getCredentialsProvider(properties);
    Assert.assertNotNull(credentialsProvider);
    assertEquals("credentials provider should be equal", ProfileCredentialsProvider.class,
            credentialsProvider.getClass());
}
 
Example #29
Source File: Main.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private static AwsIamConnector createConnector() {
    AWSCredentialsProvider baseCredentials = new ProfileCredentialsProvider("default");
    AWSSecurityTokenServiceAsync stsClient = new AmazonStsAsyncProvider(CONFIGURATION, baseCredentials).get();
    AWSCredentialsProvider credentialsProvider = new DataPlaneAgentCredentialsProvider(CONFIGURATION, stsClient, baseCredentials).get();

    Region currentRegion = Regions.getCurrentRegion();
    if (currentRegion == null) {
        currentRegion = Region.getRegion(Regions.US_EAST_1);
    }
    return new AwsIamConnector(
            CONFIGURATION,
            AmazonIdentityManagementAsyncClientBuilder.standard()
                    .withRegion(currentRegion.getName())
                    .withCredentials(credentialsProvider)
                    .build(),
            AWSSecurityTokenServiceAsyncClientBuilder.standard()
                    .withRegion(currentRegion.getName())
                    .withCredentials(credentialsProvider)
                    .build(),
            new DefaultRegistry()
    );
}
 
Example #30
Source File: AwsLoadBalancerConnectorTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();
    AmazonElasticLoadBalancingAsync albClient = AmazonElasticLoadBalancingAsyncClientBuilder.standard()
            .withCredentials(credentialsProvider)
            .withRegion(REGION)
            .build();
    awsLoadBalancerConnector = getAwsLoadBalancerConnector(albClient);
}