Easily get Jenkins secret files into the workspace

Kobi Rosenstein
1 min readDec 16, 2024

--

According to the documentation, using a secret file from the credentials should be pretty straightforward, but when I tried it, i kept getting erros about invalid characters, that didn’t even appear in my code.

The problem was this comment:

// The MY_KUBECONFIG environment variable will be assigned
// the value of a temporary file. For example:
// /home/user/.jenkins/workspace/cred_test@tmp/secretFiles/546a5cf3-9b56-4165-a0fd-19e2afe6b31f/kubeconfig.txt

It is easy to assume from this example that all you need to do is:

 mySecretFile = credentials('secret-file-id')

But, as it turns out, this returns a file handler object and NOT the path of the file like the docs claim:

@credentials(<anonymous>=secret-file-id)

The cause was that mySecretFile was being used in a script { block and not the environment { section. https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#handling-credentials.

But, in my case I just wanted a quick way to randomly add a secret file from anywhere in the pipeline? For instance, what if I want to iterate over a list of files? and so I added a new function to my shared library’s generalFunctions var file:

def secretFileToWorkspace(Map args) {
args.secretFileCredId = args.get('secretFileCredId', args.secretFileCredId)
args.secretFileLocalName = args.get('secretFileLocalName', args.secretFileLocalName)

withCredentials([file(credentialsId: args.secretFileCredId, variable: 'fileContent')]) {
sh("cat $fileContent > $args.secretFileLocalName")
}
}

And to call from within a pipeline:

generalFunctions.secretFileToWorkspace(secretFileCredId: 'secret-file-id', secretFileLocalName: 'my_secret_file.txt')

--

--

Kobi Rosenstein
Kobi Rosenstein

Written by Kobi Rosenstein

Devops engineeer. This blog chronicles my “gotcha” moments — Each post contains an answer I would have like to have found when trawling google.

No responses yet