com.cloudbees.jenkins.plugins.awscredentials.AmazonWebServicesCredentials Java Examples

The following examples show how to use com.cloudbees.jenkins.plugins.awscredentials.AmazonWebServicesCredentials. 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: AWSClientFactory.java    From awseb-deployment-plugin with Apache License 2.0 6 votes vote down vote up
private static AmazonWebServicesCredentials lookupNamedCredential(String credentialsId)
        throws CredentialNotFoundException {
    final Jenkins jenkins = Jenkins.getInstanceOrNull();

    if (jenkins == null)
        throw new RuntimeException("Missing Jenkins Instance");

    List<AmazonWebServicesCredentials> credentialList =
            CredentialsProvider.lookupCredentials(
                    AmazonWebServicesCredentials.class, jenkins, ACL.SYSTEM,
                    Collections.<DomainRequirement>emptyList());

    AmazonWebServicesCredentials cred =
            CredentialsMatchers.firstOrNull(credentialList,
                    CredentialsMatchers.allOf(
                            CredentialsMatchers.withId(credentialsId)));

    if (cred == null) {
        throw new CredentialNotFoundException(credentialsId);
    }
    return cred;
}
 
Example #2
Source File: AWSEBDeploymentBuilder.java    From awseb-deployment-plugin with Apache License 2.0 6 votes vote down vote up
public AbstractIdCredentialsListBoxModel<?, ?> doFillCredentialIdItems(
        @AncestorInPath Item owner) {
    if (owner == null || !owner.hasPermission(Item.CONFIGURE)) {
        return new AWSCredentialsListBoxModel();
    }

    List<AmazonWebServicesCredentials>
            creds =
            CredentialsProvider
                    .lookupCredentials(AmazonWebServicesCredentials.class, owner, ACL.SYSTEM,
                            Collections.<DomainRequirement>emptyList());

    return new AWSCredentialsListBoxModel()
            .withEmptySelection()
            .withAll(creds);
}
 
Example #3
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
public ListBoxModel doFillCredentialsItems(@AncestorInPath Item context) {

			if (context == null || !context.hasPermission(Item.CONFIGURE)) {
				return new ListBoxModel();
			}

			return new StandardListBoxModel()
					.includeEmptyValue()
					.includeMatchingAs(
							context instanceof Queue.Task
									? Tasks.getAuthenticationOf((Queue.Task) context)
									: ACL.SYSTEM,
							context,
							StandardUsernamePasswordCredentials.class,
							Collections.emptyList(),
							CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class))
					.includeMatchingAs(context instanceof Queue.Task
									? Tasks.getAuthenticationOf((Queue.Task) context)
									: ACL.SYSTEM,
							context,
							AmazonWebServicesCredentials.class,
							Collections.emptyList(),
							CredentialsMatchers.instanceOf(AmazonWebServicesCredentials.class));
		}
 
Example #4
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testStepWithBasicAndAwsGlobalCredentials() throws Exception {

	String globalBaseCreds = "global-basic-creds";
	String globalAwsCreds = "global-aws-creds";

	List<String> credentialIds = new ArrayList<>();
	credentialIds.add(globalBaseCreds);

	StandardUsernamePasswordCredentials key = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
			globalBaseCreds, "test-global-creds", "global-aws-access-key-id", "global-aws-secret-access-key");

	AmazonWebServicesCredentials amazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL,
			globalAwsCreds, "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description",
			"Arn::Something:or:Other", "12345678");

	SystemCredentialsProvider.getInstance().getCredentials().add(amazonWebServicesCredentials);
	SystemCredentialsProvider.getInstance().getCredentials().add(key);
	SystemCredentialsProvider.getInstance().save();

	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithBasicAndAwsGlobalCredentials");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  withAWS (credentials: '" + globalBaseCreds + "') {\n"
			+ "    echo 'It works!'\n"
			+ "  }\n"
			+ "}\n", true)
	);
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
}
 
Example #5
Source File: ECSService.java    From amazon-ecs-plugin with MIT License 5 votes vote down vote up
public ECSService(String credentialsId, String regionName) {
    this.clientSupplier = () -> {
        ProxyConfiguration proxy = Jenkins.get().proxy;
        ClientConfiguration clientConfiguration = new ClientConfiguration();

        if (proxy != null) {
            clientConfiguration.setProxyHost(proxy.name);
            clientConfiguration.setProxyPort(proxy.port);
            clientConfiguration.setProxyUsername(proxy.getUserName());
            clientConfiguration.setProxyPassword(proxy.getPassword());
        }

        // Default is 3. 10 helps us actually utilize the SDK's backoff strategy
        // The strategy will wait up to 20 seconds per request (after multiple failures)
        clientConfiguration.setMaxErrorRetry(10);

        AmazonECSClientBuilder builder = AmazonECSClientBuilder
                .standard()
                .withClientConfiguration(clientConfiguration)
                .withRegion(regionName);

        AmazonWebServicesCredentials credentials = getCredentials(credentialsId);
        if (credentials != null) {
            if (LOGGER.isLoggable(Level.FINE)) {
                String awsAccessKeyId = credentials.getCredentials().getAWSAccessKeyId();
                String obfuscatedAccessKeyId = StringUtils.left(awsAccessKeyId, 4) + StringUtils.repeat("*", awsAccessKeyId.length() - (2 * 4)) + StringUtils.right(awsAccessKeyId, 4);
                LOGGER.log(Level.FINE, "Connect to Amazon ECS with IAM Access Key {1}", new Object[]{obfuscatedAccessKeyId});
            }
            builder
                    .withCredentials(credentials);
        }
        LOGGER.log(Level.FINE, "Selected Region: {0}", regionName);

        return builder.build();
    };
}
 
Example #6
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testListAWSCredentials() throws Exception {

	Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size());
	CredentialsStore folderStore = this.getFolderStore(folder);
	AmazonWebServicesCredentials amazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL,
			"test-aws-creds", "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description",
			"Arn::Something:or:Other", "12345678");
	AmazonWebServicesCredentials globalAmazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL,
			"global-test-aws-creds", "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description",
			"Arn::Something:or:Other", "12345678");

	folderStore.addCredentials(Domain.global(), amazonWebServicesCredentials);
	SystemCredentialsProvider.getInstance().getCredentials().add(globalAmazonWebServicesCredentials);
	SystemCredentialsProvider.getInstance().save();

	WorkflowJob job = folder.createProject(WorkflowJob.class, "testStepWithFolderCredentials");
	final WithAWSStep.DescriptorImpl descriptor = jenkinsRule.jenkins.getDescriptorByType(WithAWSStep.DescriptorImpl.class);

	// 3 options: Root credentials, folder credentials and "none"
	ListBoxModel list = descriptor.doFillCredentialsItems(job);
	Assert.assertEquals(3, list.size());

	StandardUsernamePasswordCredentials systemCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM,
			"system-creds", "test-creds", "aws-access-key-id", "aws-secret-access-key");
	SystemCredentialsProvider.getInstance().getCredentials().add(systemCredentials);

	// Still 3 options: Root credentials, folder credentials and "none"
	list = descriptor.doFillCredentialsItems(job);
	Assert.assertEquals(3, list.size());
}
 
Example #7
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testStepWithAWSIamMFAFolderCredentials() throws Exception {

	String folderCredentialsId = "folders-aws-creds";

	// Create a folder with credentials in its store
	Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size());
	CredentialsStore folderStore = this.getFolderStore(folder);
	AmazonWebServicesCredentials amazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL,
			folderCredentialsId, "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description",
			"Arn::Something:or:Other", "12345678");
	folderStore.addCredentials(Domain.global(), amazonWebServicesCredentials);
	SystemCredentialsProvider.getInstance().save();

	List<String> credentialIds = new ArrayList<>();
	credentialIds.add(folderCredentialsId);

	WorkflowJob job = folder.createProject(WorkflowJob.class, "testStepWithAWSIamMFAFolderCredentials");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  withAWS (credentials: '" + folderCredentialsId + "', iamMfaToken: '1234567') {\n"
			+ "    echo 'It works!'\n"
			+ "  }\n"
			+ "}\n", true)
	);
	WorkflowRun workflowRun = job.scheduleBuild2(0).get();
	jenkinsRule.waitForCompletion(workflowRun);
	jenkinsRule.assertBuildStatus(Result.FAILURE, workflowRun);
	jenkinsRule.assertLogContains("The security token included in the request is invalid.", workflowRun);
	jenkinsRule.assertLogContains("Constructing AWS Credentials", workflowRun);
	jenkinsRule.assertLogContains("utilizing MFA Token", workflowRun);

}
 
Example #8
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testStepWithAWSFolderCredentials() throws Exception {

	String folderCredentialsId = "folders-aws-creds";

	// Create a folder with credentials in its store
	Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size());
	CredentialsStore folderStore = this.getFolderStore(folder);
	AmazonWebServicesCredentials amazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL,
			folderCredentialsId, "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description",
			"Arn::Something:or:Other", "12345678");
	folderStore.addCredentials(Domain.global(), amazonWebServicesCredentials);
	SystemCredentialsProvider.getInstance().save();

	List<String> credentialIds = new ArrayList<>();
	credentialIds.add(folderCredentialsId);

	WorkflowJob job = folder.createProject(WorkflowJob.class, "testStepWithAWSFolderCredentials");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  withAWS (credentials: '" + folderCredentialsId + "') {\n"
			+ "    echo 'It works!'\n"
			+ "  }\n"
			+ "}\n", true)
	);
	WorkflowRun workflowRun = job.scheduleBuild2(0).get();
	jenkinsRule.waitForCompletion(workflowRun);
	jenkinsRule.assertBuildStatus(Result.FAILURE, workflowRun);
	jenkinsRule.assertLogContains("The security token included in the request is invalid.", workflowRun);
	jenkinsRule.assertLogContains("Constructing AWS Credentials", workflowRun);

}
 
Example #9
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testStepWithGlobalAWSCredentials() throws Exception {

	String globalCredentialsId = "global-aws-creds";

	List<String> credentialIds = new ArrayList<>();
	credentialIds.add(globalCredentialsId);

	AmazonWebServicesCredentials amazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL,
			globalCredentialsId, "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description",
			"Arn::Something:or:Other", "12345678");

	SystemCredentialsProvider.getInstance().getCredentials().add(amazonWebServicesCredentials);
	SystemCredentialsProvider.getInstance().save();

	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithGlobalAWSCredentials");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  withAWS (credentials: '" + globalCredentialsId + "') {\n"
			+ "    echo 'It works!'\n"
			+ "  }\n"
			+ "}\n", true)
	);


	WorkflowRun workflowRun = job.scheduleBuild2(0).get();
	jenkinsRule.waitForCompletion(workflowRun);
	jenkinsRule.assertBuildStatus(Result.FAILURE, workflowRun);
	jenkinsRule.assertLogContains("The security token included in the request is invalid.", workflowRun);
}
 
Example #10
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private void withCredentials(@Nonnull Run<?, ?> run, @Nonnull EnvVars localEnv) throws IOException, InterruptedException {
	if (!StringUtils.isNullOrEmpty(this.step.getCredentials())) {
		StandardUsernamePasswordCredentials usernamePasswordCredentials = CredentialsProvider.findCredentialById(this.step.getCredentials(),
				StandardUsernamePasswordCredentials.class, run, Collections.emptyList());

		AmazonWebServicesCredentials amazonWebServicesCredentials = CredentialsProvider.findCredentialById(this.step.getCredentials(),
				AmazonWebServicesCredentials.class, run, Collections.emptyList());
		if (usernamePasswordCredentials != null) {
			localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, usernamePasswordCredentials.getUsername());
			localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, usernamePasswordCredentials.getPassword().getPlainText());
		} else if (amazonWebServicesCredentials != null) {
			AWSCredentials awsCredentials;

			if (StringUtils.isNullOrEmpty(this.step.getIamMfaToken())) {
				this.getContext().get(TaskListener.class).getLogger().format("Constructing AWS Credentials");
				awsCredentials = amazonWebServicesCredentials.getCredentials();
			} else {
				// Since the getCredentials does its own roleAssumption, this is all it takes to get credentials
				// with this token.
				this.getContext().get(TaskListener.class).getLogger().format("Constructing AWS Credentials utilizing MFA Token");
				awsCredentials = amazonWebServicesCredentials.getCredentials(this.step.getIamMfaToken());
				BasicSessionCredentials basicSessionCredentials = (BasicSessionCredentials) awsCredentials;
				localEnv.override(AWSClientFactory.AWS_SESSION_TOKEN, basicSessionCredentials.getSessionToken());
			}

			localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, awsCredentials.getAWSAccessKeyId());
			localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, awsCredentials.getAWSSecretKey());
		} else {
			throw new RuntimeException("Cannot find a Username with password credential with the ID " + this.step.getCredentials());
		}
	} else if (!StringUtils.isNullOrEmpty(this.step.getSamlAssertion())) {
		localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, "access_key_not_used_will_pass_through_SAML_assertion");
		localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, "secret_access_key_not_used_will_pass_through_SAML_assertion");
	}
	this.envVars.overrideAll(localEnv);
}
 
Example #11
Source File: EC2Api.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
public AmazonEC2 connect(final String awsCredentialsId, final String regionName, final String endpoint) {
    final AmazonWebServicesCredentials credentials = AWSCredentialsHelper.getCredentials(awsCredentialsId, Jenkins.getInstance());
    final AmazonEC2Client client =
            credentials != null ?
                    new AmazonEC2Client(credentials) :
                    new AmazonEC2Client();

    final String effectiveEndpoint = getEndpoint(regionName, endpoint);
    if (effectiveEndpoint != null) client.setEndpoint(effectiveEndpoint);
    return client;
}
 
Example #12
Source File: SQSTriggerQueue.java    From aws-codecommit-trigger-plugin with Apache License 2.0 5 votes vote down vote up
@CheckForNull
@Override
public AmazonWebServicesCredentials lookupAwsCredentials() {
    if (this.credentialsId == null) {
        return null;
    }
    return AwsCredentialsHelper.getCredentials(this.credentialsId);
}
 
Example #13
Source File: S3ItemStorage.java    From jobcacher-plugin with MIT License 4 votes vote down vote up
private AmazonWebServicesCredentials lookupCredentials() {
    return (credentialsId == null) ? null : CredentialsMatchers.firstOrNull(
            possibleCredentials(),
            CredentialsMatchers.withId(credentialsId));
}
 
Example #14
Source File: AwsCredentialsHelper.java    From aws-codecommit-trigger-plugin with Apache License 2.0 4 votes vote down vote up
@CheckForNull
public static AmazonWebServicesCredentials getCredentials(@Nullable String credentialsId) {
    return AwsCredentialsHelper.getCredentials(AmazonWebServicesCredentials.class, credentialsId);
}
 
Example #15
Source File: SQSTriggerQueue.java    From aws-codecommit-trigger-plugin with Apache License 2.0 4 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item context, @QueryParameter String credentialsId) {
    return new StandardListBoxModel()
        .includeEmptyValue()
        .includeAs(ACL.SYSTEM, context, AmazonWebServicesCredentials.class)
        .includeCurrentValue(credentialsId);
}
 
Example #16
Source File: ECSService.java    From amazon-ecs-plugin with MIT License 4 votes vote down vote up
@CheckForNull
private AmazonWebServicesCredentials getCredentials(@Nullable String credentialsId) {
    return AWSCredentialsHelper.getCredentials(credentialsId, Jenkins.get());
}
 
Example #17
Source File: S3Profile.java    From jobcacher-plugin with MIT License 4 votes vote down vote up
@DataBoundConstructor
public S3Profile(AmazonWebServicesCredentials credentials, Integer maxRetries, Long retryTime) {
    this.helper = new ClientHelper(credentials != null ? credentials.getCredentials() : null, getProxy());
    this.maxRetries = maxRetries != null ? maxRetries : 5;
    this.retryTime = retryTime != null ? retryTime : 5L;
}
 
Example #18
Source File: AWSEBDeploymentBuilder.java    From awseb-deployment-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@NonNull
protected String describe(@NonNull AmazonWebServicesCredentials c) {
    return CredentialsNameProvider.name(c);
}
 
Example #19
Source File: S3ItemStorage.java    From jobcacher-plugin with MIT License 4 votes vote down vote up
private static List<AmazonWebServicesCredentials> possibleCredentials() {
    return CredentialsProvider.lookupCredentials(AmazonWebServicesCredentials.class, Jenkins.getInstance(),
            ACL.SYSTEM, Collections.<DomainRequirement>emptyList());
}
 
Example #20
Source File: SQSQueue.java    From aws-codecommit-trigger-plugin with Apache License 2.0 votes vote down vote up
AmazonWebServicesCredentials lookupAwsCredentials();