Skip to content

Instantly share code, notes, and snippets.

@marslo
Last active April 11, 2024 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save marslo/1be12ef31c7bc5b0501c2cfe112c3b9e to your computer and use it in GitHub Desktop.
Save marslo/1be12ef31c7bc5b0501c2cfe112c3b9e to your computer and use it in GitHub Desktop.
jenkins universal credential closure

🛠 groovy scripts for jenkins credentials

... keeping update ...

import com.datapipe.jenkins.vault.credentials.common.VaultSSHUserPrivateKeyImpl
import com.datapipe.jenkins.vault.credentials.common.VaultUsernamePasswordCredentialImpl
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
import com.cloudbees.plugins.credentials.CredentialsProvider
import com.cloudbees.plugins.credentials.common.StandardCredentials
def withCredential( String credentialsId, Closure body ) {
Closure foo = { cid ->
[
( VaultSSHUserPrivateKeyImpl ) : { body([ username: cid.username, sshkey: cid.privateKeyKey ]) },
( BasicSSHUserPrivateKey ) : { body([ username: cid.username, sshkey: cid.privateKeys.join('\n') ]) },
( VaultUsernamePasswordCredentialImpl ) : { body([ username: cid.username, password: cid.passwordKey ]) },
( UsernamePasswordCredentialsImpl ) : { body([ username: cid.username, password: cid.passwordKey ]) }
].find { it.key.isAssignableFrom( cid.getClass() ) }.value.call()
}
foo CredentialsProvider.lookupCredentials( StandardCredentials.class, jenkins.model.Jenkins.instance).find { credentialsId == it.id }
}
withCredential( 'BASIC_CREDENTIAL' ) { account ->
println "${account.password} -> ${account.username}"
}
withCredential( 'SSH_CREDENTIAL' ) { account ->
println "${account.sshkey} -> ${account.username}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment