Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 40 ยท Credentials, Plugins and Security

Credentials and Secrets

Store passwords, tokens and SSH keys safely in Jenkins, use them with withCredentials, and learn how log masking works and where it stops protecting you.

Almost every pipeline needs a secret: a registry password, a cloud token, a deploy key. The worst place for it is the Jenkinsfile, because that file lives in Git and is read by everyone with access to the repository. Jenkins solves this with a credentials store: you save the secret once, give it an ID, and the pipeline asks for it by that ID. The value is injected into the build only while a block runs, and Jenkins tries to hide it from the console log.

This lesson shows the credential kinds, how withCredentials and the credentials() helper work, how masking behaves, and the limits of that protection. The real Jenkins configuration is read-only here. The runnable stand-ins reproduce the masking idea so you can see what it catches and what slips through.

Credentials in four steps

Store Save it once in Jenkins.
Name Give it a stable ID.
Bind The pipeline asks for the ID.
Mask Jenkins hides the value in logs.

The Jenkinsfile only ever contains the ID.

1 / 2

Where credentials live

Open Manage Jenkins > Credentials. Credentials sit in a store inside a domain, and the store has a scope:

  • Global scope: usable by jobs, pipelines and agents anywhere in this Jenkins.
  • System scope: usable by Jenkins itself (for example for agent connections or email), not by pipelines.
  • Folder scope: a credential attached to a folder is visible only to jobs inside it. This is how you give the "payments" team its own secrets without exposing them to everyone.

Prefer the narrowest scope that works. A deploy key for one team's folder should not be a global credential that any pipeline can request.

Jenkins encrypts credentials on disk with keys kept in JENKINS_HOME/secrets. Anyone who can read that directory (or a backup of it) can decrypt them, so back it up as carefully as a password database. Backup, Monitoring and Troubleshooting returns to this.

The ID matters

When you create a credential, the ID is what pipelines reference. Choose a descriptive, stable one such as registry-creds or deploy-ssh-prod. If you leave it blank, Jenkins invents a random UUID that nobody can read in a Jenkinsfile. Renaming an ID later breaks every pipeline that mentions it.

Using credentials in a pipeline

The credentials() helper in an environment block is the shortest form. What it creates depends on the kind:

GROOVY
pipeline {
  agent any
  environment {
    API_TOKEN = credentials('shop-api-token')     // secret text
    REGISTRY  = credentials('registry-creds')     // username + password
  }
  stages {
    stage('Publish') {
      steps {
        sh 'curl -H "Authorization: Bearer $API_TOKEN" https://api.example.com/ping'
        sh 'echo "$REGISTRY_PSW" | docker login -u "$REGISTRY_USR" --password-stdin registry.example.com'
      }
    }
  }
}

For a secret text, API_TOKEN holds the value. For a username/password credential, Jenkins sets REGISTRY to user:password and also defines REGISTRY_USR and REGISTRY_PSW.

When you want the secret only for a few steps, use withCredentials, which has a clear start and end:

GROOVY
steps {
  withCredentials([
    string(credentialsId: 'shop-api-token', variable: 'API_TOKEN'),
    usernamePassword(credentialsId: 'registry-creds',
                     usernameVariable: 'REG_USER', passwordVariable: 'REG_PASS'),
    file(credentialsId: 'kubeconfig-staging', variable: 'KUBECONFIG'),
    sshUserPrivateKey(credentialsId: 'deploy-ssh-prod',
                      keyFileVariable: 'SSH_KEY', usernameVariable: 'SSH_USER')
  ]) {
    sh 'kubectl --kubeconfig "$KUBECONFIG" get pods'
    sh 'ssh -i "$SSH_KEY" "$SSH_USER"@deploy.example.com uptime'
  }
}

Notes:

  • file writes the secret file to a temporary path on the agent and puts that path in the variable. It is deleted when the block ends.
  • sshUserPrivateKey does the same for a private key; you pass the file path to ssh -i.
  • The Git steps accept a credentialsId directly, for example git url: '...', credentialsId: 'github-deploy-key', so you often never need withCredentials for checkout.

Use single quotes with shell steps

Compare these two lines:

GROOVY
sh "docker login -p $REG_PASS ..."   // Groovy interpolates the secret into the command text
sh 'docker login -p "$REG_PASS" ...' // the shell reads the environment variable

With double quotes, Groovy puts the secret into the command string itself, where it may end up in logs or in the process list. Jenkins even warns about this ("A secret was passed to sh using Groovy String interpolation"). Single quotes keep the secret in the environment, where masking and process isolation do a better job.

How masking works

While a credentials block runs, Jenkins knows the secret values. It filters the build log as it is written and replaces each occurrence of a bound secret with ****. That is helpful and also easy to misunderstand. Masking is a string replacement on the log output, nothing more. It does not stop the build from using or exposing the value in other ways.

The stand-in below mimics the masking filter: it knows a list of secrets and rewrites each log line before showing it.

JS Stand-in: a log filter that masks bound secrets

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both secrets appear as ****, and lines without a secret are untouched. Note one design detail: longer secrets are replaced first, so a short secret that happens to be a piece of a longer one cannot leave a readable remainder.

Where masking fails

Masking only recognizes the exact bytes Jenkins was told about. Anything that transforms the secret defeats it.

JS Stand-in: what the masker does not catch

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Only the plain line is hidden. Base64, reversed, split and hex forms pass straight through, and so would a secret printed one character per line. Real pipelines hit this in practice: base64-encoded Kubernetes secrets, JSON files that contain a token, or set -x tracing that prints a derived value. Masking is a seat belt, not a vault.

Other limits to keep in mind:

  • Anyone who can edit the Jenkinsfile (or a pull request that Jenkins builds) can write sh 'echo $API_TOKEN | base64' and read the result. Credential use must be controlled by who may change pipelines, not only by masking.
  • Short or common values (like ci or 1234) get masked everywhere, which makes logs confusing, and they are weak secrets anyway.
  • Environment variables are visible to every process in the block, including the build tools and tests you run.
  • Do not turn on set -x in a shell step that holds a secret.

Review changes to Jenkinsfiles in pull requests with the same care as changes to production code. In multibranch setups, consider who may add credentials-using code from a fork; Multibranch Pipelines and Pull Requests explains the trust options.

Beyond the built-in store

For larger setups, secrets move out of Jenkins' own disk and into a dedicated manager. A plugin fetches the value at build time and exposes it through the same withCredentials style:

  • HashiCorp Vault, AWS Secrets Manager, Azure Key Vault and Google Secret Manager each have a Jenkins plugin or a documented pattern.
  • Secrets can have short lifetimes and be rotated without touching Jenkins.
  • Access is logged in the secret manager, which gives you an audit trail.

An even better pattern for cloud deployments is no long-lived secret at all: the agent assumes a cloud role, or the pipeline requests a short-lived token that expires in minutes. A leaked token is then much less valuable. Plan for rotation either way: when someone leaves the team or a log leak is suspected, you should be able to replace the credential in one place.

Good habits

  • Store each secret once, in the narrowest scope, with a clear ID.
  • Never put a secret in a Jenkinsfile, a job parameter default or an image ARG (Docker Agents and Building Images covers BuildKit secrets).
  • Use least privilege: a token that can only push to one registry repository beats an admin token.
  • Use string parameters of type password only for human-entered values, and remember they are not encrypted at rest as strongly as the credential store.
  • Rotate regularly and after any suspicion of exposure.
  • Restrict who may view and configure credentials with authorization.

What is real and what is the stand-in

The credentials() and withCredentials syntax above is the real Pipeline syntax, but it is not executed here because there is no Jenkins and no credential store on this page. The two TryIt blocks are plain JavaScript stand-ins that mimic the masking idea: Jenkins' real implementation is a log filter inside the build, and its exact behavior (for example how it handles multi-line secrets) is described in the official documentation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a Jenkinsfile contain when it uses a stored credential?

    The pipeline references the credential by ID. Jenkins resolves the value at run time, so the repository never holds the secret.
  2. 2. Why is sh 'login -p "$PASS"' safer than sh "login -p $PASS"?

    Groovy interpolation inserts the value into the command string, where it can leak into logs and process lists. With single quotes the value stays in the environment.
  3. 3. A build prints the Base64 form of a bound secret. What happens?

    Masking is a literal string replacement. Encoded or split versions of the secret do not match.
  4. 4. Which scope lets you share a credential with only one team's jobs?

    A credential attached to a folder is visible only to jobs inside that folder. Global credentials are available everywhere, and system credentials are for Jenkins itself.

Summary

  • Secrets belong in the Jenkins credentials store (or an external manager), referenced by ID, never in the Jenkinsfile.
  • Kinds include secret text, username/password, SSH key and secret file; use credentials() for simple cases and withCredentials for narrow blocks.
  • Use folder scope to limit who can use a secret, and single quotes in shell steps so Groovy does not interpolate it.
  • Masking replaces the exact secret text with **** in logs. It does not catch encoded or split values and does not stop a pipeline author from exfiltrating a secret.
  • Prefer short-lived tokens and external secret managers, and rotate on exposure.

Credentials are only as safe as the plugins and permissions around them. Continue with Plugins: Finding, Managing and Pinning.