In the previous lesson you centralized the values that were repeated in the orders-api Jenkinsfile into environment variables, and you finished with a warning: some values must never be written in a Jenkinsfile, in a plain-text variable or in a job's visible configuration. Passwords, API tokens, SSH keys and certificates are secrets: whoever gets hold of them can act on TecnoShop's behalf. You have not needed them so far because the repositories were public and there were no real services, but that changes now. In this lesson you will learn how Jenkins stores secrets with the Credentials plugin and which types, scopes and domains exist; you will make the orders-api repository private and create the github-tecnoshop credential with a least-privilege GitHub token; and you will see how to use secrets in a pipeline with credentials() and withCredentials without exposing them: what Jenkins masks, what it does not, and why Groovy interpolation is the most common mistake.
Before you start: the examples in this lesson use fictitious values. In a real environment, always check your organization's security policy (which secrets manager is used, who may create tokens, expiration periods) before creating or storing any credential.
Why Secrets Do Not Belong in the Jenkinsfile
Imagine Diego writes this to check the Nexus server:
The password ends up:
- In the Git repository, forever: even if you delete it in the next commit, it is still in the history, and anyone with read access can see it (or the whole world, if the repository is public).
- In the console of every build, which all users with read permission on the job can read.
- In every copy made of the repository, in forks and on the laptops of the entire team.
The solution is to separate the secret (stored encrypted in Jenkins) from its use (the Jenkinsfile only mentions an identifier, such as nexus-deployer). The Jenkinsfile can be public; the secret cannot.
The Credentials Plugin: Where and How Secrets Are Stored
The Credentials plugin (installed with the suggested plugins) stores Jenkins' secrets. Together with Credentials Binding, which provides withCredentials, and Plain Credentials, which provides the text and file types, it makes up the credentials system.
- Global credentials are stored in
$JENKINS_HOME/credentials.xml(folder credentials in the folder'sconfig.xml), encrypted. - The encryption key lives in
$JENKINS_HOME/secrets/(master.keyandhudson.util.Secret). Without those files,credentials.xmlis unreadable; with them, anyone can decrypt it. That is why you will protectsecrets/with particular care in Backing Up and Restoring Jenkins. - From the interface, once saved, the secret is never shown again: it can only be replaced.
To manage them: Manage Jenkins → Credentials. You will see a table of stores and domains; the main store is System and its default domain is Global credentials (unrestricted).
Credential Types
When you click Add Credentials, the Kind field offers these types:
| Type (Kind) | What it contains | Typical use | withCredentials binding |
|---|---|---|---|
| Username with password | Username + password (or token) | Git over HTTPS, Nexus, Docker registries | usernamePassword |
| Secret text | A secret string | API tokens (Slack, SonarQube) | string |
| Secret file | A whole file | kubeconfig, Maven settings.xml, key files |
file |
| SSH Username with private key | Username + private key (+ optional passphrase) | Git over SSH, SSH deployments | sshUserPrivateKey |
| Certificate | PKCS#12 keystore + password | Client certificate authentication | certificate |
| GitHub App | ID and key of a GitHub App | Advanced GitHub integration | Covered in 06-01 |
In addition to Kind, all credentials share these fields:
- Scope: the scope (next section).
- ID: the identifier the
Jenkinsfiles will use. If you leave it empty, Jenkins generates an unreadable UUID. Always fill it in, with a clear, stable name:nexus-deployer, notcred1. - Description: what it is for, who manages it and when it expires. Whoever inherits it will be grateful.
Scopes: System and Global
| Scope | Who can use it | Examples |
|---|---|---|
| Global | Jobs and pipelines (and Jenkins itself) | github-tecnoshop, nexus-deployer |
| System | Only Jenkins, for its own configuration; jobs cannot see it | Credential for connecting agents over SSH (05-01), mail server |
If only Jenkins needs a credential to function, mark it as System: that way no pipeline can use it, and therefore none can leak it.
Domains and Folder Credentials
Domains group credentials and can restrict them to certain destinations through specifications (hostname, URL scheme). For example, a GitHub domain with the hostname specification github.com makes the configuration drop-down lists offer those credentials only for GitHub URLs. It is an organizational aid, not a strong security barrier: a pipeline that knows the ID can use the credential anyway. In small installations, like the one in this course, Global credentials (unrestricted) is enough.
The real barrier is the folder store: if you create a folder (for example, catalog-team), a Credentials entry appears in its menu, and the credentials stored there can be used only by the jobs in that folder. That is how the catalog team can have its own secrets without other teams' jobs being able to use them.
flowchart TD
J["Jenkins"] --> SG["System store<br/>Global domain"]
SG --> C1["github-tecnoshop (Global)"]
SG --> C2["nexus-deployer (Global)"]
SG --> C3["ssh-agents (System)<br/>Jenkins only"]
J --> F["catalog-team folder"]
F --> FC["Folder store"]
FC --> C4["catalog-cdn<br/>folder jobs only"]
TecnoShop keeps its jobs at the root, as we decided in 02-02, so it will use the global store. Keep folders in mind as the installation grows.
Hands-On: Private Repository and the github-tecnoshop Credential
At TecnoShop, the code is not public. You are going to reproduce that with your repository.
Step 1: Make the Repository Private
On GitHub, in <your-username>/orders-api: Settings → General, at the bottom of the page, Danger Zone → Change repository visibility → Make private. Do the same with catalog-web.
Now run orders-api-pipeline. The build fails before running any stage, when it tries to read the Jenkinsfile, with an error similar to:
ERROR: Error fetching remote repo 'origin' ... fatal: could not read Username for 'https://github.com': No such device or address
Git tries to prompt for a username, but in Jenkins there is nobody there to type it.
Step 2: Create a Least-Privilege GitHub Token
Jenkins needs to read the code, nothing more. GitHub offers fine-grained personal access tokens, which let you restrict a token to specific repositories and permissions:
- On GitHub: your avatar → Settings → Developer settings → Personal access tokens → Fine-grained tokens → Generate new token.
- Fill in:
| Field | Value | Why |
|---|---|---|
| Token name | jenkins-tecnoshop |
To know what it is for when you review it |
| Expiration | 90 days | Forces you to rotate it; never "no expiration" |
| Resource owner | Your user (at TecnoShop, the tecnoshop organization) |
Where the repositories live |
| Repository access | Only select repositories: orders-api and catalog-web |
Not one more |
| Permissions → Repository permissions → Contents | Read-only | Only reading code |
- GitHub automatically adds Metadata: Read-only, which is mandatory. Click Generate token and copy the value (it starts with
github_pat_): GitHub will not show it again.
With this token, even if it leaked, nobody could write code, delete branches or access other repositories. In Multibranch Pipelines you will add one more read permission to it (pull requests), and in 06-01 you will see more robust alternatives such as GitHub Apps. If tokens in your organization require administrator approval, GitHub will tell you when you create it.
Step 3: Create the Credential in Jenkins
Manage Jenkins → Credentials → System → Global credentials (unrestricted) → Add Credentials:
| Field | Value |
|---|---|
| Kind | Username with password |
| Scope | Global |
| Username | Your GitHub username |
| Treat username as secret | Unchecked |
| Password | The github_pat_... token |
| ID | github-tecnoshop |
| Description | GitHub: read-only fine-grained token (orders-api, catalog-web). Expires after 90 days. Owner: Laura. |
- The token goes in Password: for Git over HTTPS, GitHub accepts a token instead of the password (in fact, it no longer accepts passwords).
- Treat username as secret would also mask the username in the logs. The username is not a secret, and masking it makes the consoles harder to read, so we leave it unchecked.
Step 4: Use It in the Jobs' SCM Configuration
In Configure for orders-api-pipeline, Pipeline section (Pipeline script from SCM), in the Credentials drop-down list under Repository URL, choose the entry <your-username>/****** (GitHub: read-only fine-grained token...). Once you select it, the red connection warning disappears. Save and run a build: it works again.
Repeat the operation in catalog-web-pipeline and in orders-api-build (even though its triggers are disabled, if it is ever run it must be able to read the code). Notice that the credential is chosen in the job configuration, not in the Jenkinsfile: Jenkins needs it before it can read the file. The implicit checkout of the Jenkinsfile (Declarative: Checkout SCM) reuses that same configuration, so the orders-api Jenkinsfile does not change in this lesson.
TecnoShop's Practice Credentials
Also create these credentials with clearly fictitious values; they will be used for practice now, and you will replace them with real values (from your test environment) in the modules where they are used:
| ID | Kind | Fictitious content | Real use |
|---|---|---|---|
nexus-deployer |
Username with password | Username ci-deployer, password NotARealPassword-123 |
06-05 |
slack-token |
Secret text | xoxb-0000-fake-tecnoshop |
06-07 |
ssh-staging |
SSH Username with private key | Username deploy and a key generated for practice |
06-06 |
For ssh-staging, generate a throwaway key on your machine:
ssh-keygen -t ed25519 -f ./ssh-staging-practice -N '' -C 'jenkins@tecnoshop-practice'
cat ./ssh-staging-practice-t ed25519: a modern, recommended key type.-f: output file; this createsssh-staging-practice(private) andssh-staging-practice.pub(public).-N '': no passphrase (in production, consider using one).- In the credential, under Private Key → Enter directly → Add, paste the full contents of the private key, including the
-----BEGIN OPENSSH PRIVATE KEY-----and-----END...lines. Then delete the files from your machine: this key grants access to nothing.
The sonar-token and registry-tecnoshop credentials will be created in their own lessons (06-04 and 06-05).
The credentials() Helper in environment
Create a practice Pipeline job, lab-credentials, with this script:
pipeline {
agent any
stages {
stage('Helper credentials()') {
environment {
NEXUS = credentials('nexus-deployer')
}
steps {
sh 'echo "User: $NEXUS_USR"'
sh 'echo "Password: $NEXUS_PSW"'
sh 'echo "Combined: $NEXUS"'
}
}
}
}credentials('nexus-deployer'): a special helper that only works insideenvironment. It looks the credential up by its ID and creates variables according to its type.- For Username with password, it creates three variables:
NEXUS(in the formatusername:password),NEXUS_USR(the username) andNEXUS_PSW(the password). - It is declared in the
environmentof the stage that needs it, not in the pipeline's: the smaller a secret's scope, the better.
The console shows:
+ echo 'User: ci-deployer' User: ci-deployer + echo 'Password: ****' Password: **** + echo 'Combined: ****' Combined: ****
The password appears as **** everywhere, even in the + echo trace line that sh generates. The username does not, because we did not check Treat username as secret. The combined NEXUS variable is considered secret as a whole, so it is masked entirely.
Variables created by credentials() according to the type:
| Type | Variables |
|---|---|
| Secret text | X = the text |
| Username with password | X = username:password, X_USR, X_PSW |
| Secret file | X = path to a temporary copy of the file |
| SSH Username with private key | X = path to the key, X_USR = username, X_PSW = passphrase |
| Certificate | Not supported: use withCredentials |
The withCredentials Step
withCredentials does the same thing with more control: you choose the variable names, and the secret exists only inside the block. Add these stages to the lab:
stage('withCredentials') {
steps {
withCredentials([
usernamePassword(credentialsId: 'nexus-deployer',
usernameVariable: 'NEXUS_USER',
passwordVariable: 'NEXUS_PASSWORD'),
string(credentialsId: 'slack-token', variable: 'SLACK_TOKEN')
]) {
sh 'echo "Nexus: $NEXUS_USER / $NEXUS_PASSWORD"'
sh 'echo "Slack: $SLACK_TOKEN"'
sh '''
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 \
-u "$NEXUS_USER:$NEXUS_PASSWORD" \
https://nexus.tecnoshop.local/service/rest/v1/status/check || true)
echo "Nexus response (fictitious): ${code:-no connection}"
'''
}
sh 'echo "Outside the block: [$SLACK_TOKEN]"'
}
}
stage('SSH (demo only)') {
steps {
withCredentials([sshUserPrivateKey(credentialsId: 'ssh-staging',
keyFileVariable: 'SSH_KEY',
usernameVariable: 'SSH_USER')]) {
sh 'echo "User $SSH_USER, temporary key in $SSH_KEY"'
sh 'ls -l "$SSH_KEY"'
}
}
}- The
withCredentialslist accepts several credentials at once, each with its own binding:usernamePassword,string,file,sshUserPrivateKey,certificate... - The
curlcall to Nexus is fictitious: sincenexus.tecnoshop.localdoes not exist, it will showno connection(or000).|| truekeeps the network failure from breaking the lab;--max-time 5limits the wait. What matters is the form: username and password reachcurlas shell variables. Real use with Nexus comes in 06-05. - Outside the block,
$SLACK_TOKENis empty: the secret no longer exists. sshUserPrivateKeywrites the key to a temporary file (with restricted permissions) and puts its path inSSH_KEY. It is deleted when the block exits. It would be used like this:ssh -i "$SSH_KEY" ...; real SSH deployment, with the SSH Agent plugin, comes in 06-06.- The
file(credentialsId: '...', variable: 'X')binding works the same way with Secret file credentials:Xcontains the path to a temporary copy. For example, akubeconfigfor Jenkins and Kubernetes.
credentials() vs. withCredentials:
credentials() in environment |
withCredentials |
|
|---|---|---|
| Syntax | Very short | Longer |
| Variable names | Fixed (X, X_USR, X_PSW) |
You choose them |
| Smallest scope | One stage | A handful of steps |
| Types | Does not support Certificate | All of them |
| Use at TecnoShop | Short stages that use the secret in all their steps | Every other case |
Log Masking and Its Limits
Jenkins replaces every literal occurrence of the secret's value in the console with **** while it is in use. It is a useful safety net, but it is not a guarantee. Add this stage to the lab (with the fictitious token, never with a real one):
stage('Masking limits') {
steps {
withCredentials([string(credentialsId: 'slack-token', variable: 'SLACK_TOKEN')]) {
sh 'echo "$SLACK_TOKEN" | base64'
sh 'echo "$SLACK_TOKEN" | rev'
sh 'echo "$SLACK_TOKEN" > copied-token.txt'
}
}
}The first two lines show the secret encoded and reversed, unmasked: Jenkins only recognizes the exact text. The third writes it to a file in the workspace, which anyone could archive. Limits you should know about:
| Limit | Example |
|---|---|
| It only masks the exact text | base64, rev, URL encoding, the secret split across two lines |
| It only acts on the console | Written files, archived artifacts, test reports, messages sent to other systems |
| Only while the secret is bound | If you copy it to another variable and use it outside the block, it is no longer masked |
| Very short or common secrets | A "secret" such as admin would mask every occurrence of that word and would still be weak |
| Secret files | The contents of a Secret file are not masked: only its path is expected to be used |
The takeaway is that masking protects against carelessness, not against someone who wants to steal the secret. Anyone who can modify a Jenkinsfile that uses a credential can, in practice, extract it. That is why who can modify pipelines and who can use credentials is a top-priority security matter, which you will deal with in Configuring Security.
Secrets and Groovy Interpolation: the Jenkins Warning
In 04-03 you saw that sh "...${...}..." makes Groovy paste the value into the text of the script. With secrets it is even more serious. Add this to the lab:
stage('Unsafe interpolation') {
steps {
withCredentials([string(credentialsId: 'slack-token', variable: 'SLACK_TOKEN')]) {
sh "echo Token: ${SLACK_TOKEN}"
}
}
}The build works, but Jenkins writes this to the console:
Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure. Affected argument(s) used the following variable(s): [SLACK_TOKEN] See https://jenkins.io/redirect/groovy-string-interpolation for details.
Why it is insecure:
- The secret becomes part of the script's code: it is written to a temporary file on the agent and appears in the process list (
ps), where other processes on the machine can see it. - If the secret contains shell special characters (
$,`,;, quotes), the command breaks or does something other than intended.
The correct way: single quotes in Groovy, and let the shell expand the variable:
Now the script literally contains $SLACK_TOKEN, and the value only exists in the process environment. The warning disappears.
A refinement for advanced users: even with single quotes, curl -u "$U:$P" puts the password in the arguments of the curl process, visible with ps on the agent while it runs. Many tools let you read the credential from standard input or from a file (docker login --password-stdin, curl -K -, a Maven settings.xml); where available, they are preferable. You will apply this in module 6.
The Credentials Parameter
In 02-03 you saw the Credentials Parameter among the parameter types: it lets whoever runs the build choose which credential to use (for example, among several deployment accounts), without ever seeing its value. In a Jenkinsfile it is declared in parameters (generate the exact syntax with the Declarative Directive Generator) and its value is the chosen ID, which is then passed to withCredentials:
withCredentials([usernamePassword(credentialsId: params.DEPLOY_CREDENTIAL,
usernameVariable: 'DEPLOY_USER', passwordVariable: 'DEPLOY_PASSWORD')]) {
sh 'echo "Deploying as $DEPLOY_USER"'
}Use it with caution: letting people choose credentials means letting them choose permissions.
External Secrets Managers
In large organizations, secrets do not live in Jenkins but in a centralized manager, which Jenkins queries when it needs them. Advantages: a single place to audit, rotate and revoke; short-lived dynamic secrets; and Jenkins stops being an attractive secrets store for an attacker.
| Manager | Jenkins plugin | How it is used from the pipeline | A good fit when... |
|---|---|---|---|
| HashiCorp Vault | HashiCorp Vault | withVault step with the secret's path |
The organization already uses Vault or needs dynamic secrets (for example, temporary database credentials) |
| AWS Secrets Manager | AWS Secrets Manager Credentials Provider | Secrets appear as regular (read-only) Jenkins credentials; they are used with withCredentials |
The infrastructure is on AWS |
| Azure Key Vault | Azure Key Vault | As a credentials provider or with the withAzureKeyVault step |
The infrastructure is on Azure |
There are also providers for Google Secret Manager, CyberArk Conjur and Kubernetes secrets. The pattern is always the same: Jenkins authenticates once with the manager (with its own identity, ideally without static secrets, such as a cloud role) and the pipelines request secrets by name. Their full configuration is beyond the scope of this course; what matters is that, if your organization has a manager, that is where secrets belong, and pipelines are written the same way: with withCredentials or the plugin's step, never with plain-text values.
Best Practices: Least Privilege, Rotation and Who Can Use What
- Least privilege: each credential with just the permissions its task needs. Jenkins' GitHub token only reads; the Nexus
ci-deployeraccount only publishes to its repositories and does not administer anything. - One credential per purpose: do not reuse the same one for reading code and for deploying. If one leaks, the damage is contained, and you can rotate it without affecting the rest.
- Expiration and rotation: tokens with an expiration date and a procedure for replacing them before they expire. Note the date in the Description. When rotating, create the new value at the source, update the credential in Jenkins (Update, keeping the ID so you do not have to touch any
Jenkinsfile) and revoke the old one. - Immediate revocation after a leak: if a secret shows up in a log, a commit or a chat, revoke it at the source first and then clean up the traces. Deleting the log is not enough.
- Smallest scope in the pipeline:
withCredentialsaround the steps that need it, orcredentials()in a stage'senvironment, never in the whole pipeline's. - System for anything only Jenkins uses.
- Who can see and use them: anyone who can configure a job or modify a
Jenkinsfilethat Jenkins builds can use the global credentials that job has access to. Credentials permissions (view, create, update, delete) and folder-based authorization are configured in Configuring Security; automatic detection of secrets pushed to the code is covered in DevSecOps.
Common Mistakes and Tips
- Leaving the ID empty: Jenkins generates a UUID and the
Jenkinsfiles fill up with unreadable identifiers. Always enter a descriptive ID. CredentialNotFoundException/Could not find credentials entry with ID 'nexus-deployer': the ID is misspelled, the credential is in another folder or it has System scope.sh "...${SECRET}...": triggers the unsafe interpolation warning. Single quotes and$SECRET.- Thinking that
****in the console means "safe": masking only covers the exact text in the console. credentials()outsideenvironment: the helper only works there. Insteps, usewithCredentials.- Using
Certificatewithcredentials(): not supported; usewithCredentialswithcertificate. - Choosing the credential in the
Jenkinsfilefor the checkout of theJenkinsfileitself: impossible, Jenkins needs it before reading the file. It goes in the job's SCM configuration. - A GitHub token with every permission "just in case": if it leaks, the attacker gets those same permissions on all your repositories.
- Tip: review Manage Jenkins → Credentials periodically and delete credentials nobody uses anymore. Every stored secret is a risk.
Exercises
Exercise 1. For each need, state the Kind, the Scope and how to use it from the pipeline: (a) the SonarQube API token; (b) the kubeconfig file for the staging cluster; (c) the key Jenkins uses to connect to an agent over SSH; (d) the username and password for TecnoShop's Docker registry.
Exercise 2. Review this snippet from another TecnoShop team. Point out all the problems and rewrite it correctly:
pipeline {
agent any
environment {
REGISTRY = credentials('registry-tecnoshop')
SLACK = 'xoxb-1234-fake'
}
stages {
stage('Publish') {
steps {
sh "docker login -u ${REGISTRY_USR} -p ${REGISTRY_PSW} registry.tecnoshop.local"
sh "curl -X POST -H 'Authorization: Bearer ${SLACK}' https://slack.com/api/chat.postMessage"
}
}
}
}Exercise 3. In the lab-credentials job, check what happens if you check Treat username as secret on nexus-deployer and run the credentials() helper stage again. What are the advantages and drawbacks?
Solutions
Solution 1.
| Need | Kind | Scope | Use in the pipeline |
|---|---|---|---|
| (a) SonarQube token | Secret text | Global | withCredentials([string(credentialsId: 'sonar-token', variable: 'SONAR_TOKEN')]) (or the SonarQube plugin integration, in 06-04) |
(b) Staging kubeconfig |
Secret file | Global | withCredentials([file(credentialsId: '...', variable: 'KUBECONFIG')]); the variable contains the path, which is exactly what kubectl expects |
| (c) SSH key for connecting an agent | SSH Username with private key | System | Not used from pipelines: Jenkins uses it when launching the agent (05-01) |
| (d) Docker registry | Username with password | Global | withCredentials([usernamePassword(...)]) or credentials('registry-tecnoshop') in the stage's environment |
Solution 2. Problems: (1) the Slack token is written in plain text in the Jenkinsfile; it must be a credential (slack-token). (2) credentials() is in the pipeline's environment: the secret exists in every stage; it should go in the stage that uses it. (3) Both sh steps use Groovy interpolation with secrets: Jenkins will show the warning. (4) docker login -p puts the password in the process arguments; Docker recommends --password-stdin. Corrected version:
pipeline {
agent any
stages {
stage('Publish') {
environment {
REGISTRY = credentials('registry-tecnoshop')
}
steps {
sh 'echo "$REGISTRY_PSW" | docker login -u "$REGISTRY_USR" --password-stdin registry.tecnoshop.local'
withCredentials([string(credentialsId: 'slack-token', variable: 'SLACK_TOKEN')]) {
sh 'curl -sf -X POST -H "Authorization: Bearer $SLACK_TOKEN" https://slack.com/api/chat.postMessage'
}
}
}
}
}echo is a shell builtin, so the password does not appear as an argument of any external process. In addition, the value that had been written in the Jenkinsfile must be considered compromised: it has to be revoked and a new one generated.
Solution 3. With Treat username as secret checked, the username is masked too: the first line shows User: ****, just like the other two. Advantage: if the username gives an attacker useful information (for example, service accounts with predictable names on sensitive systems), it is not exposed. Drawbacks: logs are harder to read and, if the username is a short or common word (such as admin or ci), Jenkins will mask every occurrence of it in the console, including those that have nothing to do with the credential. For service accounts with ordinary names, leave it unchecked. Uncheck it when you finish the exercise.
Conclusion
You now know how Jenkins manages secrets: the Credentials plugin stores them encrypted with the key in secrets/, in stores and domains, with Global scope (for jobs) or System scope (for Jenkins only), and with the option of restricting them to a folder. You know the types (Username with password, Secret text, Secret file, SSH Username with private key, Certificate) and you have created github-tecnoshop with a read-only fine-grained token so that Jenkins can read the now-private orders-api and catalog-web repositories, along with the practice credentials nexus-deployer, slack-token and ssh-staging. In pipelines you use the credentials() helper (with its _USR and _PSW suffixes) and withCredentials with usernamePassword, string, file and sshUserPrivateKey; you know what Jenkins masks and what it does not, and why the Groovy interpolation warning is solved with single quotes. You also know when an external manager such as Vault, AWS Secrets Manager or Azure Key Vault is the right place for secrets. With the repositories protected, it is time to change the way Jenkins builds them: instead of a job that only watches main, in the next lesson, Multibranch Pipelines and Pull Requests, you will create jobs that automatically discover every branch and every pull request.
