Search code examples
jenkinsjenkins-pipeline

How do I define Credentials as params in Jenkinsfile scripted pipeline


I am defining a scripted pipeline with many inputs, 2 of them are credentials. In the UI I can see how to add an input that is a credential, but I can't find anything on how to define Credential Params for scripted Pipelines. My params are defined like:

properties([
  buildDiscarder(logRotator(numToKeepStr: '20')),
  parameters([
     stringParam(name: 'export_credentials'),
     stringParam(name: 'import_credentials'),
  ]),
])

But I'd prefer it to be actual credentials params and not string ones


Solution

  • I figured it out after exploring the job-dsl plugin API (<jenkins_url>/plugin/job-dsl/api-viewer/index.htm):

    properties([
      buildDiscarder(logRotator(numToKeepStr: '20')),
      disableResume(),
      parameters([
         credentials(name: 'export_token_credential_id', required: true, credentialType: "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl", defaultValue: 'dockerjenkins-token', description: 'Username and API Token for the Jenkins to migrate from'),
         credentials(name: 'import_token_credential_id', required: true, credentialType: "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl", defaultValue: 'cloudbees-token', description: 'Username and API Token for this Jenkins'),
         stringParam(name: 'item', description: 'Item (job) to migrate. '),
         choiceParam(name: 'disable_mode', choices: "NEITHER\nDEST\nSOURCE\nBOTH", description: 'Which Jenkins, if any, to disable jobs on when migrating'),
      ]),
    ])