Configure matrix authorization plugin using Groovy script - jenkins

I am learning to write the groovy script to configure matrix authorization plugin. I have written this script where only authenticated users can access Jenkins:
import jenkins.model.*
import hudson.security.*
import com.cloudbees.hudson.plugins.folder.properties.AuthorizationMatrixProperty
try {
def instance = Jenkins.getInstance()
def realm = new HudsonPrivateSecurityRealm(false)
instance.setSecurityRealm(realm)
def strategy = new hudson.security.GlobalMatrixAuthorizationStrategy()
strategy.add(Jenkins.ADMINISTER, 'authenticated')
instance.setAuthorizationStrategy(strategy)
instance.save()
}
catch(Throwable exc) {
println '!!! Error configuring jenkins'
org.codehaus.groovy.runtime.StackTraceUtils.sanitize(new Exception(exc)).printStackTrace()
println '!!! Shutting down Jenkins to prevent possible mis-configuration from going live'
jenkins.cleanUp()
System.exit(1)
}
Now, I want to configure this matrix plugin in a way that nobody can access the Jenkins settings area(even authenticated users can not access the Jenkins settings). I have done lot of research on that and not able to move forward with this. Any help/pointer will be appreciated. Thanks!

I found an answer to that. Below is the complete code for the above requirement where I was missing Jenkins.READ.
import jenkins.model.*
import hudson.security.*
import com.cloudbees.hudson.plugins.folder.properties.AuthorizationMatrixProperty
try {
def instance = Jenkins.getInstance()
def realm = new HudsonPrivateSecurityRealm(false)
instance.setSecurityRealm(realm)
def strategy = new hudson.security.GlobalMatrixAuthorizationStrategy()
strategy.add(Jenkins.READ, 'authenticated')
instance.setAuthorizationStrategy(strategy)
instance.save()
}
catch(Throwable exc) {
println '!!! Error configuring jenkins'
org.codehaus.groovy.runtime.StackTraceUtils.sanitize(new
Exception(exc)).printStackTrace()
println '!!! Shutting down Jenkins to prevent possible mis-configuration from going live'
jenkins.cleanUp()
System.exit(1)
}

Related

Jenkins add Git Behaviors using groovy scripts

I'm creating my Jenkins instance using groovy scripts because I'm automating the Jenkins creation process. I create this script:
/* Adds a multibranch pipeline job to Jenkins */
import hudson.model.*
import hudson.util.PersistedList
import jenkins.*
import jenkins.branch.*
import jenkins.model.*
import jenkins.model.Jenkins
import jenkins.plugins.git.*
import com.cloudbees.hudson.plugins.folder.computed.PeriodicFolderTrigger
import org.jenkinsci.plugins.workflow.multibranch.*
// Create job
def env = System.getenv()
Jenkins jenkins = Jenkins.instance
String jobName = "Job"
String jobScript = "Jenkinsfile"
def job = jenkins.getItem(jobName)
// Create the folder if it doesn't exist
if (job == null) {
job = jenkins.createProject(WorkflowMultiBranchProject.class, jobName)
}
job.getProjectFactory().setScriptPath(jobScript)
// Add git repo
String id = null
String remote = env.CODE_COMMIT_URL
String includes = "*"
String excludes = ""
boolean ignoreOnPushNotifications = false
GitSCMSource gitSCMSource = new GitSCMSource(id, remote, null, includes, excludes, ignoreOnPushNotifications)
BranchSource branchSource = new BranchSource(gitSCMSource)
// Remove and replace?
PersistedList sources = job.getSourcesList()
sources.clear()
sources.add(branchSource)
job.addTrigger(new PeriodicFolderTrigger("1m"))
and paste it at $JENKINS_HOME/ref/init.groovy.d/. When I start Jenkins, by job was already created. Besides that, I need to add some Git Behaviors to my job and I'd like to know if is there a way to add Git Behaviors using groovy script?
My Git after created:
Git behaviors I'd like to add at initialization (Discover tags, Check out to matching local branch, Custom user name/e-mail address)
Thank you!
I think what you want is managed through traits (I haven't actually tried this):
import jenkins.plugins.git.traits.*
def traits = []
// Add your traits...
traits.add(new TagDiscoveryTrait())
traits.add(new LocalBranchTrait())
gitSCMSource.setTraits(traits)

Check if user is already created in Jenkins

How to check if user is already created in Jenkins on Groovy?
I am using this script for automatic creation of admin user https://github.com/foxylion/docker-jenkins/blob/master/docker-images/master/default-user.groovy but unfortunately it launches each time when docker container (with it) restarts. Consequently I lose my other manually created users in Jenkins GUI.
It looks like getSecurityRealm() will return an impl that will include HudsonPrivateSecurityRealm ... is so this looks like it will work:
import jenkins.model.*
import hudson.security.*
import org.acegisecurity.userdetails.UsernameNotFoundException
import org.springframework.dao.DataAccessException
def env = System.getenv()
def jenkins = Jenkins.getInstance()
jenkins.setSecurityRealm(new HudsonPrivateSecurityRealm(false))
jenkins.setAuthorizationStrategy(new GlobalMatrixAuthorizationStrategy())
def user = null;
try {
jenkins.getSecurityRealm().loadUserByUsername(env.JENKINS_USER);
} catch (UsernameNotFoundExceoption n) {
user = jenkins.getSecurityRealm().createAccount(env.JENKINS_USER, env.JENKINS_PASS)
user.save()
jenkins.getAuthorizationStrategy().add(Jenkins.ADMINISTER, env.JENKINS_USER)
jenkins.save()
} catch (org.springframework.dao.DataAccessException d) {
/// log
}

Groovy Script to add new phase job to multi-job in Jenkins

For the already available multi-job in jenkins, need to add new phase jobs using Groovy Scripting. I have written the following groovy code which adds up an already existing job p25_deploy-1.
This code is working to create the multi-job but the phase job is not showing as mapped in the Jenkins UI. Where as if I see it config.xml, its created properly as expected except a tag <killPhaseOnJobResultCondition>. Not sure why the phase job is not mapped properly?
import jenkins.model.*
import hudson.model.*
import com.tikal.jenkins.plugins.multijob.*
import com.tikal.jenkins.plugins.multijob.PhaseJobsConfig.*
import com.tikal.jenkins.plugins.multijob.PhaseJobsConfig.KillPhaseOnJobResultCondition.*
import java.lang.String.*
import hudson.model.Descriptor;
import hudson.tasks.Builder;
def jenkinsInstance = jenkins.model.Jenkins.instance
def templateJobName = 'profile_p25'
def templateJob = jenkinsInstance.getJob(templateJobName)
// get MultiJob BuildPhases and clone each PhaseJob
builders = templateJob.getBuilders();
builders.each { b ->
if (b instanceof MultiJobBuilder){
def pj = b.getPhaseJobs()
hudson.model.Describable p1 = new PhaseJobsConfig("p25_deploy-1",null,
true,PhaseJobsConfig.KillPhaseOnJobResultCondition NEVER,null,false,false,null,0,false,true,null,false,false)
pj.add(p1)
}
}
templateJob.save()
// update dependencies
jenkinsInstance.rebuildDependencyGraph()
Any help will be really appreciated. Have tried many ways but was not able to figure out the problem with the script.
We can use DSL to create but I wanted it to be done in Groovy Scripting and moreover modify the existing job.
Blockquote
Yay! I am back with the answer for my question. Have tried this since very long time. Finally am able to make it though. I was aware that solution would be really simple but not able to figure out the hack of it.
import jenkins.model.*
import hudson.model.*
import com.tikal.jenkins.plugins.multijob.*
import com.tikal.jenkins.plugins.multijob.PhaseJobsConfig.*
import com.tikal.jenkins.plugins.multijob.PhaseJobsConfig.KillPhaseOnJobResultCondition.*
import java.lang.String.*
import hudson.model.Descriptor
import hudson.tasks.Builder
def jenkinsInstance = jenkins.model.Jenkins.instance
def templateJobName = 'profile_p25'
def templateJob = jenkinsInstance.getJob(templateJobName)
// get MultiJob BuildPhases and clone each PhaseJob
builders = templateJob.getBuilders();
builders.each { b -> if (b instanceof MultiJobBuilder)
{ def pj =
b.getPhaseJobs()
hudson.model.Describable newphase = new
PhaseJobsConfig(deploys[i],null,
true,null,null,false,false,null,0,false,false,"",false,false)
newphase.killPhaseOnJobResultCondition = 'NEVER'
pj.add(newphase)
}
}
templateJob.save()

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.
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();
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")
);

EnvInject Error using Jenkins evaluated Groovy script

We have a evaluated Groovy script in Jenkins below:-
;
But the build is failing with error [EnvInject] - [ERROR] - [EnvInject] - [ERROR] - Problems occurs on injecting env vars as a build wrap: null
17:04:06 Finished: FAILURE.
Also how can I call the variable from Jenkins shell script to get last successful build date. -Thanks
def env = System.getenv()
def item = Jenkins.instance.getItem("")
def f=item.getLastFailedBuild()
println f.getTime()
def ff=env['item.getLastSuccessfulBuild()]
println ff.getTime().format("YYYY-MMM-dd HH:MM:SS")
println ff.getTime().format("dd-MM-yyyy")
def pa = new ParametersAction([new StringParameterValue('PARAMETER_NAME', ff)]);
Thread.currentThread().executable.addAction(pa)
println 'Script finished! \nenv variable
The easy answer is that on line 7 you have no closing quote here:
def ff=env['item.getLastSuccessfulBuild()]
However, that is not the last of your issues:
I don't think you want to use ff = env['item.getLastSuccessfulBuild()]'] but rather just a simple ff = item.getLastSuccessfulBuild()
You need to include the following import lines to be able to use the associated classes:
import jenkins.model.Jenkins
import hudson.model.ParametersAction
import hudson.model.StringParameterValue
The line item = Jenkins.instance.getItem("Fastlane_Test") doesn't work in my environment, even replacing "Fastlane_Test" with a job that exists.I've replaced it with item = Jenkins.instance.getItemByFullName("Fastlane_Test").
Also, for safety, you should test to ensure item isn't null
Finally, have you missed the Thread.currentThread().executable.addAction(pa) line out for a reason? You need to use it to add the new parameter to the running environment.
The following code should hopefully be a reasonable starting point, however please note that I've removed the line def env = System.getenv() since env isn't used anywhere else in the code later:
import jenkins.model.Jenkins
import hudson.model.ParametersAction
import hudson.model.StringParameterValue
def item = Jenkins.instance.getItemByFullName("Fastlane_Test")
if (item) {
def f=item.getLastFailedBuild()
println f.getTime()
def ff=item.getLastSuccessfulBuild()
println ff.getTime().format("YYYY-MMM-dd HH:MM:SS")
println ff.getTime().format("dd-MM-yyyy")
def pa = new ParametersAction([new StringParameterValue("LAST_GOOD", ff.getTime().toString())])
Thread.currentThread().executable.addAction(pa)
}
Hope you find this of assistance, although I see it's been a while since you posted the question.
Kind Regards
Thanks Nick!!
I added the below "execute system groovyscript" as part of Jenkins job and it worked:
import jenkins.model.Jenkins
`. def item = Jenkins.instance.getItem("Job")
def ff=item.getLastSuccessfulBuild()
println ff.getTime().format("yyyy-MM-dd")
def temp = ff.getTime().format("yyyy-MM-dd")
import hudson.model.*
def build = Thread.currentThread().executable
def pa = new ParametersAction([
new StringParameterValue("LAST_BUILD_DATE",temp)
])
build.addAction(pa)`

Resources