groovy script to remove users from jenkins project role alone? - jenkins

import hudson.security.*
import jenkins.security.*
import jenkins.model.Jenkins
def sids = Jenkins.instance.authorizationStrategy.getAllSIDs()
return sids
In the Build Section;
def removeAMP(Job jobName, user ) {
println jobName.name.center(80,'-')
def authorizationMatrixProperty = jobName.getProperty(AuthorizationMatrixProperty.class)
Map<Permission,Set<String>> Permissions = authorizationMatrixProperty.getGrantedPermissions()
println "Permission Map Before: " + Permissions + cr
println "Permission Values: " + Permissions.values() + cr
for (Set<String> permissionUsers:Permissions.values()) {
permissionUsers.remove(user)
}
println "Permission Map After: " + Permissions + cr
jobName.save();
}
I created a job in jenkins with "Execute system grrovy script" for removing users from project role not from jenkins global role.with following scripts,but am getting error as follows:
ERROR: Build step failed with exception
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 10: unable to resolve class Job
# line 10, column 19.
def removeAMP(Job jobName, user ) {
^
1 error
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:302)
at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:861)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:550)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:499)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:302)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:281)
at groovy.lang.GroovyShell.parseClass(GroovyShell.java:731)
at groovy.lang.GroovyShell.parse(GroovyShell.java:743)
at groovy.lang.GroovyShell.parse(GroovyShell.java:723)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:680)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:666)
at hudson.plugins.groovy.SystemGroovy.perform(SystemGroovy.java:81)
at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:782)
at hudson.model.Build$BuildExecution.build(Build.java:205)
at hudson.model.Build$BuildExecution.doRun(Build.java:162)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:534)
at hudson.model.Run.execute(Run.java:1738)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:98)
at hudson.model.Executor.run(Executor.java:410)
Build step 'Execute system Groovy script' marked build as failure
Finished: FAILURE
Please help me with correct script.Thanks in advance
Ashif

Do you need to add
import hudson.model.Job

Related

WorkflowScript: 1: unable to resolve class groovy.yaml.YamlSlurper

I am use the Jenkins docker container to run Jenkins. I have this pipeline:
import groovy.yaml.YamlSlurper
def wholeFileData
def ys = new YamlSlurper()
pipeline {
agent any
stages {
...
... and I get this error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 1: unable to resolve class groovy.yaml.YamlSlurper
# line 1, column 1.
import groovy.yaml.YamlSlurper
^
How can I fix this?

Trigger a script on windows remote environment (VM) using jenkins

I have 2 windows servers, one server(development) has Jenkins on it and both the servers have OPEN SSH installed in them.
I want to trigger the script(batch script) on my testing server through Jenkins. I tried writing the pipeline but it is showing an error.
I refered to https://github.com/jenkinsci/ssh-steps-plugin and wrote a pipeline as given below.
node {
def remote = [http://inb*****.com]
remote.name = 'inb***'
remote.host = 'http://inb*****.com'
remote.user = 'jenkinsSSH'
remote.password = '********34'
remote.allowAnyHosts = true
stage('Remote SSH') {
writeFile file: 'abc.bat', text: 'ls -lrt'
sshScript remote: remote, script: "abc.bat"
}
}
The output which I am getting is given below,
Running in Durability level: MAX_SURVIVABILITY
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 12: unexpected token: } # line 12, column 1.
}
^
1 error
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
at org.codehaus.groovy.control.ErrorCollector.addFatalError(ErrorCollector.java:150)
at org.codehaus.groovy.control.ErrorCollector.addError(ErrorCollector.java:120)
at org.codehaus.groovy.control.ErrorCollector.addError(ErrorCollector.java:132)
at org.codehaus.groovy.control.SourceUnit.addError(SourceUnit.java:350)
at org.codehaus.groovy.antlr.AntlrParserPlugin.transformCSTIntoAST(AntlrParserPlugin.java:144)
at org.codehaus.groovy.antlr.AntlrParserPlugin.parseCST(AntlrParserPlugin.java:110)
at org.codehaus.groovy.control.SourceUnit.parse(SourceUnit.java:234)
at org.codehaus.groovy.control.CompilationUnit$1.call(CompilationUnit.java:168)
at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:943)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:605)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:142)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:127)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:571)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:523)
at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:337)
at hudson.model.ResourceController.execute(ResourceController.java:100)
at hudson.model.Executor.run(Executor.java:433)
Finished: FAILURE
I have written a simple batch file - " echo hello " and saved it as abc.bat in the test server.
This is where I am stuck, If there is another method to run the script on the testing server through Jenkins then also please let me know it will be of great help.
You have an error in this line:
def remote = [http://inb*****.com]
It should be
def remote = [:]
to create an empty map.

Jenkins pipeline script error WorkflowScript: Expected a step

I have created a testcase from a much bigger Jenkins pipeline project and it works fine.
pipeline {
agent none
stages {
stage ("Check Parameters")
{
steps {
echo "In pipeline"
script {
echo "Start condition check"
}
build job: 'printuser'
//def slaveJob = build job: 'printuser'
//println slaveJob.rawBuild.log
}
}
}
}
Howevr, inorder to get the output of printuser job onto the pipeline i comment build job: 'printuser' and uncomment the slaveJob code as below:
//build job: 'printuser'
def slaveJob = build job: 'printuser'
println slaveJob.rawBuild.log
It now fails with the below error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 13: Expected a step # line 13, column 15.
def slaveJob = build job: 'printuser'
^
1 error
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1085)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:133)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:126)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:561)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:522)
at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:320)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE
Can you please suggest what is the issue here ?
If you want to use groovy, you must put it inside the script section, not outside:
script {
echo "Start condition check"
build job: 'printuser'
def slaveJob = build job: 'printuser'
println slaveJob.rawBuild.log
}
PS: not sure your code will work as such, but you should at least put it inside the script part. Outside of the script closure, jenkins will only accept a set of predefined steps.

How to add timestamp for artifacts in Jenkins

I have following Jenkisfile and I'm trying to upload the artifacts with a timestamp.
import groovy.transform.Field
#Field def timeStamp = Calendar.getInstance().getTime().format('YYYYMMdd-hhmmss',TimeZone.getTimeZone('CST'))
node {
stage('Creating some artifacts') {
sh 'touch hello.txt hi.txt'
}
stage('Uploading artifacts') {
def server = Artifactory.server ('art-1')
def uploadSpec = """{
"files": [
{
"pattern": "*.txt",
"target": "repo1/Dev/${env.BUILD_NUMBER}/*.txt.${timeStamp}"
}
]
}"""
def buildInfo1 = server.upload(uploadSpec)
server.publishBuildInfo(buildInfo1)
}
}
However, I'm getting the following error while trying this.
[consumer_1] Deploying artifact: http://learner.blr.example.com:8081/artifactory/repo1/Dev/12/*.txt.20180913-044451
[Thread consumer_1] An exception occurred during execution:
java.lang.RuntimeException: java.io.IOException: Failed to deploy file. Status code: 500 Response message: Artifactory returned the following errors:
Invalid path. '*' is not a valid name character: repo1/Dev/12/*.txt.20180913-044451 Status code: 500
at org.jfrog.build.extractor.clientConfiguration.util.spec.SpecDeploymentConsumer.consumerRun(SpecDeploymentConsumer.java:44)
at org.jfrog.build.extractor.producerConsumer.ConsumerRunnableBase.run(ConsumerRunnableBase.java:11)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.IOException: Failed to deploy file. Status code: 500 Response message: Artifactory returned the following errors:
Invalid path. '*' is not a valid name character: repo1/Dev/12/*.txt.20180913-044451 Status code: 500
at org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBuildInfoClient.uploadFile(ArtifactoryBuildInfoClient.java:692)
at org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBuildInfoClient.doDeployArtifact(ArtifactoryBuildInfoClient.java:374)
at org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBuildInfoClient.deployArtifact(ArtifactoryBuildInfoClient.java:362)
at org.jfrog.build.extractor.clientConfiguration.util.spec.SpecDeploymentConsumer.consumerRun(SpecDeploymentConsumer.java:39)
... 2 more
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.lang.Exception: Error occurred during operation, please refer to logs for more information.
at org.jfrog.build.extractor.producerConsumer.ProducerConsumerExecutor.start(ProducerConsumerExecutor.java:84)
at org.jfrog.build.extractor.clientConfiguration.util.spec.SpecsHelper.uploadArtifactsBySpec(SpecsHelper.java:71)
at org.jfrog.hudson.generic.GenericArtifactsDeployer$FilesDeployerCallable.invoke(GenericArtifactsDeployer.java:190)
Caused: java.lang.RuntimeException: Failed uploading artifacts by spec
at org.jfrog.hudson.generic.GenericArtifactsDeployer$FilesDeployerCallable.invoke(GenericArtifactsDeployer.java:194)
at org.jfrog.hudson.generic.GenericArtifactsDeployer$FilesDeployerCallable.invoke(GenericArtifactsDeployer.java:131)
at hudson.FilePath.act(FilePath.java:1042)
at hudson.FilePath.act(FilePath.java:1025)
at org.jfrog.hudson.pipeline.executors.GenericUploadExecutor.execution(GenericUploadExecutor.java:52)
at org.jfrog.hudson.pipeline.steps.UploadStep$Execution.run(UploadStep.java:65)
at org.jfrog.hudson.pipeline.steps.UploadStep$Execution.run(UploadStep.java:46)
at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1$1.call(AbstractSynchronousNonBlockingStepExecution.java:47)
at hudson.security.ACL.impersonate(ACL.java:290)
at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1.run(AbstractSynchronousNonBlockingStepExecution.java:44)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Finished: FAILURE
Are there any alternative/simple way to add timestamp in artifacts in Jenkins?
P.S.: I'm new to Jenkins groovy scripting and JFrog
The error message says that * is an invalid character for a file name so I don't think you can use it in the target field. However, the artifactory docs say you can do this instead (links for docs bellow):
def uploadSpec = """{
"files": [
{
"pattern": "(*).txt",
"target": "repo1/Dev/${env.BUILD_NUMBER}/{1}.txt.${timeStamp}"
}
]
In this code, {1} stands for "whatever got matched inside the first parenthesis in the pattern" (every open+close parenthesis in a regex defines a capture group).
Note: I don't use artifactory so I didn't test the above code, I am going off of the artifactory docs:
https://www.jfrog.com/confluence/display/RTF/Using+File+Specs
https://www.jfrog.com/confluence/display/RTF/Using+File+Specs#UsingFileSpecs-UsingPlaceholders
I'd also suggest you move the timestamp to the file name instead of the file extension, so that when you download the file, your computer knows which program to use to open it. So i'd change target to something like:
files shorted fist by name then by timestamp: repo1/Dev/${env.BUILD_NUMBER}/{1}-${timeStamp}.txt
files shorted fist by timestamp then by name:
repo1/Dev/${env.BUILD_NUMBER}/${timeStamp}-{1}.txt

NULL pointer Exception in Groovy postbuild Script

I am using the build flow project for combining the two different project test results.Then i am in need to change the build status of the aggregated test results so i am using groovy postbuild to change my build status.In that script if any one of the test fails gets failed in any of the projects then i am trying to change the build status to unstable.For that i am calculating the fail counts from both results using groovy script.But when i am trying this it throws the NULL pointer Exception.
The script i used in the groovy postbuild is
def testResult = manager.build.testResultAction.result
def fail = testResult.failCount
if(fail==NULL)
{ manager.buildSuccess() }
else
{ manager.buildUnstable() }
It throws the exception as
ava.lang.NullPointerException: Cannot get property 'result' on null object
at org.codehaus.groovy.runtime.NullObject.getProperty(NullObject.java:56)
at org.codehaus.groovy.runtime.InvokerHelper.getProperty(InvokerHelper.java:156)
at org.codehaus.groovy.runtime.callsite.NullCallSite.getProperty(NullCallSite.java:44)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:227)
at Script1.run(Script1.groovy:1)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:580)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:618)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:589)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript.evaluate(SecureGroovyScript.java:166)
at org.jvnet.hudson.plugins.groovypostbuild.GroovyPostbuildRecorder.perform(GroovyPostbuildRecorder.java:362)
at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:782)
at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:723)
at hudson.model.Build$BuildExecution.post2(Build.java:185)
at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:668)
at hudson.model.Run.execute(Run.java:1763)
at hudson.model.FreeStyleBuild.run``(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:98)
at hudson.model.Executor.run(Executor.java:410)
Activity

Resources