To create a new user in Jenkins, admin needs to provide a username, emialID and password. Being an admin, is there a way to add a large number of users to Jenkins at a time by providing their username as their mail id, display name as their name and a common password*?
*Assuming that password will be reset at the time of each user logging in
I am using the below groovy script to add a user to Jenkins and provide only build permission.
import hudson.model.*
import hudson.security.*
import hudson.tasks.Mailer
def userId = args[0]
def password = args[1]
def email = args[2]
def fullName= args[3]
def instance = jenkins.model.Jenkins.instance
def existingUser = instance.securityRealm.allUsers.find {it.id == userId}
if (existingUser == null) {
def user = instance.securityRealm.createAccount(userId, password)
user.addProperty(new Mailer.UserProperty(email));
user.setFullName(fullName)
def strategy = (GlobalMatrixAuthorizationStrategy)
instance.getAuthorizationStrategy()
strategy.add(hudson.model.Item.BUILD,userId)
instance.setAuthorizationStrategy(strategy)
instance.save()
}
The script is invoked using jenkins-cli.
It is easier to connect Jenkins to LDAP. See this plugin here
looks like the Jenkins cli doesn't support add users , but check this one - using groovy script you can do it.
Creating user in Jenkins via API
if you want give specific permissions per job , maybe you can use the CLI get-job & update-job commands.
Or you can try check this one - Jenkins Add permissions to jobs using groovy it discuses almost the same ...
Related
we store a GitHub account in one of the AD User attribute. When receiving a Pull Request webhook from GitHub I want to find a user based on GitHub Account and notify user about tests results. How to do that?
if I understand you correctly you want to take email attribute value by another user attribute. can't test the following code but it should give you an idea how to do that.
import javax.naming.directory.InitialDirContext
import javax.naming.directory.DirContext
Properties ldapProps = [
'java.naming.factory.initial' :'com.sun.jndi.ldap.LdapCtxFactory',
'java.naming.security.authentication':'simple',
'java.naming.provider.url' :'ldap://ldap-host:389',
'java.naming.security.principal' :'ldap-access-username',
'java.naming.security.credentials' :'ldap-access-password',
] as Properties
String user = 'user-to-search'
String attr = 'mail' //attribute name for email could be different in your ldap
String ldapFilter = "CN=${user}" //put instead of `CN` git attribute
String[] attrValues = [] //array because could be several values for one attribute
DirContext ldapCtx = new InitialDirContext(ldapProps)
ldapCtx.search("", ldapFilter, null).each{ldapUser->
def ldapAttr = ldapUser.getAttributes().get(attr)
attrValues = ldapAttr?.getAll()?.collect{it.toString()}
}
ldapCtx.close()
println "found values: $attrValues"
I am trying to extract the username and password in jenkins groovy script who has initiated the build. I need these details to post comments on jira from my name.
So for eg.. I login into jenkins and start a job, then my login credentials should be used to post the comment on jira..
I tried alot of posts but didnt find anytihng related to my requirement.
Any help will be appreciated..
after few seconds of Googling, I found this script officially published by cloudbees.
So, as follows:
Jenkins.instance.getAllItems(Job).each{
def jobBuilds=it.getBuilds()
//for each of such jobs we can get all the builds (or you can limit the number at your convenience)
jobBuilds.each { build ->
def runningSince = groovy.time.TimeCategory.minus( new Date(), build.getTime() )
def currentStatus = build.buildStatusSummary.message
def cause = build.getCauses()[0] //we keep the first cause
//This is a simple case where we want to get information on the cause if the build was
//triggered by an user
def user = cause instanceof Cause.UserIdCause? cause.getUserId():""
//This is an easy way to show the information on screen but can be changed at convenience
println "Build: ${build} | Since: ${runningSince} | Status: ${currentStatus} | Cause: ${cause} | User: ${user}"
// You can get all the information available for build parameters.
def parameters = build.getAction(ParametersAction)?.parameters
parameters.each {
println "Type: ${it.class} Name: ${it.name}, Value: ${it.dump()}"
}
}
}
You will get the user ID of the user, which start the job, for sure you will not be able to get his credentials, at least not in the plain text.
Little explanation
//to get all jobs
Jenkins.instance.getAllItems(Job)
{...}
//get builds per job
def jobBuilds=it.getBuilds()
//get build cause
def cause = build.getCauses()[0] //we keep the first cause
//if triggered by an user get id, otherwise empty string
def user = cause instanceof Cause.UserIdCause? cause.getUserId():""
I am trying to run some AJAX on the frontend of a Jenkins build configuration page. To be exact to have a dropdown selection of available databases on a remote server. How do I accomplish this?
In case you need a dynamic list you can use Active Choice Parameter and add a groovy script to generate dynamic list from a remote api call.
below is an example i use to generate list of vpc's from aws :
#!groovy
def sout = new StringBuffer(), serr = new StringBuffer()
def process = [ "aws", "ec2", "describe-vpcs", "--query", "Vpcs[*].[Tags[?Key==`Name`].Value]"].execute()
process.consumeProcessOutput(sout, serr)
process.waitFor();
def s3_vpcs = sout.tokenize('\n')
def vpcs = []
for ( vpc in s3_vpcs) {
vpcs.add(vpc)
}
return vpcs
I have a parametrized jenkins job with 2 parameters:
1st job parameter is APIKEY of type 'Password parameter'
2nd job parameter is SERVICE of type 'Active Choices Reactive Parameter' - single select, referencing parameter APIKEY and using following groovy script code which returns value of APIKEY parameter in the single select UI control:
[ APIKEY ]
When I start the build of this job, value offered in single select UI control for parameter SERVICE is garbled (encrypted?) value of APIKEY.
What I want is to be able to use actual (decrypted) value of entered APIKEY password parameter in the script code of SERVICE parameter.
I tried decrypting the APIKEY garbled value by using hudson.util.Secret like below but with no luck:
def apikey = hudson.util.Secret.fromString(APIKEY).getPlainText()
Is there any way to get actual password parameter value from active choices reactive parameter groovy script code?
After a little bit more trying this out it turns out this is working properly after all - but only when password parameter is entered manually, not with the default password parameter value (not sure if this is a bug or a feature).
First time the job is run default password parameter value provided is garbled, but entering the value again in the password field then gives the correct value in groovy script.
This worked for me:
run job build
at this point APIKEY value in groovy script code of the SERVICE field is not evaluated correctly - it is garbled value
enter correct value in APIKEY password parameter field - e.g. "abc123"
switch focus to SERVICE field
SERVICE field groovy code gets executed now and shows actual entered value of APIKEY: "abc123"
Since my use case is such that entering APIKEY is mandatory every time job is build this is good enough for me.
This is an old topic, but I found a solution so I'll add it here in case anyone else still needs it. This was working code, but I sanitized it for publication.
This Groovy script runs in an Active Choices Reactive Parameter. The task is to provide a list of the build versions available to deploy from an internal Artifactory archive. The API key needed for the REST call is stored as Secret Text in our Jenkins instance. So this code reads from the Credentials plugin's repo to find the secret text, then adds it to the header of the http request.
This is a clunky solution. There is much more elegant withCredentials method for Groovy, but it may only work in Jenkins pipelines. I didn't find a way to use it in this parameter.
This solution also does not use HTTPBuilder, which would have been simpler, but wasn't available in our Groovy plugin.
import org.apache.http.client.methods.*
import org.apache.http.impl.client.*
import groovy.json.JsonSlurper;
def APP_FULL_NAME = "My.Project.Name"
def request = new HttpGet("https://fakeDns/artifactory/api/search/versions?r=releases&a="+APP_FULL_NAME)
def jenkinsCredentials = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.Credentials.class,
Jenkins.instance,
null,
null
);
def apiKey
for (creds in jenkinsCredentials)
{
//println creds.id
//println creds.class
if(creds.id == "my_target_api_key")
{
apiKey = creds.secret.toString(creds.secret);
break
}
}
request.addHeader("X-API-KEY", apiKey)
def responseString = new DefaultHttpClient().execute(request, new BasicResponseHandler());
def branchList = new JsonSlurper().parseText(responseString)
//return branchList
def myList= []
branchList.results.each { myList << it }
return myList.version
Use Case : A single user with “single user name” should be able to use data available in different tenant without relogin.
Expected Flow :
User “A” login into tenant 1
He done some activity and able to access all tenant 1 data
He clicks on the “switch tenant” link and after that he should be able to access all data related to Tenant 2
Environment :
Grails v2.1
spring-security-core v1.2.7.3
multi-tenant-single-db v0.8.3
I am using following auto generated class
SpringSecurityTenantRepository
SpringSecurityTenantResolver
I used following code in controller but it did not work.
def switchedTenentId = params.switchedTenentId
if(switchedTenentId != null && !"".equals(switchedTenentId))
{
def currUser = springSecurityService.currentUser
springSecurityService.currentUser.userTenantId = new Long(switchedTenentId)
}
I googled but did not find any solution. I like to know the logic, solution or any sample code.
Thanks
Here is what I did:
User u = User.get(springSecurityService.currentUser.id)
u.userTenantId = params.switchedTenentId.toInteger()
u.save flush: true
springSecurityService.reauthenticate u.username
It worked like a charm.