Adding Global Password to Jenkins with init.groovy

How can I add a global passwords to Jenkins through the init.groovy that runs at startup?

To be clear, in the Manage Jenkins -> Configure Jenkins page, there is a section titled "Global Passwords". I would like to add entries in that section via Groovy code during the startup of Jenkins.

I am trying to provision my jenkins environment through groovy code by using the init.groovy. I need to add global passwords through the EnvInject plugin. I can successfully add path to a file for the same plugin using this code:

def instance = Jenkins.getInstance()


DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties = 
    instance.getGlobalNodeProperties();

globalNodeProperties.add(
    new EnvInjectNodeProperty(false, "/var/lib/jenkins/secret.properties")
);

However, I am failing to understand the mechanics needed to programmatically add global passwords.

Upvotes: 0

Views: 1030

Answers (2)

imuchnik
imuchnik

Reputation: 36

Here is the code example that should work. It seems that save() method also adds it to GlobalNodeProperties, so you don't have to add to that collection manually.

import jenkins.model.*
import hudson.util.*
import hudson.slaves.NodeProperty
import hudson.slaves.NodePropertyDescriptor
import org.jenkinsci.plugins.envinject.*


def instance = Jenkins.getInstance()


DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties 
                 = instance.getGlobalNodeProperties();

envInjectNodeProperty= new EnvInjectNodeProperty(false, "/var/lib/jenkins/secret.properties" 
propDescriptor = envInjectNodeProperty.getDescriptor()

//password entry
def passEntry = new EnvInjectGlobalPasswordEntry("some_username", "password")
//password entries list, add you global password here
List<EnvInjectGlobalPasswordEntry> envInjectGlobalPasswordEntriesList= [passEntry];
propDescriptor.envInjectGlobalPasswordEntries = 
          envInjectGlobalPasswordEntriesList.toArray(
          new EnvInjectGlobalPasswordEntry[envInjectGlobalPasswordEntriesList.size()]
         );
propDescriptor.save();

Upvotes: 2

daggett
daggett

Reputation: 28599

https://github.com/jenkinsci/envinject-plugin/tree/master/src/main/java/org/jenkinsci/plugins/envinject

I did not try this plugin, but there is a class : EnvInjectGlobalPasswordEntry

i guess it could be like this:

globalNodeProperties.add(
    new EnvInjectGlobalPasswordEntry("pass-name", "the-password")
);

Upvotes: 0

Related Questions