Edit user in Jenkins via groovy script - jenkins

I am wondering if I can change password, username, email in Jenkins user. Because I am able to create user via groovy script like this:
import hudson.model.*
def user = instance.securityRealm.createAccount(userId, password)
user.addProperty(new Mailer.UserProperty(email));
instance.save()
Jenkins interface allows me to manage user credentials, but script which allow to change password/email/username would be very helpfull. I didnt find examples.
I tried many times with script like this, but It didnt work
import hudson.model.*
User user = User.getAll().get(1)
user.setProperty(newPassword)

Here's a simple code that works :
import jenkins.model.*
import hudson.security.*
import hudson.tasks.Mailer
def env = System.getenv()
def jenkins = Jenkins.getInstance()
if(!(jenkins.getSecurityRealm() instanceof HudsonPrivateSecurityRealm))
jenkins.setSecurityRealm(new HudsonPrivateSecurityRealm(false))
if(!(jenkins.getAuthorizationStrategy() instanceof GlobalMatrixAuthorizationStrategy))
jenkins.setAuthorizationStrategy(new GlobalMatrixAuthorizationStrategy())
// update admin Jenkins user account
def user = jenkins.getSecurityRealm().getUser('admin')
email= 'jenkins-admin#gmail.com'
user.addProperty(new Mailer.UserProperty(email));

For Jenkins Jenkins 2.361.1, I have used such Jenkins groovy script to update user's password:
User.getById("userName",false).addProperty(hudson.security.HudsonPrivateSecurityRealm.Details.fromPlainPassword("new-password"));
You can also easily run it from bash script or similar, given $USERNAME and $PASSWORD are set:
echo "script=User.getById(\"$USERNAME\",false).addProperty(hudson.security.HudsonPrivateSecurityRealm.Details.fromPlainPassword(\"$PASSWORD\"));" | \
curl -d #- --user admin:access_token http://<ip>:8080/scriptText

Related

How to use the credentials stored in Jenkins in a groovy script in jenkins DSL

I am using jenkins with Jobdsl to create jenkins jobs. I am trying to build a parameterized job by adding a groovy script in active choice parameter. The script uses a credential stored in jenkins credential, I am trying to fetch it in my script by using the code
import jenkins.model.*
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
credentialsId = '1672622gjj'
def jenkinsCredentials = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.Credentials.class,
Jenkins.instance,
null,
null
).find{it.id == credentialsId};
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class, Jenkins.instance, null, null ).find{
it.id == credentialsId}
println(creds.username)
println(creds.password)
This code gives me the credential name and password but the result of the branches is blank. I am using `creds.password` as the authorization token.
What I am doing wrong?
You can replace the string there the same way, you do already with your script name (+ the strings), yet this not groovy at all.
So this should work:
... "curl ... 'Authorization: token ${creds.password}' ...

How to get values of env vars by writing groovy script on jenkins script console?

I searched a lot for this problem but couldn't find working solution anywhere. Can anybody please help me out? I want to get already existing env vars value through jenkins script console.
You need to distinguish:
build environment variables:
def myVar = build.getBuildVariables().get('myVar')
system environment variables:
System.getenv('MY_VARIABLE')
If you see
groovy.lang.MissingPropertyException: No such property: manager for class: Script1
Check this answer, and define build first:
import hudson.model.*
def build = Thread.currentThread().executable
def buildNumber = build.number
According to this answer, in order to access env vars from Jenkins script console, do as follows :
import jenkins.model.*;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.EnvVars;
jenkins = Jenkins.instance;
EnvironmentVariablesNodeProperty prop = jenkins.getGlobalNodeProperties().get(EnvironmentVariablesNodeProperty.class)
EnvVars env = prop.getEnvVars()
def myVariable = env['MY_VAR']
The env vars listed in http://<JENKINS_URL>/env-vars.html are available for each build. In order to access these variables in the Jenkins script console you need to define first the build :
build = Jenkins.instance.getItemByFullName('JOB_NAME').getBuildByNumber(BUILD_NUMBER)
envvars = build.getEnvironment()
envvars.each{envvar ->
println envvar
}

Create docker image with latest jenkins

I'm using the latest Jenkins image (2.60.3) and then I would like to update the jenkins.war file that is in /usr/share/jenkins/jenkins.war to get an image with the latest version of it (2.73.3). I'm trying to achieve that using the following dockerfile:
FROM jenkins:latest
COPY jenkins.war /usr/share/jenkins/
I have the jenkins.war file in the same folder than the dockerfile. The issue I'm having is that for some reason the file doesn't get overwritten (there is the jenkins.war v2.60.3). Why that could be happening?
As commented, using the jenkins/jenkins image, I have (with the latest LTS):
FROM jenkins/jenkins:2.73.3
ARG http_proxy
ARG https_proxy
# Skip setup wizard
ENV JAVA_OPTS="-Djenkins.install.runSetupWizard=false"
USER root
RUN addgroup --system --gid 581 dtpdkr && \
adduser jenkins dtpdkr
USER jenkins
# Remove executors in master
COPY master-executors.groovy /usr/share/jenkins/ref/init.groovy.d/
# Set proxy based on proxy-password secret
COPY set-proxy.groovy /usr/share/jenkins/ref/init.groovy.d/
# Create admin based on secrets jenkins-adm-name and jenkins-adm-pass
COPY security.groovy /usr/share/jenkins/ref/init.groovy.d/security.groovy
# Install plugins
COPY plugins.txt /usr/share/jenkins/ref/plugins.txt
RUN /usr/local/bin/install-plugins.sh < /usr/share/jenkins/ref/plugins.txt
That does give me an installed Jenkins LTS image, with all the plugins I need.
Since I am behind a proxy, I had to configure it first:
$ more set-proxy.groovy
import hudson.model.*;
import jenkins.model.*;
def instance = Jenkins.getInstance()
final String name = "proxy.mycompany.com"
final int port = 8080
final String username = "unix_web_account"
def password = new File("/run/secrets/proxy_password").text.trim()
final String noProxyHost = "127.0.0.1,localhost,mycompany.com"
final def pc = new hudson.ProxyConfiguration(name, port, username, password, noProxyHost)
instance.proxy = pc
instance.save()
pc.save()
println "Proxy settings updated!"
And I need to define an admin account:
$ more security.groovy
#!groovy
import jenkins.model.*
import hudson.security.*
import jenkins.security.s2m.AdminWhitelistRule
def instance = Jenkins.getInstance()
def user = new File("/run/secrets/jenkins-adm-name").text.trim()
def pass = new File("/run/secrets/jenkins-adm-pass").text.trim()
println "Creating user " + user + "..."
def hudsonRealm = new HudsonPrivateSecurityRealm(false)
hudsonRealm.createAccount(user, pass)
instance.setSecurityRealm(hudsonRealm)
def strategy = new FullControlOnceLoggedInAuthorizationStrategy()
instance.setAuthorizationStrategy(strategy)
instance.save()
Jenkins.instance.getInjector().getInstance(AdminWhitelistRule.class).setMasterKillSwitch(false)
println "User " + user + " was created"
Finally, I don't want any job execution on the master:
$ more master-executors.groovy
import hudson.model.*;
import jenkins.model.*;
println "--> disabling master executors"
Jenkins.instance.setNumExecutors(0)

Jenkins: Automate CI Docker instance

I'm trying to setup Jenkins to be fully automated once I launch it from a docker container.
My question is how do I automate the configuration of the global Jenkins settings. For example the items in manage jenkins and credentials?
I'm using this a reference:
https://wiki.jenkins.io/display/jenkins/remote+access+api
Currently, I have the set these items up manually. I would like to fully automate the CI server creation. Is this possible with Jenkins or is there some human intervention that is required?
Any help would be greatly appreciated.
we used chef to setup the master , and it run some groovy scripts to install all the plugin and configuration. it almost done fully automatically , beside 1 or 2 plugins that I didn't find the syntax to configure all others works fine.
I installed all the plugins using Jenkins CLI , check yourJenkins/cli/ for reference.
for the general configuration you can install all the tools
import jenkins.model.*
import hudson.model.*
def inst1 = Jenkins.getInstance()
def desc1 = inst1.getDescriptor("hudson.tools.JDKInstaller")
println desc1.doPostCredential('buildJenkins#gmail.com','JenkinsOracleXXXXX')
import jenkins.model.*
import hudson.model.*
import hudson.tools.*
// JDK installation
def inst = Jenkins.getInstance()
def desc = inst.getDescriptor("hudson.model.JDK")
def versions = [
"jdk-1.8.101": "jdk-8u101-oth-JPR",
// "jdk-1.8.102": "jdk-8u102-oth-JPR"
]
general variables
// general properties
instance = Jenkins.getInstance()
globalNodeProperties = instance.getGlobalNodeProperties()
envVarsNodePropertyList = globalNodeProperties.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class)
newEnvVarsNodeProperty = null
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("ARTIFACTORY_URL", "artifactory-url")
envVars.put("ARTIFACTORY_USER", "jenkins")
envVars.put("DOCKER_USER", "docker-push")
instance.save()
email address
// admin Email
def jenkinsLocationConfiguration = JenkinsLocationConfiguration.get()
jenkinsLocationConfiguration.setAdminAddress('admin#yours.com')
jenkinsLocationConfiguration.save()
there a lot of examples , just look for groovy Jenkins configuration ..
if you have any specific question let me know.

Triggering a Job on start up in Jenkins

I am trying to get a new job to run every time my Jenkins restarts. I want to do this through "init.groovy" script. For example let's say if I restart my jenkins server it will execute a job that says "Hello world". And I have to create this job from my init.groovy script.
I have this code so far
import jenkins.model.Jenkins
import org.jenkinsci.plugins.workflow.job.WorkflowJob
WorkflowJob job = Jenkins.instance.createProject(WorkflowJob, 'my-pipeline2')
now I don't know how to configure this job instance without getting into the GUI. I want to add pipeline scripts to it. Like echo "Hello world". And then I want to finally build this job. I want to do all that from this one init.groovy script. I couldn't find any solution to this over internet. So any help is greatly appreciated. Thanks
You could also try the Startup Trigger plugin.
Once installed, go the Job that you want to trigger after startup and in the section 'Build Triggers', check 'Build when Jenkins first starts'
(This question may be old, but hope my answer helps someone)
So I have finally done this with the following groovy script.
#!groovy
import jenkins.model.*
import hudson.security.*
import jenkins.install.*;
import hudson.triggers.SCMTrigger;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
def instance = Jenkins.getInstance()
println "--> creating local user 'admin'"
def hudsonRealm = new HudsonPrivateSecurityRealm(false)
hudsonRealm.createAccount('admin','admin')
instance.setSecurityRealm(hudsonRealm)
def strategy = new FullControlOnceLoggedInAuthorizationStrategy()
instance.setAuthorizationStrategy(strategy)
instance.save()
jenkins = Jenkins.instance;
workflowJob = new WorkflowJob(jenkins, "workflow2");
jobName = "create-dsl-job2";
gitTrigger = new SCMTrigger("* * * * *");
dslProject = new hudson.model.FreeStyleProject(jenkins, jobName);
dslProject.addTrigger(gitTrigger);
jenkins.add(dslProject, jobName);
job = jenkins.getItem(jobName)
builders = job.getBuildersList()
hudson.tasks.Shell newShell = new hudson.tasks.Shell("echo \"Hello\" ")
builders.replace(newShell)
gitTrigger.start(dslProject, true);

Resources