Skip to main content
In this guide, we’ll walk through refactoring a Jenkins pipeline to:
  • Simplify credential handling
  • Remove duplicate withCredentials blocks
  • Centralize test report and HTML publishing in a post section
This approach reduces boilerplate and improves maintainability of your Jenkinsfile.

Original Jenkinsfile Snippet

Both the Unit Testing and Code Coverage stages currently use identical withCredentials wrappers:

1. Injecting Credentials via environment

Instead of wrapping every stage in withCredentials, Jenkins can populate environment variables automatically:
The image shows a webpage from the Jenkins documentation, specifically focusing on using a Jenkinsfile with credential environment variables. It includes code snippets and explanations about handling credentials in a Jenkins pipeline.

Define a Single Credential

You can echo these variables to confirm that Jenkins injects them correctly, but remember that secrets remain masked in logs.

2. Why the Stage Fails

After pushing, the build fails:
The image shows a Jenkins pipeline interface with a visual representation of a build process, highlighting a failed unit testing step. It includes details of the steps executed and their status.
Although the variables are injected:
  • $MONGO_DB_CREDS is masked
  • $MONGO_DB_CREDS_USR is displayed
  • $MONGO_DB_CREDS_PSW is masked
Your test suite still expects MONGO_USERNAME and MONGO_PASSWORD, so the stage cannot authenticate.

3. Defining Separate Secret-Text Credentials

To match your test code, split the single credential into two Secret text entries:
  1. In Jenkins UI, go to Credentials > Global.
  2. Add Secret text credentials:
    • ID: mongo-db-usernameMongoDB username
    • ID: mongo-db-passwordMongoDB password
The image shows a Jenkins interface displaying a list of global credentials, including Gitea server and MongoDB credentials, with options to add or edit them.
  1. Update the environment block accordingly:

4. Centralizing Reports in post { always { ... } }

Rather than repeating junit and publishHTML in each stage, use a post block to archive all reports after every build:
Don’t forget to adjust testResults patterns if you rename or relocate report files—otherwise Jenkins may skip them.

5. Run the Refactored Pipeline

With credentials injected at the top and reports centralized, the build should now succeed:

Final Full Example


Watch Video