I found this groovy script to create a global environment variable in
Jenkins.
Env.groovy:
import hudson.EnvVars;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.util.DescribableList;
import jenkins.model.Jenkins;
public createGlobalEnvironmentVariables(String key, String value){
Jenkins instance = Jenkins.getInstance();
DescribableList<NodeProperty<?>, NodePropertyDescriptor>
globalNodeProperties = instance.getGlobalNodeProperties();
List<EnvironmentVariablesNodeProperty> envVarsNodePropertyList =
globalNodeProperties.getAll(EnvironmentVariablesNodeProperty.class);
EnvironmentVariablesNodeProperty newEnvVarsNodeProperty = null;
EnvVars envVars = null;
if ( envVarsNodePropertyList == null ||
envVarsNodePropertyList.size() == 0 ) {
newEnvVarsNodeProperty = new
hudson.slaves.EnvironmentVariablesNodeProperty();
globalNodeProperties.add(newEnvVarsNodeProperty);
envVars = newEnvVarsNodeProperty.getEnvVars();
} else {
envVars = envVarsNodePropertyList.get(0).getEnvVars();
}
envVars.put(key, value)
instance.save()
}
createGlobalEnvironmentVariables('xyzabc','baymac')
Using Jenkins CLI with the command to execute the above script
java -jar "jenkins-cli.jar" -s 'https://my.jenkins.instance' -noKeyAuth -auth
".jenkins-cli-auth" groovy = <
where .jenkins-cli-auth is `<User ID>:<API Token>`
The env variables are populated
[image: Screenshot from 2019-06-12 06-19-33.png]
Now the question is, is it a good idea to recommend users to populate env
with GitLab Personal Access Token using this method before performing a
jcasc reload?
Also I think it would be better to store env variables values in a password
form rather than plain text.
On Tuesday, June 11, 2019 at 8:24:32 AM UTC+5:30, Parichay Barpanda wrote:
>
> Hi all,
>
> I am trying to figure out a way to add an environment variable to Jenkins
> without using the UI. Is there a way to do it via API? The intention is to
> let user add credentials to Jenkins without using UI. Please let me know if
> you have a solution to this.
>
> Thanks.
>
> Regards,
> Parichay (baymac)
>
>
>
--
You received this message because you are subscribed to the Google Groups
"Jenkins Developers" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/jenkinsci-dev/b1b6ad46-b08f-4eca-9ee1-5ff6550e5990%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.