Jenkins cheatsheet

Jenkins: Steps and credentials

7 common Jenkins tasks.

Use credentials safely

Bind a stored secret to a variable for a block. Jenkins masks the value in the log.

withCredentials([string(credentialsId: 'api-token', variable: 'API_TOKEN')]) {
  sh 'curl -H "Authorization: Bearer $API_TOKEN" https://api.example.com/deploy'
}

Bind credentials in environment

Expose a username and password credential as environment variables.

environment {
  REGISTRY = credentials('docker-registry')   // sets REGISTRY_USR and REGISTRY_PSW
}

Save build artifacts

Keep files from the workspace with the build, with a fingerprint.

archiveArtifacts artifacts: 'dist/**', fingerprint: true

Publish test results

Parse JUnit XML reports so test results show in Jenkins.

post {
  always { junit 'reports/**/*.xml' }
}

Pass files between stages or agents

Save files in one stage and restore them in another, even on a different agent.

stash name: 'build', includes: 'dist/**'
// later, in another stage
unstash 'build'

Wait for approval

Pause the pipeline until someone approves.

input message: 'Deploy to production?', ok: 'Deploy'

Retry and time-limit a step

Retry a flaky step and give up if it takes too long.

retry(3) {
  timeout(time: 5, unit: 'MINUTES') {
    sh './flaky-integration-test.sh'
  }
}

Was this page helpful?