How to copy Jenkins secret files

Ok, I think I managed to do it. my-private-key variable is a path to the secret, so I had to copy that secret to the destination I needed.

withCredentials([file(credentialsId: 'PRIVATE_KEY', variable: 'my-private-key'),
                 file(credentialsId: 'PUBLIC_KEY', variable: 'my-public-key')]) {
   sh "cp \$my-public-key /src/main/resources/my-public-key.der"
   sh "cp \$my-private-key /src/main/resources/my-private-key.der"
}

Following on from @Humberds answer, the equivalent for powershell is:

withCredentials([file(credentialsId: 'PRIVATE_KEY', variable: 'my-private-key')]) {
  bat "powershell Copy-Item $appSettings -Destination src\\main\\resources "
}

Both solution is good for specific OS(win, unix). There are some basic function to check is system unix isUnix(). Instead of this you can use the read/write basic methods for any machine.

withCredentials([file(credentialsId: PRIVATE_KEY, variable: 'my_private_key'),
                 file(credentialsId: PUBLIC_KEY, variable: 'my_public_key')]) {
        writeFile file: 'key/private.pem', text: readFile(my_private_key)
        writeFile file: 'key/public.pem', text: readFile(my_public_key)
    }

Tags:

Groovy

Jenkins