Jenkins Extended Choice Parameter with groovy shell command - jenkins

I try to collect data for an Extended Choice Paramater.
I use the code:
def ingo = sh(script: 'mktemp', returnStdout: true)
return ingo
inside the groovy script part, but it seem that this is not allowed or well formated.
The choice is always empty. Anybody has some experience with shell command inside this part of the pipeline?
Sense is, I want to collect data with curl here. But simple shell query is not working.
Please see image

You can't execute Jenkins steps within the Extended Choice Parameter. You have to use pure Groovy within the Parameter. For example, if you want to do an HTTP call you can use a Groovy script like below. Here I'm fetching content from a GitHub file. A Full example can be found here.
def content = new URL ("https://raw.githubusercontent.com/xxx/sample/main/testdir/hosts").getText()

Related

How to approve script snippets from a jenkinsfile via the groovy script console?

In my jenkins pipeline file I use the JsonSlurperClassic to read build configurations from a .json file. This however introduces code that needs to be approved over the in-process Script Approval page. This works fine when I do it over the GUI.
However I also have a script that automatically sets up my jenkins machine which should create a ready-to-work machine that does not require further GUI operations. This script already uses the jenkins script console to approve slave start-up commands. The groovy code that is executed in the script console to do this looks like this.
def language = 'system-command';
def scriptSnippet = 'ssh me#slavemachine java -jar ~/bin/slave.jar';
def scriptApproval = Jenkins.instance.getExtensionList(
'org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval')[0];
def scriptHash = scriptApproval.hash(scriptSnippet, language);
scriptApproval.approveScript(scriptHash);
This works fine, but now I want to use the same code to approve the script
snippets that come from my pipeline. I exchanged the first two lines with
def language = 'groovy'
def scriptSnippet = 'new groovy.json.JsonSlurperClassic';
where the scriptSnippet is taken from the scriptApproval.xml file.
Executing this adds a new <approvedScriptHashes> entry to the scriptApproval.xml file but does not remove the <pendingSignature> entry that contains the script snippet. This means it does not work.
My guess is, that the language is wrong, but other values I tried like groovy-sh or system-commands did not work either. Do you have any ideas why it does not work?
Thank you for your time.
You can use ScriptApproval#approveSignature method. Here is an example that works on my Jenkins 2.85
def signature = 'new groovy.json.JsonSlurperClassic'
org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval.get().approveSignature(signature)
import org.jenkinsci.plugins.scriptsecurity.scripts.*
toApprove = ScriptApproval.get().getPendingScripts().collect()
toApprove.each {pending -> ScriptApproval.get().approveScript(pending.getHash())}
I know this is an old post, but I thought if anyone else is looking for answers then this could help. If you already have a list of known signatures for script approvals and if you would like to do all of the approvals at once, then the snippet mentioned in the below link works well.
Here's a groovy script to pre-populate script approvals

Trigger Jenkins Job for every parameter

I have created a Global choice Parameter using Extensible Choice Parameter plugin.
I am using this parameter list in one of my parametrized jenkins job.
Is there a way in jenkins, where I can execute the job with each of the parameters in the Global choice Parameter list?
I have had a look on Build Flow job in jenkins, as suggested in this answer, but it seems it accepts hardcoded parameters only, and not dynamic.
I finally managed to resolve this using the following steps (with great help from this post) -
As my parameters list is dynamic in nature, it could be added or modified according to other jobs, we have managed it in a text file.
Next, We have used Extensible Choice Parameter plugin to display the parameters, using the groovy script -
def list = [];
File file = new File("D:/JenkinJob/parameterList.txt")
file.eachLine { line ->
list.add("$line")
}
return list
Now I want to call this jenkins job for each of the parameter.
For this, I have installed, BuildFlow plugin, and crated a new jenkins job of BuildFlow type -
Next, get the Extended Choice Parameter plugin, and configure it as follows -
Now in the flow step of this job, write this script, where "Feature" is the parameter, that is just created above, and within call to "build" parameter, pass in the name of job which we want to call for each parameter -
def features = params['Features'].split(',')
for (feature in features ) {
build("JobYouWantToCall", JobParameter: feature,)
}

How to select the parameter coming from script output and pass it to next script or job in Bamboo?

I am trying to do below things in bamboo.I have script which basically shows the branches of hg repository.I know there is a plugin in Jenkins where you can run the script and get the output and use that output as a parameter to the job/script but I am not sure how to achieve this in Bamboo.Is there any plugin or some way to achieve this?
script abc.py which gives the below output
a
b
c
d
e
f
g
I want this script will run and it will give me the above output and then I can select anyone of them and pass it to my script.The value of the createBranch should come from the script so I can select any one of them
With Bamboo, it is impossible to create/change a variable value from within tasks due to concurrency issues it might create. There is a feature request open for this.
As a workaround, how about writing the script result out to a text file, then read it in from the file using Inject Variables plugin task. You can use this as a variable within the same stage to create a branch in your case.
Hope that helps.

How can I get all build numbers of particular job in jenkins using groovy script?

I am using active choice plugin, have groovy script which retrieves names of all jobs in Jenkins. Can I write a groovy script which get me list of all the build numbers of that particular job.
In order to get a list of builds for a particular job using the active choice plugin, You can use the following example.
First, create an active choice parameter for retriving the job names:
Then create an active choice parameter for retriving the build numbers from the selected job:
Try:
def xml=new XmlSlurper().parse("http:{serverName}/Jenkins/rssLatest")
def projects = xml.entry.collect{(it.title as String).split("#")[0].trim()}
println projects
In general I suggest browsing your jenkins feed for the info you want then look for an "rss feed" -- then put that rss URL into the XmlSlurper and see what you get.
Also I tend to work through these things in groovysh, it makes it really easy to explorer how objects work. In this case you might want to also be looking at the raw XML as you try objects in groovysh.
I would go over the REST-API (because there I know that it works):
http:///api/xml?tree=jobs[name,builds[result,description,id,number,url,timestamp]]&pretty=true&xpath=hudson/job[name='']&wrapper=jobs
This results in something like this:
<jobs>
<job _class="...">
<name>JOBNAME</name>
<build _class="...">
<id>66</id>
<number>66</number>
<result>FAILURE</result>
<timestamp>1489717287702</timestamp>
<url>JOB_URL</url>
</build>
...
</job>
<jobs>
So the following call in conjunction with an foreach-loop should do the trick.
def text = "rest_api_url".toURL().text
def jobs = new XmlSlurper().parseText(text.toString())
Otherwise something like this should also work - even I haven't tested it.
import jenkins.model.*
for(item in Jenkins.instance.items) {
if ("JOBNAME".equals(item.name)) {
// do something with $item.builds
// foreach item.builds -> ...
}
}

Post build in Jenkins with last parameters

I would like to know if is possible to set a post build triggering the job with the last parameters. I've found this plugin https://wiki.jenkins-ci.org/display/JENKINS/Rebuild+Plugin but I can't have a properly way to call, this plugin is based on last job index.
It's a short question but I was not able to find a properly fix / workaround for that.
I think you must save this parameters in some file in workspace folder for example settings.xml or something similar, you can in easy way make command like this:
sh """echo '<name>$PARAMETER_VALUE</name>' >> ./settings.xml"""
When you would like to read this parameter you could use sed option or something else like:
sh """awk '{if($1 == "name") print $2}' ./settings.xml"""

Resources