Search code examples
groovyjenkins

How to store secret text or file using groovy


I have found how to store an Username/Password or SSH Username/PrivateKey using the groovy-based APIs for Jenkins.

https://gist.github.com/iocanel/9de5c976cc0bd5011653

domain = Domain.global()
store = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore()

priveteKey = new BasicSSHUserPrivateKey(
CredentialsScope.GLOBAL,
"jenkins-slave-key",
"root",
new BasicSSHUserPrivateKey.UsersPrivateKeySource(),
"",
""
)

usernameAndPassword = new UsernamePasswordCredentialsImpl(
CredentialsScope.GLOBAL,
"jenkins-slave-password", "Jenkis Slave with Password Configuration",
"root",
"jenkins"
)

store.addCredentials(domain, priveteKey)
store.addCredentials(domain, usernameAndPassword)

There are more kinds of credentials that can be stored. How do I do:

  • Secret file
  • Secret text

Solution

  • After some research, I found that the plain-credentials plugin implements the Secret Text and Secret File credentials. I forked the gist above and added code for these two types (see the gist for the reqwuired imports).

    https://gist.github.com/chrisvire/383a2c7b7cfb3f55df6a

    secretText = new StringCredentialsImpl(
    CredentialsScope.GLOBAL,
    "secret-text",
    "Secret Text Description",
    Secret.fromString("some secret text goes here"))
    
    file = new File("/path/to/some/file")
    noFileItem = [ getName: { return "" } ] as FileItem
    
    //FileCredentailsImpl can take a file from a do
    
    secretFile = new FileCredentialsImpl(
      CredentialsScope.GLOBAL,
      "secret-file",
      "Secret File Description",
      noFileItem, // Don't use FileItem
      file.getName(),
      file.text
    )
    
    store.addCredentials(domain, secretText)
    store.addCredentials(domain, secretFile)