How to Pass a Secret File to a Command in Jenkins
A Secret file credential bound with withCredentials is written to a temporary path that is deleted when the block ends.
Store a file (kubeconfig, service-account key) as a Secret file credential, then bind it with withCredentials([file(...)]). The variable holds a path to a temp copy that Jenkins removes after the block.
Steps
- Add a Secret file credential and note its ID.
- Bind it with
withCredentials([file(credentialsId: ..., variable: ...)]). - Point the tool at the path in the bound variable.
Jenkinsfile
pipeline {
agent any
stages {
stage('Deploy') {
steps {
withCredentials([file(credentialsId: 'kubeconfig-prod', variable: 'KUBECONFIG')]) {
sh 'kubectl --kubeconfig "$KUBECONFIG" apply -f k8s/'
}
}
}
}
}Gotchas
- The temp file exists only inside the block; copying it elsewhere defeats the cleanup.
- Avoid printing the path contents; the file body is not masked, only the bound value would be.
Verify it actually works
Validate the pipeline definition against the running controller before committing. Jenkins parses declarative pipelines strictly, and a syntax error surfaces as a failed build rather than a clear parse message.
# validate a Jenkinsfile against the live controller
curl -X POST -F "jenkinsfile=<Jenkinsfile" \
https://your-jenkins/pipeline-model-converter/validate
# replay a build with modified script to test a change without committing
# Build page -> Replay -> edit -> RunAgent and workspace assumptions that break in CI
- An agent label that matches no online agent leaves the build queued indefinitely rather than failing.
- Workspaces are reused between builds by default, so stale files from a previous run can mask or cause failures. Use
cleanWs()or a fresh workspace when correctness matters. - Tools resolved from the controller PATH are not necessarily on the agent PATH. Declare them in a
toolsblock or install them in the pipeline. - Credentials bound with
withCredentialsare masked in logs but still visible to any process you launch; avoid passing them as command-line arguments.