Secret Text vs Secret File Credentials in Jenkins

Secret Text vs Secret File Credentials in Jenkins

Two ways to hand a secret to a build without ever writing it in your code: what each one is, how Jenkins stores and delivers it, when to choose which, and how to keep both from leaking.

Almost every real pipeline needs a secret. It might be a token that lets the build talk to a cloud service, a password for a package registry, a key file that proves the build may deploy, or a settings file that must never be shown in public. The tempting shortcut is to paste that secret straight into the pipeline file. It works on day one. Then the code is shared, copied, reviewed by many people, and the secret goes with it.

Jenkins offers a safer place for secrets: the credentials store. Two of its most common entry types look almost identical at first glance and are often confused. Secret text holds a single string. Secret file holds a whole file. Choosing the wrong one leads to broken builds, awkward workarounds, and sometimes accidental leaks.

This guide assumes you know nothing. Every new word is explained when it first appears, everyday pictures make ideas stick, and later chapters cover what experienced engineers care about: how masking really works, why quoting matters, what happens on the agent machine, how to rotate secrets, and how to keep both types safe in busy production systems.

1What Are These Two Credentials?

A plain-language first look before any details.

Jenkins is a free, open-source automation server that builds, tests and delivers software. Its work is written as a pipeline, a recipe stored in a text file called the Jenkinsfile. A credential in Jenkins is a stored secret, such as a password, a token or a key, kept in a protected vault instead of inside the recipe.

Jenkins supports several kinds of credentials. Two are the focus of this guide.

Type

Secret text

A single piece of text that must stay private, such as an access token or an API key. When a build uses it, the text is handed to the build as a variable.

Type

Secret file

A complete file that must stay private, such as a cluster configuration file or a signing keystore. When a build uses it, Jenkins places a temporary copy on the machine and gives the build its location.

Everyday Analogy

Think of a hotel safe. Some guests need to pass along a short number, like a door code. A receptionist can simply whisper it. That is secret text. Other guests need to hand over an entire sealed envelope of documents. The receptionist lays the envelope on the desk for a short while and takes it back afterwards. That is a secret file. The vault is the same; the way the item is delivered is different.

i
The one-line rule

If the tool you are running wants a value, use secret text. If it wants the path to a file, use secret file. Most of this guide explains why that simple rule works and where it needs care.

Both types belong to the same family, they are stored the same way, and they are protected by the same permissions. The difference is in shape and delivery, and that difference decides how safe, how convenient and how reliable your pipeline will be.

2Why the Credentials Store Exists

The problem it solves and how the idea grew.

The problem: secrets in the wrong places

In the early days, teams put secrets wherever was easiest: typed into the job’s settings page, written in shell scripts, saved in files committed to the code repository. Each of these places has a flaw. Job settings pages are visible to many administrators. Scripts get copied into chat messages and tickets. Code repositories keep every version forever, so a secret removed today still lives in history, and anyone who ever cloned the code has it.

The idea: keep secrets apart from recipes

The credentials store separates two things that should never be mixed. The recipe says what to do. The vault says what secret to use. The recipe refers to a secret only by a nickname, called an ID. The real value is fetched from the vault at the moment it is needed, and only for the steps that need it.

1

Secrets typed into jobs

Passwords sat in job settings and scripts, visible and easy to copy.

2

The Credentials plugin

Jenkins added a central store with encryption, permissions and scopes.

3

More credential kinds

The Plain Credentials plugin supplied secret text and secret file, complementing username and password and SSH key types.

4

Binding into pipelines

The Credentials Binding plugin let pipelines request a secret for a limited block of steps, with automatic masking in logs.

5

External vaults

Plugins let Jenkins read secrets from dedicated secret managers while still presenting them as ordinary credentials.

2
shapes: a string or a file
1
vault holds both
0
secrets that belong in the Jenkinsfile
A recipe should name the secret it needs, never contain it.

3Core Concepts You Need First

A handful of small ideas that make everything else easy.

Controller and agent

Jenkins has a main server, the controller, which stores settings and schedules work. The machines that really run your commands are agents. Secrets live on the controller and travel to an agent only when a build needs them.

Credential ID

Every credential has an ID, a short unique label such as payments-deploy-token. Pipelines refer to the credential by this ID. Choose readable IDs, because you will see them in many pipeline files.

Scope

The scope says who may use the credential. Global scope means jobs across Jenkins may use it. System scope means only Jenkins itself, not jobs, may use it. Credentials can also be placed in a folder, so only the jobs inside that folder can see them.

Binding

To bind a credential means to attach it to a variable for a short time. Inside a bound block, the build can read the variable. When the block ends, the binding disappears.

Masking

Masking is Jenkins’ habit of replacing a known secret value with asterisks whenever it appears in the build log. It is a safety net, not a lock, and Chapter 12 explains exactly how far it goes.

TermSimple meaningWhy it matters here
CredentialA stored secretKept in the vault, not in code
IDThe secret’s nicknameHow pipelines ask for it
ScopeWho may use itLimits the damage of misuse
BindingAttaching it to a variable for a whileDifferent for text and file
MaskingHiding the value in logsWorks well for text, less for files
AgentThe worker that runs stepsWhere secret files briefly exist

4Architecture and Components

Which parts of Jenkins take part when a secret is used.

A secret is used through a chain of cooperating parts. Understanding the chain explains almost every surprising behavior you will meet later.

flowchart LR
    ADM["Administrator adds credential"] --> VAULT["Credentials Store on Controller"]
    VAULT --> ENC["Encrypted at rest"]
    JF["Jenkinsfile asks for ID"] --> BIND["Credentials Binding"]
    BIND --> VAULT
    BIND -->|"secret text"| ENV["Environment variable on agent"]
    BIND -->|"secret file"| TMP["Temporary file on agent"]
    ENV --> TOOL["Tool or script"]
    TMP --> TOOL
    BIND --> MASK["Log masking"]
    TOOL --> LOG["Build log"]
    MASK --> LOG
Figure 1: From the vault to the tool, and how the two credential types diverge on the agent.

Read the diagram from left to right. An administrator adds the credential to the store on the controller, where it is kept encrypted. When a build reaches a step that asks for an ID, the binding component fetches the value. For secret text it is placed in an environment variable. For secret file, Jenkins writes a temporary file on the agent and places its path in the variable instead. The tool uses the value or the file. Meanwhile the masking component watches the log and hides known secret values.

Vault

Credentials Store

Holds every credential on the controller, with descriptions, scopes and encrypted values.

Plugin

Plain Credentials

Provides the secret text and secret file kinds.

Plugin

Credentials Binding

Lets a pipeline attach a credential to a variable for a limited block, and handles masking and cleanup.

Worker

Agent

Receives the secret for the duration of the step. Holds the temporary file for secret file credentials.

Shield

Permissions

Control who can view, create, change and use each credential.

Log

Console log

Where masked output appears. Readable by everyone who can view the build.

5Secret Text in Depth

The simple one: a single private string.

Secret text stores one string of characters. When you create it, you type or paste the value into a single box, give it an ID and a description, and save. From then on, the value is never shown again on the page. You can replace it, but you cannot read it back.

What it is good for

  • Access tokens for code hosting services, chat tools and quality-scanning tools.
  • API keys for cloud and payment services.
  • Webhook secrets used to check that incoming messages are genuine.
  • Passwords that are used alone, without a user name.
  • Short one-line values such as license keys or registration codes.

How it reaches the build

When bound, the text is placed in an environment variable with a name you choose. An environment variable is a named value that every program started by that step can read. The tool reads the variable, or the step passes it as an argument. When the bound block ends, the variable disappears from later steps.

Strengths

  • Very simple to create and to use.
  • No file left behind on the agent.
  • Masking works reliably for ordinary one-line values.
  • Tiny and fast to handle.

Limits

  • Awkward for anything long, structured or spanning many lines.
  • Special characters can break commands if quoting is careless.
  • Environment variables can be read by every process in the step, and appear in diagnostic output if someone prints them.
  • Cannot hold binary data.

Example: a chat notification token

A team wants the pipeline to post a message to their chat channel. The chat service gives them one long token. They store it as secret text with the ID chat-notify-token. The notification step reads it from a variable. The token never appears in the code, and the log shows asterisks if it is ever printed.

6Secret File in Depth

The flexible one: a complete private file.

Secret file stores an uploaded file. When you create it, you choose a file from your computer, give it an ID and a description, and save. Jenkins keeps the contents encrypted and remembers the file’s name. Like secret text, the contents cannot be viewed again through the page.

What it is good for

  • Cluster configuration files that tell a tool how to connect to a container platform.
  • Service account key files in structured formats, given by cloud providers.
  • Signing keystores used to sign mobile apps or packages, which are binary.
  • Certificates and key bundles for secure connections.
  • Environment or settings files containing many values that a tool loads by path.
  • Long multi-line secrets such as private keys in text form.

How it reaches the build

When bound, Jenkins writes the file into a temporary folder on the agent, sets restrictive permissions so that only the build’s user can read it, and puts the file’s location into the variable you named. The tool is given the location, not the contents. When the bound block ends, Jenkins deletes the temporary file.

Strengths

  • Handles binary data and very large secrets.
  • Preserves line breaks and special characters exactly.
  • Matches how many tools want to receive their configuration.
  • The value itself never sits in an environment variable or on a command line.

Limits

  • The secret exists as a real file on the agent, even if briefly.
  • Masking of the contents in logs is not something to rely on if the file is printed.
  • If a step copies the file elsewhere, the copy may outlive the bound block.
  • Slightly more setup and cleanup thinking is required.

Example: a cluster configuration file

A deployment tool needs a configuration file that lists cluster addresses and access details. The team uploads it as secret file with the ID staging-cluster-config. The deploy step is told, through a variable, where the temporary file is. When the step ends, Jenkins deletes it.

7Side by Side Comparison

The two types compared across everything that matters.

QuestionSecret textSecret file
What is stored?One stringOne uploaded file
Can it hold binary data?NoYes
Suitable sizeShort valuesSmall to large
Multi-line valuesAwkwardNatural
What the build variable holdsThe secret value itselfThe path to a temporary file
Touches the agent’s disk?NoYes, briefly
Log masking of the valueYes, for known exact valuesNot for file contents printed by a step
Risk of quoting mistakesHigher, because the value passes through commandsLower, because the tool reads a file
Typical usesTokens, API keys, one-line passwordsConfig files, key files, keystores, certificates
Cleanup after the stepVariable removed automaticallyTemporary file deleted automatically
Main dangerPrinting or passing the value carelesslyCopying the file or printing its contents

Two rows deserve special attention. The row about what the variable holds explains why the two types are not interchangeable: a tool that expects a token will fail if given a file path, and a tool that expects a file will fail if given the token itself. The row about masking explains why secret file needs extra care in what steps you allow to touch it.

8Choosing Between Them

A short set of questions that gives the right answer almost every time.

flowchart TD
    S["I have a secret to store"] --> Q1{"Is it binary data?"}
    Q1 -->|"Yes"| F["Use secret file"]
    Q1 -->|"No"| Q2{"Does the tool want a file path?"}
    Q2 -->|"Yes"| F
    Q2 -->|"No"| Q3{"Is it more than one line or structured?"}
    Q3 -->|"Yes"| F
    Q3 -->|"No"| Q4{"Is it a user name plus password?"}
    Q4 -->|"Yes"| UP["Use username with password type"]
    Q4 -->|"No"| T["Use secret text"]
Figure 2: A decision path for choosing the right credential type.
1

Is it binary?

Keystores and some certificate bundles are binary. Text boxes cannot hold them, so file is the only choice.

2

What does the tool expect?

Read the tool’s documentation. If it asks for a path to a configuration or key file, give it a file. If it asks for a token or key value, give it text.

3

How long and messy is it?

Multi-line or structured content, like a JSON key file, belongs in a file to avoid escaping and masking trouble.

4

Is it really a pair?

A user name with a password has its own credential type, which also creates helpful variables for each part. Do not squeeze the pair into one text value.

i
Tie-breaker

When both would technically work, prefer secret text for simple short values, since nothing touches the disk. Prefer secret file for anything long or multi-line, since it avoids quoting and masking surprises.

9Creating Each Credential

What you fill in, and what each field means.

In the Jenkins web page you open the credentials area, choose the store and domain, and add a new credential. From the list of kinds you choose secret text or secret file. The form is short.

1

Kind

Choose secret text or secret file. This cannot be changed later without recreating the credential.

2

Scope

Choose global for jobs to use it, or system for Jenkins internal use only. Pick a folder store to restrict it to one team’s jobs.

3

The secret

For text, paste the value. For file, choose the file to upload. Make sure there are no extra spaces or line breaks in a pasted token.

4

ID

A unique nickname. Leave it empty and Jenkins generates a random one, but a readable ID is far easier to use and audit.

5

Description

Say what the secret is for, who owns it and when it expires. This text is shown in lists and is your future self’s best friend.

A naming convention that scales

Choose IDs that answer three questions: which team, which purpose, which environment. For example, payments-registry-token-prod tells you everything at a glance. In a crowded credentials list, vague IDs such as token1 lead to mistakes, like using a production secret in a test job.

!
Common mistake

A hidden trailing newline at the end of a pasted token is a classic cause of “authentication failed” errors. If a token that works elsewhere fails in Jenkins, re-paste it carefully or trim the value before use.

Illustration: the useful description

A team’s description reads “Registry token for payments service, owner Priya, rotates every 90 days, next rotation 1 March.” When the token expires, anyone can see whom to ask and how the secret is maintained. Without it, the token is an anonymous mystery that nobody dares to touch.

10Using Them in a Pipeline

Two ways to request a secret, and what each gives you.

A pipeline asks for a credential by its ID and says which variable should carry it. There are two common ways, and both work for both types.

MethodWhere it is writtenHow long the secret livesBest for
The credentials helper in the environment blockAt the top of the pipeline or a stageWhole pipeline or the whole stageSimple pipelines where many steps use the same secret
The withCredentials stepAround just the steps that need itOnly inside the blockTight control, and several different secrets in one place

The environment block helper

In the declarative environment section you can assign a variable from a credential ID. For secret text the variable holds the text. For secret file the variable holds the path to a temporary file. Because the variable exists for the whole stage or pipeline, any step, including ones that do not need the secret, can read it. That is convenient but broader than necessary.

The withCredentials step

The withCredentials step wraps a small group of steps. Inside it you list bindings. The one for secret text is called string, and the one for secret file is called file. Each binding names the credential ID and the variable. Outside the wrapped group, the secret does not exist. This is the tighter and usually safer choice.

i
Rule of thumb

Bind for the shortest time and the smallest group of steps that truly need the secret. A secret that exists for two steps can leak in two steps. A secret that exists for the whole pipeline can leak anywhere.

Other binding types exist for other credential kinds, for example a combined one for user name and password, one for SSH keys and one for certificates. Their names differ, but the principle is identical: name the ID, name the variable, keep the block small.

11The Life of a Secret During a Build

What happens, in order, for each type.

flowchart TD
    subgraph TXT["Secret text"]
        T1["Step reaches bound block"] --> T2["Controller sends value to agent"]
        T2 --> T3["Value placed in environment variable"]
        T3 --> T4["Masking registered for log"]
        T4 --> T5["Tool reads variable"]
        T5 --> T6["Block ends and variable removed"]
    end
    subgraph FIL["Secret file"]
        F1["Step reaches bound block"] --> F2["Controller sends contents to agent"]
        F2 --> F3["Temporary file created with restricted access"]
        F3 --> F4["Variable holds the file path"]
        F4 --> F5["Tool opens the file"]
        F5 --> F6["Block ends and file deleted"]
    end
Figure 3: Both types follow a bind, use and remove cycle, but only the file touches the disk.
1

Request

The pipeline reaches the bound block and asks for the credential by ID. Jenkins checks that this job is allowed to use it.

2

Delivery

The controller decrypts the value and sends it to the agent running the step, over the connection between them.

3

Exposure

The text appears in a variable, or the file appears in a temporary location. This is the period of greatest risk.

4

Use

The tool reads the value or opens the file and does its work.

5

Removal

When the block ends, the variable disappears or the file is deleted. Nothing remains available to later steps.

The exposure window is the heart of secret safety. A good pipeline makes that window as short and as small as possible, and makes sure that nothing inside the window copies the secret somewhere that outlives it.

12Masking: What It Protects and What It Does Not

A helpful safety net that is easy to overtrust.

When a secret is bound, Jenkins remembers its exact value. If that exact value shows up in the build log, Jenkins replaces it with a row of asterisks before anyone sees it. This is what stops an accidental print statement from publishing your token to everyone who can read the log.

What masking does well

  • Hides an exact, unchanged copy of a bound secret text value in the console log.
  • Works automatically, with no extra steps from you.
  • Protects against simple accidents, such as a tool that echoes its own settings.

What masking cannot do

  • Changed values slip through. If a script converts the secret to another encoding, reverses it, splits it into pieces or adds spaces between letters, the changed version no longer matches, and is shown in full.
  • File contents are not a masked string. The variable that holds a file path is masked, but if a step prints the contents of the file, whatever is inside appears in the log.
  • It works only on the log. Files, artifacts, test reports and chat messages built from secret values are not protected.
  • It cannot undo. Once a secret has appeared in a log without masking, it stays there until the log is deleted, and may already have been copied elsewhere.
  • It cannot stop a determined insider. Someone who can edit the pipeline can transform the value before printing it.
Everyday Analogy

Masking is like a proofreader who blacks out any exact appearance of a secret phrase in a newspaper before printing. It catches the phrase written normally. It will not catch the same phrase written backwards, spelled out letter by letter, or described in other words.

!
Key idea

Treat masking as a seatbelt, not a locked door. Design your pipelines so that secrets are never printed in the first place, and use masking only as the last line of defense.

13The String Interpolation Trap

The single most common way secret text is mishandled.

Pipelines are written in a language called Groovy. In Groovy, text written inside double quotes can contain placeholders that are filled in by Jenkins itself before the command is run. This is called string interpolation. Text in single quotes is passed through untouched, so the placeholder is filled in later by the shell on the agent.

Why the difference matters for secrets

Quote styleWho fills in the variableWhat can go wrong
Double quotesJenkins, before the command is sent to the agentThe real secret is baked into the command text, which can appear in logs, process lists and error messages, and Jenkins warns that this is insecure
Single quotesThe shell on the agent, at run timeLittle, because the command text holds only the variable’s name

With double quotes, the secret becomes part of the command line itself. Other programs running on the same machine may be able to see command lines. Error messages that quote the failing command can reveal it. Jenkins prints a warning in the log when it detects a secret passed this way, and that warning should never be ignored.

The safe habit

  • Write shell commands that use secrets inside single quotes, so the shell, not Jenkins, reads the variable.
  • Prefer tools that read secrets from an environment variable or a file, not from a command-line argument.
  • If a tool insists on a command-line argument, pass it via the environment variable and let the shell expand it at run time.
i
Why file avoids the trap

With secret file, the command line contains only the path to the file, never the secret itself. This is one reason file credentials are favored for anything sensitive that a tool can load from disk.

Illustration: the warning nobody read

A team’s log has shown the same interpolation warning on every build for months. Nobody reads it. One day a failing command prints its full text in an error report sent to a shared chat channel, and the token inside becomes visible to two hundred people. Fixing the quotes takes ten minutes; rotating the token, and explaining the incident, takes a week.

14Multi-line Secrets, JSON and Certificates

Where secret file clearly wins.

Some secrets are not one neat line. A private key in text form spans many lines and includes header and footer lines. A service account key is a structured document full of quotation marks and braces. A certificate bundle may be binary. These are exactly the cases where beginners try secret text and run into trouble.

Problem

Line breaks

Environment variables and command lines handle line breaks badly. Keys can be silently damaged, causing confusing “invalid key” errors.

Problem

Quotation marks

Structured text contains characters that the shell treats as special. Without careful escaping, the value is cut short or altered.

Problem

Masking gaps

Masking multi-line values in the log is less dependable, because each line may appear separately in output.

Problem

Binary content

Keystores and certificate bundles cannot be pasted into a text box at all.

Why the file type fixes these

A file keeps every byte exactly as uploaded. There is no escaping, no lost line breaks and no encoding problem. The tool simply opens the file. In addition, most tools that need structured or multi-line credentials already know how to read them from a path, so the workflow fits naturally.

A special case: SSH keys

Jenkins has a dedicated credential type for SSH user names with private keys, and it has built-in support in the source control steps. When a tool speaks SSH, use that dedicated type instead of storing the key as text or file. It handles the details, such as passphrases and agents, for you.

Example: the mobile signing keystore

A mobile team must sign every release build with a keystore, a binary file. They upload it as secret file, and store its password separately as secret text. The build binds both: the file path goes to the signing tool, and the password arrives through a variable. Neither ever appears in the code.

!
Pairing pattern

Files often come with a passphrase. Store the file as secret file and the passphrase as secret text, as two credentials with related IDs. Then rotate each independently.

15Scopes, Folders and Domains

Deciding who can reach a secret in the first place.

flowchart TD
    J["Jenkins root store"] --> SYS["System scope: Jenkins internal use only"]
    J --> GL["Global scope: usable by jobs everywhere"]
    J --> F1["Folder: payments team"]
    J --> F2["Folder: search team"]
    F1 --> C1["payments-registry-token-prod"]
    F1 --> C2["payments-signing-keystore"]
    F2 --> C3["search-index-api-key"]
    GL --> C4["shared-chat-notify-token"]
Figure 4: Credentials in a folder are visible only to jobs in that folder.
PlacementWho can use itTypical use
System scopeJenkins itself, for example to connect to agents or send email; not jobsInfrastructure secrets that jobs should never touch
Global scopeAny job on the server that has permissionTruly shared, low-risk secrets
Folder storeOnly jobs inside that folder and belowA team’s or project’s own secrets

Domains

Within a store, a domain groups credentials and can restrict them to certain web addresses or host names. A domain limited to one server address means the credential will be offered only when talking to that server. This helps stop a secret being used by accident against the wrong system.

Why folder scope is the default choice

Global credentials are easy but broad. Anyone who can create or edit a job on the server can potentially reference them. Folder credentials narrow that circle to the team that owns the secret. As a habit, start at the narrowest scope and widen only with a reason.

!
Watch out

System scope hides a credential from jobs, but it does not hide it from administrators. It protects against job authors, not against people who manage Jenkins.

16Permissions: Who Can Use and Who Can See

Access to secrets is a set of separate rights, not one switch.

Jenkins separates several actions on credentials. Being clear about which people need which action keeps the vault safe without blocking real work.

View

See that it exists

Lets a person see the ID and description, never the secret value.

Create

Add new credentials

Typically for team leads or a security team. Uploading a file or text is a powerful act.

Update

Replace the value

Needed for rotation. Should be limited to the owners.

Delete

Remove it

Breaks every pipeline that uses it, so it should be restricted.

Use

Reference it in a build

Anyone who can edit a pipeline and run it can effectively use the secrets it can see, which is the most important permission to think about.

Manage

Manage domains

Control how credentials are grouped and restricted.

The uncomfortable truth about use

A person who can write a pipeline that binds a credential can, in principle, make the pipeline do anything with it, including sending it somewhere. Masking will not stop a deliberate leak. So the ability to run pipelines that can see a secret is, in practice, the ability to know the secret. This is why the scope of a credential and the control of who may change the pipeline file matter so much.

Illustration: the intern’s pipeline

A new team member is allowed to edit jobs in a shared folder. Every credential in that folder is therefore available to their pipeline code. The team realizes their folder mixes test secrets with production ones. They split the folder in two, and give only senior engineers access to the production one.

17How Jenkins Stores Secrets

What sits on the controller’s disk and how it is protected.

The controller keeps its data in a folder called the Jenkins home. Credentials are saved in a configuration file inside it. The secret values in that file are not written as plain text. They are encrypted, both for secret text and for the contents of secret files.

1

Encryption keys

Jenkins keeps encryption keys in a protected subfolder of its home directory, created when the controller first starts.

2

Encrypted values

When you save a credential, its value is encrypted with those keys, and only the encrypted form is written to the configuration file.

3

Decryption on demand

When a build requests the credential, the controller decrypts it in memory and sends it to the agent.

What this protects against, and what it does not

  • Protects: someone who sees only the configuration file, for example in a stray copy or a screenshot, cannot read the secrets from it.
  • Does not protect: someone who obtains both the configuration file and the keys can decrypt everything. Backups typically contain both. Treat backups of the Jenkins home as highly sensitive.
  • Does not protect: administrators with the right to run scripts on the controller, who can ask Jenkins itself to decrypt credentials.
!
Backup rule

Encrypt backups, restrict who can read them, and never copy the Jenkins home to an unprotected place. A backup is a copy of the vault together with its key.

Because everything is stored inside the controller, controller security is the foundation. Keep it updated, restrict who can log in as an administrator, and limit network access to it.

18Leak Paths and How Secrets Escape

Knowing the exits is the first step to closing them.

flowchart LR
    S["Bound secret"] --> A["Printed by a step"]
    S --> B["Changed then printed"]
    S --> C["Passed in a double quoted command"]
    S --> D["Copied to workspace"]
    S --> E["Written into an archived artifact"]
    S --> F["Sent to another service by a pipeline"]
    S --> G["Read from process environment by another program"]
    A --> LOG["Build log"]
    B --> LOG
    C --> LOG
    D --> ART["Artifacts and later builds"]
    E --> ART
    F --> EXT["Outside systems"]
    G --> EXT
Figure 5: The common ways a bound secret can leave its safe place.
Leak pathMore likely withHow to close it
Printing the valueSecret textNever print variables; avoid debug modes that echo them
Changed then printedBoth, by a careless or hostile scriptReview pipeline changes; restrict who can edit them
Double-quoted commandsSecret textUse single quotes; heed the interpolation warning
Printing file contentsSecret fileNever display the file; let the tool read it
Copying the file into the workspaceSecret fileUse the temporary path directly; delete any copy
Archiving artifacts that include secretsBothArchive only chosen paths; check contents
Environment dumpsSecret text in environmentAvoid printing all environment variables
Error reports to chatBothSend short summaries with links, never raw logs
Untrusted pull requestsBothNever bind secrets in builds of code from outsiders

Notice how many exits involve people, not machines: a debug line added in a hurry, a copy made for convenience, a log pasted into a ticket. Good habits and reviews matter as much as good settings.

19Security Best Practices

A short list of habits that prevent most incidents.

1

Least privilege

Give each secret the smallest scope and the smallest set of users that works. Narrow secrets do narrow damage.

2

Short exposure

Bind inside a small block around only the steps that need the secret, not for the whole pipeline.

3

Protect the Jenkinsfile

Anyone who can change the pipeline file can use its secrets. Require review for changes, and protect important branches.

4

Untrusted code gets no secrets

Builds of pull requests from outsiders must run without any bound credentials.

5

Short-lived where possible

Prefer tokens that expire quickly and can be revoked, so a leak has a short useful life.

6

Separate environments

Use different secrets for test, staging and production, and never reuse one across them.

7

Rotate and audit

Change secrets on a schedule and after any suspected exposure, and keep records of who changed what.

i
Assume leaks will happen

The strongest posture is not “our secrets never leak” but “when one leaks, the harm is small and the fix is quick.” Narrow scope, short lifetime and easy rotation deliver exactly that.

Illustration: the contained incident

A token is accidentally pasted into a public issue. Because it was a narrowly scoped, read-only token for one service, that expired in thirty days, and because rotation is a documented five-minute task, the team revokes it within an hour with no customer impact. The same leak with a broad, permanent administrator token would have been a crisis.

20Rotation and Lifecycle Management

Secrets age. Plan for their replacement from the start.

Rotation means replacing an old secret with a new one, and revoking the old. It limits how long a stolen secret stays useful and reduces the risk from people who once had access and no longer should.

flowchart LR
    R1["Owner creates new secret at the service"] --> R2["Update Jenkins credential with new value"]
    R2 --> R3["Run a test build that uses it"]
    R3 --> R4{"Build works?"}
    R4 -->|"Yes"| R5["Revoke the old secret"]
    R4 -->|"No"| R6["Fix and retry, old secret still valid"]
    R5 --> R7["Record date and next rotation"]
    R6 --> R3
Figure 6: A safe rotation keeps the old secret valid until the new one is proven.

Rotating each type

StepSecret textSecret file
Update in JenkinsEdit the credential and replace the textEdit the credential and upload the new file
Keep the IDYes, so pipelines need no changeYes, same reason
Common trapExtra whitespace in the pasted valueUploading the wrong or an old file version
VerificationRun a test build that calls the serviceRun a test build that loads the file
Companion secretsRotate related passwords togetherRotate the file and its passphrase together

The most valuable feature for rotation is that pipelines refer to the ID, not the value. Because you replace the value under the same ID, no pipeline files change. Rotation becomes a quick, low-risk maintenance task rather than a project.

!
Do not skip the last step

Revoking the old secret at the source is what makes rotation matter. A new secret with an old one still valid is just an extra key on the ring.

21External Secret Managers

When the Jenkins vault is not the only vault.

Large organizations often keep secrets in a dedicated secret manager, such as HashiCorp Vault or the secret services offered by cloud providers. Jenkins plugins can read from these systems and present the secrets as ordinary Jenkins credentials, including secret text and secret file. Pipelines then use the same binding steps they always did, while the real storage, rotation and auditing happen in the specialized system.

Benefit

One source of truth

Secrets are managed in one place for all tools, not copied into each system.

Benefit

Automatic rotation

The manager can rotate secrets on a schedule, and Jenkins reads the current value every time.

Benefit

Detailed auditing

Every read is logged with who and when, which is stronger than what a plain Jenkins store offers.

Cost

More moving parts

Another system to run and secure, and another dependency that can be down when a build needs it.

Mapping to the two types

A text secret in the external system typically appears as secret text in Jenkins. A binary or file-like secret appears as secret file. So the guidance in this guide about choosing between the two still applies, even when the store is somewhere else.

i
Design tip

External managers do not remove the need for careful binding. A secret fetched from a perfect vault can still be printed by a careless step. Combine both: strong storage and disciplined use.

22Agents, Containers and Temporary Files

What happens on the machine where the build really runs.

The agent is where secrets are actually used, so its safety matters. For secret text, the exposure is an environment variable in a running process. For secret file, the exposure is a real file on the agent’s disk for the length of the block.

Shared agents

If many teams share the same long-lived agent, one build may be running next to another. Temporary files are protected by permissions, but a shared machine with many users widens the risk, and a crash may leave a file behind. Keep secrets away from shared agents where you can.

Containers and disposable agents

Running builds in containers or on machines that are created for one build and destroyed afterwards limits exposure sharply. Even if a temporary file is left behind, it disappears when the container does. Disposable agents are the strongest practical defense for secret file use.

Agent styleExposure of secret textExposure of secret file
Shared, long-lived machineProcess environment on a busy hostTemporary file on a busy host, cleanup depends on a normal exit
Dedicated team agentLower, fewer neighborsLower, fewer neighbors
Container or disposable agentLimited to that container’s lifeFile vanishes with the container

Practical cautions

  • Do not copy the secret file into the workspace. The workspace is often kept, archived or shared between later builds.
  • Do not archive the whole workspace in a build where secrets were handled. Choose specific paths instead.
  • Clean the workspace at the end of builds that touched sensitive data, using the post section’s cleanup.
  • Mind containers inside builds. If a build runs a container and mounts the secret file into it, remember that the container can read it too.

23Monitoring, Auditing and Scale

How to know who uses what, and how to keep the vault tidy as it grows.

Knowing where a credential is used

Before changing or deleting a credential, you need to know which jobs depend on it. Jenkins can track usage of credentials in some setups, and searching your pipeline files for the ID is a simple fallback. Keep a habit of putting the owner and purpose in the description, so a quick look at the list answers most questions.

Auditing

Jenkins audit and logging plugins record who created, changed or deleted a credential and when. Keep those records long enough to answer questions after an incident. An external secret manager typically adds a record of every read as well.

Metric or checkWhy it mattersWarning sign
Number of credentials per folderShows sprawlHundreds with vague IDs
Credentials not used in monthsUnused secrets are pure riskOld entries nobody claims
Age since last rotationOld secrets have had more time to leakAnything older than your policy allows
Interpolation warnings in logsSignals insecure quotingAny occurrence
Changes to pipeline files that touch bindingsWatches for new places using secretsUnreviewed changes
Global-scope credential countBroad exposureGrowing over time

Scale

Credential lookup is quick, so a few hundred entries cause no performance trouble. The real cost of scale is human: people cannot tell which of five hundred entries is safe to change. Use a naming convention, folder-level ownership, and a regular review to remove what is unused. Some teams keep a yearly cleanup day where every owner confirms or retires their credentials.

Illustration: the cleanup day

A team with 240 global credentials runs a one-day review. Owners claim what is theirs. Sixty-one credentials have no owner and no recent use. After a two-week warning, they are removed, and three long-forgotten production keys are revoked at their source. The list becomes something people can actually read.

24Useful Design Patterns

Reliable ways of arranging secrets in pipelines.

Pattern 1: Bind late, unbind early

Wrap only the deploy or publish steps in the credential block. Build and test steps run with no secrets available at all.

Pattern 2: File plus passphrase

Store a keystore or key as secret file and its passphrase as secret text. Bind both in one block. Rotate them independently.

Pattern 3: One credential per environment

Keep separate IDs for test, staging and production with the same naming pattern. The pipeline picks the ID based on the branch or target, so a mistake in one environment cannot touch another.

Pattern 4: Secrets only in trusted builds

Use build-type conditions so credentials are bound only for protected branches or tags. Pull request builds run tests with no secrets and no deployment power.

Pattern 5: Shared library wrapper

Create a small shared library function that binds the right credential and runs a deployment. Pipelines call the function and never see credential IDs, so a security team controls how secrets are used in one place.

Pattern 6: Disposable agent for sensitive stages

Run stages that use secret files inside a fresh container. When the stage ends, the container and any leftover files vanish together.

25Anti-patterns to Avoid

Habits that look fine at first and hurt later.

ANTI-PATTERN 01Avoid
What people do

They paste a multi-line key or JSON document into secret text.

Why it hurts

Line breaks and quotes get damaged, masking becomes unreliable, and builds fail with confusing errors.

Better approach

Store it as secret file and let the tool read it from the path.

ANTI-PATTERN 02Avoid
What people do

They write commands with double quotes that include the secret variable.

Why it hurts

Jenkins bakes the real secret into the command text, which can be seen in logs and process lists.

Better approach

Use single quotes so the shell expands the variable at run time, and heed the interpolation warning.

ANTI-PATTERN 03Avoid
What people do

They print the file or the variable “just to check” that it arrived.

Why it hurts

File contents are not masked, and altered text is not masked either. The secret lands in the log for everyone to read.

Better approach

Check only that the file exists or that the variable is not empty, never its contents.

ANTI-PATTERN 04Avoid
What people do

They copy the temporary secret file into the workspace so a later step can use it.

Why it hurts

The copy outlives the bound block, may be archived, and may be visible to later builds.

Better approach

Do all work needing the file inside the bound block, or bind again in the later step.

ANTI-PATTERN 05Avoid
What people do

They make everything global scope and reuse one secret everywhere.

Why it hurts

Any job can use it, and one leak compromises every system it opens.

Better approach

Use folder scope, separate secrets per environment and per purpose.

ANTI-PATTERN 06Avoid
What people do

They bind secrets in builds of pull requests from outsiders.

Why it hurts

An outsider can change the pipeline to send the secret elsewhere.

Better approach

Bind secrets only in trusted builds, and run untrusted changes with none.

26Best Practices and Common Mistakes

A checklist to apply to any Jenkins setup today.

Do this

  • Choose the type by what the tool wants: a value or a file path.
  • Use secret file for multi-line, structured and binary secrets.
  • Use readable IDs with team, purpose and environment.
  • Write useful descriptions with owner and rotation date.
  • Bind for the smallest group of steps possible.
  • Use single quotes around commands that use secrets.
  • Prefer folder scope over global scope.
  • Rotate on a schedule and after any suspected leak.
  • Use disposable agents for stages that handle secret files.

Avoid this

  • Putting secrets in the Jenkinsfile or the repository.
  • Printing secret variables or file contents.
  • Double-quoted commands that include secrets.
  • Copying secret files into the workspace.
  • Sharing one secret across environments.
  • Binding secrets for the whole pipeline without need.
  • Giving secrets to untrusted pull request builds.
  • Leaving old credentials nobody owns.
  • Trusting masking as your only protection.

Mistakes people make when they are new

Using the wrong type. Giving a tool a token when it wants a path, or a path when it wants a token, produces errors that look like login failures. Read what the tool expects.

Trailing whitespace. A pasted token with a hidden line break at the end fails authentication in ways that are hard to spot. Trim values when you paste.

Forgetting the file’s format. Uploading a file with the wrong line endings or an extra extension can break tools that are strict about it. Upload the file exactly as the provider issued it.

Wrong ID or scope. A typo in the ID, or a credential in a folder the job cannot reach, gives a “could not find credentials” error.

Ignoring warnings. The interpolation warning is real. Fix it the first time it appears.

27Advantages, Disadvantages and Trade-offs

An honest look at each type.

Secret text: advantages

  • Simplest to create and use.
  • Nothing written to the agent’s disk.
  • Reliable log masking for one-line values.
  • Ideal for tokens and API keys.

Secret text: disadvantages

  • Awkward for long, structured or multi-line values.
  • Quoting mistakes can leak or corrupt it.
  • Visible to every process in the step’s environment.
  • No binary support.

Secret file: advantages

  • Handles binary and very large secrets.
  • Keeps every byte exactly as uploaded.
  • Command lines contain only a path, not the secret.
  • Fits tools that load configuration from disk.

Secret file: disadvantages

  • Exists as a real file on the agent for a while.
  • Printing its contents bypasses masking.
  • Copies can outlive the bound block.
  • Slightly more care with cleanup and agents.

Trade-offs to weigh

ChoiceBenefitCost
Text for a short tokenSimple, no disk exposureQuoting discipline needed
File for a short tokenValue stays off the command lineTool must accept a file, and file touches the disk
Bind for the whole pipelineConvenientLarger exposure window
Bind per blockTight exposureA little more writing
Global scopeEasy sharingBroad blast radius
Folder scopeTeam-owned and limitedDuplicates for truly shared secrets
Jenkins storeSimple, built inWeaker auditing and rotation
External secret managerCentral control and auditMore systems to run

There is no universally right answer. Match the type to the tool, the scope to the team and the storage to your risk. Then write down why, so the next person understands your choices.

28Real-World and Industry Examples

How the two types show up in the kinds of teams that run Jenkins at scale.

A mobile app studio

Teams building phone apps must sign every release with a keystore file. They store the keystore as secret file and its passwords as secret text, bind both only in the release stage, and run that stage on a fresh machine that is wiped afterwards.

A company running containers on a cloud platform

Deployment tools need a configuration file that lists cluster addresses and access details. Each environment has its own secret file with an ID that includes the environment name, so a staging build can never reach a production cluster.

A software vendor publishing packages

Publishing to a public package registry needs an access token. The vendor stores it as secret text in the release folder, restricts that folder to release managers and rotates the token every quarter.

A bank with strict audit rules

All secrets come from a central secret manager, surfaced in Jenkins as secret text and secret file. Every read is logged, every credential has a named owner, and pull request builds run in isolated agents with no credentials at all.

A small startup

A team of six keeps three secret text tokens and one secret file in a single folder, uses clear IDs, binds them only in the deploy stage and sets a calendar reminder to rotate quarterly. Simple habits, big protection.

flowchart TD
    PR["Pull request build"] --> NS["No credentials bound: build and test only"]
    MB["Main branch build"] --> T1["Build and test with no secrets"]
    T1 --> B1["Bind secret text: registry token"]
    B1 --> PUB["Publish package"]
    T1 --> B2["Bind secret file: cluster config"]
    B2 --> DEP["Deploy to cluster"]
    PUB --> CL["Cleanup workspace"]
    DEP --> CL
Figure 7: A typical layout: untrusted builds get nothing, and trusted builds bind each secret only where needed.

29A Complete Story: From Vault to Deployment

Follow one imaginary team through a release.

A team owns a booking service. They keep two credentials in their team folder: a secret text called booking-registry-token-prod, used to publish packages, and a secret file called booking-cluster-config-prod, used to deploy. Only release managers can change them, and both are rotated every ninety days.

1

A pull request

Maya opens a pull request. Jenkins builds and tests it. No credentials are bound, so even if her Jenkinsfile change were careless, there would be nothing to leak.

2

Merge to main

After review, the change merges. The main build starts, and the conditions now allow the release stages.

3

Publish

A small bound block requests the registry token by ID. The variable exists only inside the block. The publish command uses single quotes so the shell reads the variable at run time.

4

Deploy

On a fresh container agent, another bound block requests the cluster file. Jenkins writes a temporary file with restricted access and hands its path to the deployment tool.

5

Removal

When each block ends, the token variable vanishes and the temporary file is deleted. The container is discarded a moment later.

6

Rotation day

Ninety days later, the owner creates a new token at the registry, replaces the value in Jenkins under the same ID, runs a test build, and revokes the old token. No pipeline file changes.

At no point did a secret appear in code, in a log, or in a place where it lasted longer than needed. The team did not need heroic effort. They chose the right type for each secret, kept the bound blocks small, and followed a few habits.

The safest secret is the one that exists for the fewest seconds in the fewest places.

30Troubleshooting Guide

Symptoms, likely causes and calm fixes.

SymptomLikely causeWhat to do
Error that credentials cannot be foundWrong ID, or credential in a folder the job cannot reachCheck the exact ID and the folder or scope
Authentication fails though the token is rightExtra whitespace or a hidden line break in the pasted valueRe-paste carefully or trim before use
Tool says file not foundVariable used outside the bound block, or wrong variable nameUse the variable only inside the block
Tool receives a path instead of a tokenSecret file used where secret text was neededMatch the type to what the tool expects
Key rejected as invalidMulti-line key damaged inside secret textMove it to secret file
Warning about insecure interpolationDouble-quoted command that includes a secret variableSwitch to single quotes
Secret appears unmasked in the logValue was changed before printing, or a file was printedRemove the print, rotate the secret, delete the log
Works in one job, fails in anotherDifferent scope or permissionsCompare folder placement and rights
Binary keystore looks corruptedUploaded through a text-based route or editedUpload the original file again as secret file
Old value still in use after rotationCached copy or a second credential with a similar IDConfirm the ID and check for duplicates

A calm debugging routine

  1. Check the ID in the pipeline against the one in the credentials list, character by character.
  2. Check the scope and whether the job’s folder can see the credential.
  3. Check the type against what the tool expects: value or path.
  4. Check that the variable is used inside the block and not after it ends.
  5. Test without printing the secret. Confirm that a file exists or a variable is not empty, never its contents.
!
If a secret was exposed

Treat it as compromised at once. Revoke it at the source, create a new one, update Jenkins, and delete or restrict the build log that showed it. Speed matters more than blame.

31Plain-English Glossary

Every important word in this guide in one place.

WordSimple meaning
JenkinsA free automation server that builds, tests and delivers software.
PipelineA written recipe of the steps Jenkins follows.
JenkinsfileThe text file holding the pipeline, stored next to the code.
CredentialA secret stored in the Jenkins vault.
Secret textA credential holding a single private string.
Secret fileA credential holding a whole private file.
IDThe nickname pipelines use to ask for a credential.
ScopeWho may use a credential.
DomainA group of credentials that can be limited to certain addresses.
BindingAttaching a credential to a variable for a limited time.
Environment variableA named value that programs in a step can read.
MaskingReplacing known secret values with asterisks in the log.
String interpolationJenkins filling in variables inside double-quoted text before running a command.
ControllerThe main Jenkins server that holds the vault.
AgentA worker machine or container that runs steps.
RotationReplacing an old secret with a new one and revoking the old.
KeystoreA file holding keys or certificates, often used to sign software.
Secret managerA dedicated system for storing and auditing secrets.

32Frequently Asked Questions

Short answers to the questions that come up most often.

Q1What is the main difference between secret text and secret file?
Secret text stores one string, and the build receives the string itself in a variable. Secret file stores a whole file, and the build receives the path to a temporary copy.
Q2Which one should I use for an API token?
Secret text, unless the tool you are using insists on reading the token from a file.
Q3Which one for a JSON key file or a keystore?
Secret file. Structured, multi-line and binary secrets are handled correctly only as files.
Q4Will Jenkins hide my secret in the log?
It masks exact copies of bound secret text values. It does not protect changed versions, and it does not hide the contents of a file if a step prints them.
Q5Why does Jenkins warn about string interpolation?
Because double-quoted commands let Jenkins insert the real secret into the command text, where it may be seen in logs or process lists. Use single quotes so the shell reads the variable instead.
Q6Is the temporary file deleted automatically?
Yes, when the bound block ends. Copies you make yourself are not deleted, so avoid making them.
Q7Can I read a stored secret back from the Jenkins page?
No. You can replace it but not view it. Keep the original safely at its source, or in a proper secret manager.
Q8How do I rotate a secret without changing my pipelines?
Replace the value under the same ID. Pipelines refer only to the ID, so they need no edit. Then revoke the old secret at its source.
Q9Should I use global or folder scope?
Prefer folder scope so that only the owning team’s jobs can use the secret. Use global scope only for truly shared, low-risk secrets.
Q10Can someone who edits a pipeline steal a bound secret?
Potentially yes. That is why pipeline changes need review, untrusted code gets no secrets, and each secret has the narrowest scope possible.
Q11Why does my token fail even though it is correct?
Often a hidden space or line break was pasted with it, or the wrong credential type is being used. Re-paste carefully and check what the tool expects.
Q12Do I still need Jenkins credentials if I use an external secret manager?
Jenkins still needs to present the secret to the build. Plugins expose external secrets as ordinary Jenkins credentials, so the same types and binding rules apply.

33Summary and Key Takeaways

The whole story in a few lines.

Secret text and secret file are two shapes of the same idea: keep the secret in the Jenkins vault, name it by an ID, and attach it to a build only for as long as needed. Secret text delivers a value through a variable and leaves nothing on the disk. Secret file delivers a temporary file and suits anything long, structured or binary. The right choice follows from what the tool expects. The safe use follows from a few habits: small bound blocks, single-quoted commands, narrow scope, no printing, no copying, no secrets for untrusted code, and regular rotation.

Key Takeaways

  • Match the type to the tool. Use secret text when the tool wants a value, and secret file when it wants a path, or when the secret is multi-line, structured or binary.
  • Know what the variable holds. For text it is the secret itself. For a file it is the path to a temporary copy that Jenkins deletes when the block ends.
  • Masking is a seatbelt, not a lock. It hides exact copies in the log only. Changed values and printed file contents are not protected.
  • Mind the quotes. Double-quoted commands bake secrets into command text. Use single quotes and fix every interpolation warning.
  • Keep exposure short and narrow. Bind around only the steps that need the secret, prefer folder scope and separate secrets per environment.
  • Untrusted code gets no secrets. Protect the Jenkinsfile, review changes and run outsiders’ pull requests without credentials.
  • Plan rotation from day one. Use readable IDs and owner descriptions, replace values under the same ID, and always revoke the old secret.