Java Code Examples for com.cloudbees.plugins.credentials.CredentialsStore#addCredentials()

The following examples show how to use com.cloudbees.plugins.credentials.CredentialsStore#addCredentials() . 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: MarathonRecorderTest.java    From marathon-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Test that a JSON credential without a "jenkins_token" field and without a proper DC/OS service account value
 * results in a 401 and only 1 web request.
 *
 * @throws Exception
 */
@Test
public void testRecorderInvalidToken() throws Exception {
    final FreeStyleProject                       project         = j.createFreeStyleProject();
    final SystemCredentialsProvider.ProviderImpl system          = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
    final CredentialsStore                       systemStore     = system.getStore(j.getInstance());
    final String                                 credentialValue = "{\"field1\":\"some value\"}";
    final Secret                                 secret          = Secret.fromString(credentialValue);
    final StringCredentials                      credential      = new StringCredentialsImpl(CredentialsScope.GLOBAL, "invalidtoken", "a token for JSON token test", secret);
    TestUtils.enqueueFailureResponse(httpServer, 401);

    systemStore.addCredentials(Domain.global(), credential);

    addBuilders(TestUtils.loadFixture("idonly.json"), project);

    // add post-builder
    addPostBuilders(project, "invalidtoken");

    final FreeStyleBuild build = j.assertBuildStatus(Result.FAILURE, project.scheduleBuild2(0).get());
    j.assertLogContains("[Marathon] Authentication to Marathon instance failed:", build);
    j.assertLogContains("[Marathon] Invalid DC/OS service account JSON", build);
    assertEquals("Only 1 request should have been made.", 1, httpServer.getRequestCount());
}
 
Example 2
Source File: CredentialsUtils.java    From blueocean-plugin with MIT License 6 votes vote down vote up
public static void createCredentialsInUserStore(@Nonnull Credentials credential, @Nonnull User user,
                                                @Nonnull String domainName, @Nonnull List<DomainSpecification> domainSpecifications)
        throws IOException {
    CredentialsStore store= findUserStoreFirstOrNull(user);

    if(store == null){
        throw new ServiceException.ForbiddenException(String.format("Logged in user: %s doesn't have writable credentials store", user.getId()));
    }

    Domain domain = findOrCreateDomain(store, domainName, domainSpecifications);

    if(!store.addCredentials(domain, credential)){
        throw new ServiceException.UnexpectedErrorException("Failed to add credential to domain");
    }

}
 
Example 3
Source File: CredentialApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void listAllCredentials() throws IOException {
    SystemCredentialsProvider.ProviderImpl system = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
    CredentialsStore systemStore = system.getStore(j.getInstance());
    systemStore.addDomain(new Domain("domain1", null, null));
    systemStore.addDomain(new Domain("domain2", null, null));
    systemStore.addCredentials(systemStore.getDomainByName("domain1"), new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null,null, "admin", "pass$wd"));
    systemStore.addCredentials(systemStore.getDomainByName("domain2"), new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null,null, "joe", "pass$wd"));

    CredentialsStoreAction credentialsStoreAction = ExtensionList.lookup(ViewCredentialsAction.class).get(0).getStore("system");
    CredentialsStoreAction.DomainWrapper domain1 = credentialsStoreAction.getDomain("domain1");
    CredentialsStoreAction.DomainWrapper domain2 = credentialsStoreAction.getDomain("domain2");

    CredentialsStoreAction.CredentialsWrapper credentials1 = domain1.getCredentialsList().get(0);
    CredentialsStoreAction.CredentialsWrapper credentials2 = domain2.getCredentialsList().get(0);
    List<Map>  creds = get("/search?q=type:credential;organization:jenkins", List.class);
    Assert.assertEquals(2, creds.size());
    Assert.assertEquals(credentials1.getId(), creds.get(0).get("id"));
    Assert.assertEquals(credentials2.getId(), creds.get(1).get("id"));

    creds = get("/search?q=type:credential;organization:jenkins;domain:domain2", List.class);
    Assert.assertEquals(1, creds.size());
    Assert.assertEquals(credentials2.getId(), creds.get(0).get("id"));
}
 
Example 4
Source File: GitLabConnectionConfigTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
    gitLabUrl = "http://localhost:" + mockServer.getPort() + "/gitlab";
    for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
            List<Domain> domains = credentialsStore.getDomains();
            credentialsStore.addCredentials(domains.get(0),
                new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN)));
        }
    }
}
 
Example 5
Source File: GitLabRule.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
public GitLabConnectionProperty createGitLabConnectionProperty() throws IOException {
    for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
            List<Domain> domains = credentialsStore.getDomains();
            credentialsStore.addCredentials(domains.get(0),
                new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(getApiToken())));
        }
    }

    GitLabConnectionConfig config = Jenkins.getInstance().getDescriptorByType(GitLabConnectionConfig.class);
    GitLabConnection connection = new GitLabConnection("test", url, API_TOKEN_ID, new V3GitLabClientBuilder(), true,10, 10);
    config.addConnection(connection);
    config.save();
    return new GitLabConnectionProperty(connection.getName());
}
 
Example 6
Source File: MarathonRecorderTest.java    From marathon-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Test that a JSON credential with "jenkins_token" uses the token value as the authentication token.
 *
 * @throws Exception
 */
@Test
public void testRecorderJSONToken() throws Exception {
    final FreeStyleProject                       project         = j.createFreeStyleProject();
    final String                                 responseStr     = "{\"version\": \"one\", \"deploymentId\": \"someid-here\"}";
    final SystemCredentialsProvider.ProviderImpl system          = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
    final CredentialsStore                       systemStore     = system.getStore(j.getInstance());
    final String                                 tokenValue      = "my secret token";
    final String                                 credentialValue = "{\"field1\":\"some value\", \"jenkins_token\":\"" + tokenValue + "\"}";
    final Secret                                 secret          = Secret.fromString(credentialValue);
    final StringCredentials                      credential      = new StringCredentialsImpl(CredentialsScope.GLOBAL, "jsontoken", "a token for JSON token test", secret);
    TestUtils.enqueueJsonResponse(httpServer, responseStr);
    systemStore.addCredentials(Domain.global(), credential);

    // add builders
    addBuilders(TestUtils.loadFixture("idonly.json"), project);

    // add post-builder
    addPostBuilders(project, "jsontoken");

    final FreeStyleBuild build = j.assertBuildStatusSuccess(project.scheduleBuild2(0).get());
    j.assertLogContains("[Marathon]", build);

    // handler assertions
    assertEquals("Only 1 request should be made", 1, httpServer.getRequestCount());
    RecordedRequest request           = httpServer.takeRequest();
    final String    authorizationText = request.getHeader("Authorization");
    assertEquals("Token does not match", "token=" + tokenValue, authorizationText);
}
 
Example 7
Source File: MarathonRecorderTest.java    From marathon-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Test a basic API token using StringCredentials.
 *
 * @throws Exception
 */
@Test
public void testRecorderBasicToken() throws Exception {
    final FreeStyleProject                       project     = j.createFreeStyleProject();
    final String                                 responseStr = "{\"version\": \"one\", \"deploymentId\": \"someid-here\"}";
    final SystemCredentialsProvider.ProviderImpl system      = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
    final CredentialsStore                       systemStore = system.getStore(j.getInstance());
    final String                                 tokenValue  = "my secret token";
    final Secret                                 secret      = Secret.fromString(tokenValue);
    final StringCredentials                      credential  = new StringCredentialsImpl(CredentialsScope.GLOBAL, "basictoken", "a token for basic token test", secret);
    TestUtils.enqueueJsonResponse(httpServer, responseStr);
    systemStore.addCredentials(Domain.global(), credential);

    // add builders
    addBuilders(TestUtils.loadFixture("idonly.json"), project);
    // add post-builder
    addPostBuilders(project, "basictoken");

    final FreeStyleBuild build = j.assertBuildStatusSuccess(project.scheduleBuild2(0).get());
    j.assertLogContains("[Marathon]", build);

    // handler assertions
    assertEquals("Only 1 request should be made", 1, httpServer.getRequestCount());
    RecordedRequest request = httpServer.takeRequest();

    final String authorizationText = request.getHeader("Authorization");
    assertEquals("Token does not match", "token=" + tokenValue, authorizationText);
}
 
Example 8
Source File: GitLabConnectionConfigSSLTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
    for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
            List<Domain> domains = credentialsStore.getDomains();
            credentialsStore.addCredentials(domains.get(0),
                new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN_ID)));
        }
    }
}
 
Example 9
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 10
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testListCredentials() throws Exception {
	Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size());
	CredentialsStore folderStore = this.getFolderStore(folder);
	StandardUsernamePasswordCredentials folderCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
			"folder-creds", "test-creds", "aws-access-key-id", "aws-secret-access-key");
	StandardUsernamePasswordCredentials globalCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
			"global-creds", "test-creds", "aws-access-key-id", "aws-secret-access-key");

	folderStore.addCredentials(Domain.global(), folderCredentials);
	SystemCredentialsProvider.getInstance().getCredentials().add(globalCredentials);
	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 11
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 12
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 13
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testStepWithFolderCredentials() 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);
	StandardUsernamePasswordCredentials inFolderCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
																								  folderCredentialsId, "test-folder-creds", "folder-aws-access-key-id", "folder-aws-secret-access-key");
	folderStore.addCredentials(Domain.global(), inFolderCredentials);
	SystemCredentialsProvider.getInstance().save();

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

	WorkflowJob job = folder.createProject(WorkflowJob.class, "testStepWithFolderCredentials");
	job.setDefinition(new CpsFlowDefinition(""
													+ "node {\n"
													+ "  withAWS (credentials: '" + folderCredentialsId + "') {\n"
													+ "    echo 'It works!'\n"
													+ "  }\n"
													+ "}\n", true)
	);
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

}
 
Example 14
Source File: CredentialApiTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void listCredentials() throws IOException {
    SystemCredentialsProvider.ProviderImpl system = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
    CredentialsStore systemStore = system.getStore(j.getInstance());
    systemStore.addDomain(new Domain("domain1", null, null));
    systemStore.addCredentials(systemStore.getDomainByName("domain1"), new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null,null, "admin", "pass$wd"));


    CredentialsStoreAction credentialsStoreAction = ExtensionList.lookup(ViewCredentialsAction.class).get(0).getStore("system");
    CredentialsStoreAction.DomainWrapper domainWrapper = credentialsStoreAction.getDomain("domain1");
    CredentialsStoreAction.CredentialsWrapper credentialsWrapper = domainWrapper.getCredentialsList().get(0);


    List<Map>  creds = get("/organizations/jenkins/credentials/system/domains/domain1/credentials/", List.class);
    Assert.assertEquals(1, creds.size());
    Map cred = creds.get(0);
    Assert.assertNotNull(cred.get("id"));

    Map cred1 = get("/organizations/jenkins/credentials/system/domains/domain1/credentials/"+cred.get("id")+"/");

    Assert.assertEquals(credentialsWrapper.getId(),cred1.get("id"));
    Assert.assertEquals(credentialsWrapper.getTypeName(),cred1.get("typeName"));
    Assert.assertEquals(credentialsWrapper.getDisplayName(),cred1.get("displayName"));
    Assert.assertEquals(credentialsWrapper.getFullName(),cred1.get("fullName"));
    Assert.assertEquals(String.format("%s:%s:%s", credentialsWrapper.getDisplayName(), credentialsWrapper.getDomain().getUrlName(), credentialsWrapper.getTypeName()),cred1.get("description"));
    Assert.assertEquals(credentialsWrapper.getDomain().getUrlName(),cred1.get("domain"));
}
 
Example 15
Source File: TestUtility.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
static void addGitLabApiToken() throws IOException {
    for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
            List<Domain> domains = credentialsStore.getDomains();
            credentialsStore.addCredentials(domains.get(0),
                new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN)));
        }
    }
}
 
Example 16
Source File: JiraCloudSiteConfigDescriptorTest.java    From atlassian-jira-software-cloud-plugin with Apache License 2.0 5 votes vote down vote up
private void setupCredentials(String credentialId, String secret) throws Exception {
    final CredentialsStore credentialsStore =
            CredentialsProvider.lookupStores(jRule.jenkins).iterator().next();
    final Domain domain = Domain.global();
    final Credentials credentials =
            new StringCredentialsImpl(
                    CredentialsScope.GLOBAL, credentialId, "", Secret.fromString(secret));
    credentialsStore.addCredentials(domain, credentials);
}
 
Example 17
Source File: DockerBuildImageStepTest.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
@Test
    public void testBuild() throws Throwable {
        jRule.getInstance().setNumExecutors(0);
//        jRule.createSlave();
//        jRule.createSlave("my-slave", "remote-slave", new EnvVars());
        final UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM,
                null, "description", "vagrant", "vagrant");

        CredentialsStore store = CredentialsProvider.lookupStores(jRule.getInstance()).iterator().next();
        store.addCredentials(Domain.global(), credentials);

        final SSHLauncher sshLauncher = new SSHLauncher("192.168.33.10", 22, credentials.getId(),
                "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", //jvmopts
                "", //      String javaPath,
                "",  //      String prefixStartSlaveCmd,
                "", //      String suffixStartSlaveCmd,
                20, //      Integer launchTimeoutSeconds,
                1, //      Integer maxNumRetries,
                3,//      Integer retryWaitTime
                new NonVerifyingKeyVerificationStrategy()
        );
        final DumbSlave dumbSlave = new DumbSlave("docker-daemon", "/home/vagrant/jenkins2", sshLauncher);
        jRule.getInstance().addNode(dumbSlave);
        await().timeout(60, SECONDS).until(() -> assertThat(dumbSlave.getChannel(), notNullValue()));
        String dockerfilePath = dumbSlave.getChannel().call(new StringThrowableCallable());


        final CredentialsYADockerConnector dockerConnector = new CredentialsYADockerConnector()
                .withConnectorType(JERSEY)
                .withServerUrl("tcp://127.0.0.1:2376")
                .withSslConfig(new LocalDirectorySSLConfig("/home/vagrant/keys"))
                ;
//                .withCredentials(new DockerDaemonFileCredentials(null, "docker-cert", "",
//                        "/home/vagrant/keys"));

        DockerBuildImage buildImage = new DockerBuildImage();
        buildImage.setBaseDirectory(dockerfilePath);
        buildImage.setPull(true);
        buildImage.setNoCache(true);

        DockerBuildImageStep dockerBuildImageStep = new DockerBuildImageStep(dockerConnector, buildImage);

        FreeStyleProject project = jRule.createFreeStyleProject("test");
        project.getBuildersList().add(dockerBuildImageStep);

        project.save();

        QueueTaskFuture<FreeStyleBuild> taskFuture = project.scheduleBuild2(0);
        FreeStyleBuild freeStyleBuild = taskFuture.get();
        jRule.waitForCompletion(freeStyleBuild);
        jRule.assertBuildStatusSuccess(freeStyleBuild);
    }
 
Example 18
Source File: TestUtils.java    From phabricator-jenkins-plugin with MIT License 4 votes vote down vote up
private static void addCredentials(ConduitCredentials credentials) throws IOException {
    CredentialsStore store = new SystemCredentialsProvider.UserFacingAction().getStore();
    store.addCredentials(Domain.global(), credentials);
}
 
Example 19
Source File: DockerShellStepIT.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
@Test
    public void testDockerShellStep() throws Throwable {
        jRule.getInstance().setNumExecutors(0);
//        jRule.createSlave();
//        jRule.createSlave("my-slave", "remote-slave", new EnvVars());
        final UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM,
                null, "description", "vagrant", "vagrant");

        CredentialsStore store = CredentialsProvider.lookupStores(jRule.getInstance()).iterator().next();
        store.addCredentials(Domain.global(), credentials);

        final SSHLauncher sshLauncher = new SSHLauncher("192.168.33.10", 22, credentials.getId(),
                "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", //jvmopts
                "", //      String javaPath,
                "",  //      String prefixStartSlaveCmd,
                "", //      String suffixStartSlaveCmd,
                20, //      Integer launchTimeoutSeconds,
                1, //      Integer maxNumRetries,
                3,//      Integer retryWaitTime
                new NonVerifyingKeyVerificationStrategy()
        );
        final DumbSlave dumbSlave = new DumbSlave("docker-daemon", "/home/vagrant/jenkins2", sshLauncher);
        jRule.getInstance().addNode(dumbSlave);
        await().timeout(60, SECONDS).until(() -> assertThat(dumbSlave.getChannel(), notNullValue()));
//        String dockerfilePath = dumbSlave.getChannel().call(new DockerBuildImageStepTest.StringThrowableCallable());


        final CredentialsYADockerConnector dockerConnector = new CredentialsYADockerConnector()
                .withConnectorType(JERSEY)
                .withServerUrl("tcp://127.0.0.1:2376")
                .withSslConfig(new LocalDirectorySSLConfig("/home/vagrant/keys"));
//                .withCredentials(new DockerDaemonFileCredentials(null, "docker-cert", "",
//                        "/home/vagrant/keys"));

        DockerShellStep dockerShellStep = new DockerShellStep();
        dockerShellStep.setShellScript("env && pwd");
        dockerShellStep.setConnector(dockerConnector);

        FreeStyleProject project = jRule.createFreeStyleProject("test");
        project.getBuildersList().add(dockerShellStep);

        project.save();

        QueueTaskFuture<FreeStyleBuild> taskFuture = project.scheduleBuild2(0);
        FreeStyleBuild freeStyleBuild = taskFuture.get();

        jRule.waitForCompletion(freeStyleBuild);

        jRule.assertBuildStatusSuccess(freeStyleBuild);
    }
 
Example 20
Source File: DockerImageComboStepTest.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
@Ignore
    @Test
    public void testComboBuild() throws Throwable {
        jRule.getInstance().setNumExecutors(0);
//        jRule.createSlave();
//        jRule.createSlave("my-slave", "remote-slave", new EnvVars());
        final UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM,
                null, "description", "vagrant", "vagrant");

        CredentialsStore store = CredentialsProvider.lookupStores(jRule.getInstance()).iterator().next();
        store.addCredentials(Domain.global(), credentials);

        final SSHLauncher sshLauncher = new SSHLauncher("192.168.33.10", 22, credentials.getId(),
                "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", //jvmopts
                "", //      String javaPath,
                "",  //      String prefixStartSlaveCmd,
                "", //      String suffixStartSlaveCmd,
                20, //      Integer launchTimeoutSeconds,
                1, //      Integer maxNumRetries,
                3,//      Integer retryWaitTime
                new NonVerifyingKeyVerificationStrategy()
        );
        final DumbSlave dumbSlave = new DumbSlave("docker-daemon", "/home/vagrant/jenkins2", sshLauncher);
        jRule.getInstance().addNode(dumbSlave);
        await().timeout(60, SECONDS).until(() -> assertThat(dumbSlave.getChannel(), notNullValue()));
        String dockerfilePath = dumbSlave.getChannel().call(new StringThrowableCallable());


        final CredentialsYADockerConnector dockerConnector = new CredentialsYADockerConnector()
                .withConnectorType(JERSEY)
                .withServerUrl("tcp://127.0.0.1:2376")
                .withSslConfig(new LocalDirectorySSLConfig("/home/vagrant/keys"));
//                .withCredentials(new DockerDaemonFileCredentials(null, "docker-cert", "",
//                        "/home/vagrant/keys"));

        DockerBuildImage buildImage = new DockerBuildImage();
        buildImage.setBaseDirectory(dockerfilePath);
        buildImage.setPull(true);
        buildImage.setTags(Collections.singletonList("localhost:5000/myfirstimage"));

        DockerImageComboStep comboStep = new DockerImageComboStep(dockerConnector, buildImage);
        comboStep.setClean(true);
        comboStep.setCleanupDangling(true);
        comboStep.setPush(true);

        FreeStyleProject project = jRule.createFreeStyleProject("test");
        project.getBuildersList().add(comboStep);

        project.save();

        QueueTaskFuture<FreeStyleBuild> taskFuture = project.scheduleBuild2(0);
        FreeStyleBuild freeStyleBuild = taskFuture.get();
        jRule.waitForCompletion(freeStyleBuild);
        jRule.assertBuildStatusSuccess(freeStyleBuild);
    }