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
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.
Related guides
How to Bind a Credential in the environment Block in JenkinsInject a stored Jenkins credential into an environment variable with the credentials() helper, so secrets sta…
How to Publish an HTML Report in a Jenkins PipelineAttach a browsable HTML report such as coverage or Playwright output to a Jenkins build with the publishHTML…