How to pass parameter to groovy post build in jenkins? - jenkins

I have the following Groovy Postbuild script in a jenkins job:
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.net.URL
import java.net.URLConnection
def sendPostRequest(urlString, paramString) {
def url = new URL(urlString)
def conn = url.openConnection()
conn.setDoOutput(true)
def writer = new OutputStreamWriter(conn.getOutputStream())
writer.write(paramString)
writer.flush()
String line
def reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))
while ((line = reader.readLine()) != null) {
println line
}
writer.close()
reader.close()
}
def result =" Project: *Autotests* \n Version *manager.build.buildVariables.get("VERSION_CURR")* \n"
sendPostRequest("https://api.telegram.org/bot{token}/sendMessage", "parse_mode=Markdown&chat_id={id_Chat}&reply_to_message_id=&text=${result}")
But I am getting an error: "groovy.lang.MissingPropertyException: No such property: VERSION_CURR for class: Script1"
However, I have a string parameter:
i also tried: def result =' Project: *Autotests* \n Version *${VERSION_CURR}* \n'

Related

Static type checking The variable jiraHelper/issue is undeclared

I am using a condition in my script in the REST endpoint and I am receiving the following errors:
Anyone knows what the problem is and what needs to be fixed?
Here is the code:
package CreateMultipleSubtasks
import org.apache.log4j.Logger
import com.atlassian.jira.plugin.webfragment.model.JiraHelper
import com.atlassian.jira.component.ComponentAccessor
def log1 = Logger.getLogger("atlassian-jira.log")
log1.warn("MOUNA BEFORE")
Configuration_CreateMultipleSubtasks conf = new Configuration_CreateMultipleSubtasks()
def subTaskCreatorHashMap= conf.getSubTaskCreatorHashMap()
String projectKey = subTaskCreatorHashMap["projectKey"];
String issueTypeName = subTaskCreatorHashMap["issueTypeName"];
log.warn("MOUNA PROJECT KEY "+ projectKey+" issuetypename "+issueTypeName)
def val=jiraHelper.project?.key==projectKey && issue.issueType.name==issueTypeName
return val

Install Snyk in Jenkins "Global Tool Configuration" using groovy

I'm trying to add a Snyk installation to Jenkins using groovy. The plugin is installed and I can see the installation option in Global Tool Configuration:
The problem is the Descriptor is not available until I manually add the installer and click Save. If I don't do this task manually, which I want to prevent, it causes my code to fail with the following error message "Cannot invoke method setInstallations() on null object"
My code:
import hudson.model.*
import jenkins.model.*
import hudson.tools.*
import hudson.tasks.*
import io.snyk.jenkins.tools.SnykInstaller
import io.snyk.jenkins.tools.SnykInstallation
def snyk_name = "Snyk"
def snyk_home = ""
def snyk_installer = new SnykInstaller("", "latest", 24)
def snyk_properties = new InstallSourceProperty([snyk_installer])
def instance = Jenkins.getInstance()
println("[init.groovy.d] START Configuring Snyk Installation...")
// Get the GlobalConfiguration descriptor of Snyk plugin.
def snyk_conf = instance.getDescriptor("io.snyk.jenkins.SnykStepBuilder.SnykStepBuilderDescriptor")
def snyk_inst = new SnykInstallation(
snyk_name,
snyk_home,
[snyk_properties]
)
// Only add the new Snyk setting if it does not exist - do not overwrite existing config
def snyk_installations = snyk_conf.getInstallations()
def snyk_inst_exists = false
snyk_installations.each {
installation = (SnykInstallation) it
if (snyk_inst.getName() == installation.getName()) {
snyk_inst_exists = true
println("Found existing installation: " + installation.getName())
}
}
if (!snyk_inst_exists) {
snyk_installations += snyk_inst
snyk_conf.setInstallations((SnykInstallation[]) snyk_installations)
snyk_conf.save()
}
// Save the state
instance.save()
println("[init.groovy.d] END")
Is there any way to do what I want programmatically?
After testing your groovy on my local Jenkins (v 2.263.1) I came up with the below which then worked for me:
import hudson.model.*
import jenkins.model.*
import hudson.tools.*
import hudson.tasks.*
import io.snyk.jenkins.tools.*
def instance = Jenkins.getInstance()
def snyk_name = "SnykLatest"
def snyk_home = ""
def snyk_installer = new SnykInstaller("", "latest", 24L, null)
def snyk_properties = new InstallSourceProperty([snyk_installer])
println("[init.groovy.d] START Configuring Snyk Installation...")
// Get the GlobalConfiguration descriptor of Snyk plugin.
def snyk_conf = instance.getDescriptor("io.snyk.jenkins.tools.SnykInstallation")
def snyk_inst = new SnykInstallation(
snyk_name,
snyk_home,
[snyk_properties]
)
// Only add the new Snyk setting if it does not exist - do not overwrite existing config
def snyk_installations = snyk_conf.getInstallations()
def snyk_inst_exists = false
snyk_installations.each {
installation = (SnykInstallation) it
if (snyk_inst.getName() == installation.getName()) {
snyk_inst_exists = true
println("Found existing installation: " + installation.getName())
}
}
if (!snyk_inst_exists) {
snyk_installations += snyk_inst
snyk_conf.setInstallations((SnykInstallation[]) snyk_installations)
snyk_conf.save()
}
// Save the state
instance.save()
println("[init.groovy.d] END")
In basic Terms the SnykInstaller was expecting 4 values not 3. Groovy also took the 3rd value as an Integer when it was expecting a Long Value.
References:
https://javadoc.jenkins.io/plugin/snyk-security-scanner/io/snyk/jenkins/tools/SnykInstaller.html
https://github.com/jenkinsci/snyk-security-scanner-plugin/blob/master/src/main/java/io/snyk/jenkins/tools/SnykInstaller.java
https://github.com/jenkinsci/snyk-security-scanner-plugin/blob/master/src/main/java/io/snyk/jenkins/tools/PlatformItem.java

How to minimize the complexity of this code ,by avoiding it to traverse all the jenkins job(lets say 5000 jobs?)

I'm changing my jenkins job's SCM url from, lets say gitlab to github by using Groovy script. Is there any way to minimize the complexity of this code ?
I have used Jenkins.instance.items.each {} which traverses through all the jobs in my jenkins
import hudson.plugins.git.*
import jenkins.*
import jenkins.model.*
def modifyGitUrl(url) {
def newurl = url.replace("source", "destination")
return newurl
}
def modifyGitID(credentialsId) {
def newID = ("Jenkins User ID")
return newID
}
Jenkins.instance.items.each {
if(it.name == "expected name"){
if (it.scm instanceof GitSCM) {
def oldScm = it.scm
def newUserRemoteConfigs = oldScm.userRemoteConfigs.collect {
new UserRemoteConfig(modifyGitUrl(it.url), it.name, it.refspec, modifyGitID(it.credentialsId))
}
def newScm = new GitSCM(newUserRemoteConfigs, oldScm.branches, oldScm.doGenerateSubmoduleConfigurations,
oldScm.submoduleCfg, oldScm.browser, oldScm.gitTool, oldScm.extensions)
it.scm = newScm
it.save()
}
}
}

Executing CURL in Shared Library Jenkins Pipeline Using `Process`

I have a method in a shared library in my Jenkins pipeline. The idea is to use this library and upload files to a remote host. The library is imported in a singleton library.
import com.package.jobutil.UploadFile
def uploadFunc() {
def uploader = new UploadFile(this)
withCredentials ([usernamePassword(credentialsId: 'user', userNameVariable: 'username', passwordVariable:'password)]) {
uploader.uploadArtifact("${username}", "${password}", file.txt, location)
}
}
def call() {
uploadFunc()
}
The class that is instantiated looks like this:
class UploadFile {
def steps
UploadFile (steps) {
this.steps = steps
}
pulic uploadArtifct (String user, String password, String file, String location) {
Process proc
def cred = "${user}:${pass}"
def cmd = ["curl", "-v", "-u", cred, "--upload-file", file, location]
steps.println "CURL: ${cmd}"
proc = cmd.execute()
}
}
Even though I see the println line in the logs. I do not see the curl command being executed.
Is there something I am missing that does not invoke the cmd.execute to work?
EDIT
When I use the curl directly in the library, it works.
pulic uploadArtifct (String user, String password, String file, String
location) {
def cred = "${user}:${password}"
def cmd = "curl -v -u ${cred} --upload-file ${file} ${nexusLocation}/${file}"
try {
steps.sh cmd
} catch (Exception e) {
throw new RuntimeExceptipon("Cannot execute curl, exception: [${e.getClass().getName()} - '${e.getMessage()}']")
}
}
However, when trying to use the Process it does not work.
pulic uploadArtifct (String user, String password, String file, String
location) {
def cred = "${user}:${password}"
def cmd = ["curl", "-v", "-u", cred, "--upload-file", ${file}, ${location}]
try {
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = cmd.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println sout
} catch (Exception e) {
throw new RuntimeExceptipon("Cannot execute curl, exception: [${e.getClass().getName()} - '${e.getMessage()}']")
}
}
The exception I get is:
java.lang.RuntimeException: Cannot execute curl, exception: [groovy.lang.MissingMethodException - 'No signature of method: java.lang.String.div() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl) values: [file.txt]
As explained here, you need to capture stdout/stderr to see anything.
At the very least:
def outputStream = new StringBuffer();
proc.waitForProcessOutput(outputStream, System.err)
//proc.waitForProcessOutput(System.out, System.err)
Or, as in this gist:
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = cmd.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println sout
An example of blocking call would be:
println new ProcessBuilder( 'sh', '-c', 'du -h --max-depth=1 /var/foo/bar/folder\\ with\\ spaces | sort -hr').redirectErrorStream(true).start().text
def cmd = ["curl", "-v", "-u", cred, "--upload-file", ${file}, ${location}/${file}]
No signature of method: java.lang.String.div() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl) values: [file.txt]
The '/' in '${location}/${file}' is interpreted as an '/ (div) operation instead of a string.
Try instead for that curl command argument:
${location}+"/"+${file}
As noted in your subsequent question, the all path needs to be between double-quotes.

issues with groovy script

I have the following groovy script that does the following
- checks all the builds for a specific job to see if it has the same build parameter as the current build
- stops the build with the same parameter as the current build
import hudson.tasks.Ant
def myBuildNumber = build.getEnvVars()['BUILD_NUMBER'].toInteger();
def myFractureNO = build.getEnvVars()['FRACTURE_NO'].toInteger();
def projectXml = new XmlSlurper().parseText("curl http://test.corp.test.com:8080/job/FractureAUT/api/xml".execute().text);
projectXml.build.each {
if(it.number.toInteger() < myBuildNumber)
{
def jobXml = new XmlSlurper().parseText(("curl http://test.corp.test.com:8080/job/FractureAUT/" + it.number + "/api/xml").execute().text);
def myparams = jobXml.getAction(hudson.model.ParametersAction.class);
for( p in myparams ) {
printlin p.name.toString();
if (p.name.toString == "FRACTURE_NO") {
if (p.value.toString() == myFractureNO.toString()) {
"curl http://test.corp.adobe.com:8080/job/FractureAUT/" + it.number + "/stop".execute().waitFor();
break;
}
}
}
}
}
the script outputs a bunch of urls to the screen because of the line:
def projectXml = new XmlSlurper().parseText("curl http://test.corp.test.com:8080/job/FractureAUT/api/xml".execute().text);
and it doesn't do what it suppose to do. How can I make it so that the line
def projectXml = new XmlSlurper().parseText("curl http://test.corp.test.com:8080/job/FractureAUT/api/xml".execute().text);
doesn't output the urls to the screen?
I get the following output
189http://test.corp.test.com:8080/job/FractureAUT/189/188http://test.corp.test.com:8080/job/FractureAUT/188/187http://test.corp.test.com:8080/job/FractureAUT/187/186http://test.corp.test.com:8080/job/FractureAUT/186/185http://test.corp.test.com:8080/job/FractureAUT/185/184http://test.corp.test.com:8080/job/FractureAUT/184/183http://test.corp.test.com:8080/job/FractureAUT/183/182http://test.corp.test.com:8080/job/FractureAUT/182/181http://test.corp.test.com:8080/job/FractureAUT/181/179http://test.corp.test.com:8080/job/FractureAUT/179/178http://test.corp.test.com:8080/job/FractureAUT/178/177http://test.corp.test.com:8080/job/FractureAUT/177/176http://test.corp.test.com:8080/job/FractureAUT/176/174http://test.corp.test.com:8080/job/FractureAUT/174/173http://test.corp.test.com:8080/job/FractureAUT/173/172http://test.corp.test.com:8080/job/FractureAUT/172/171http://test.corp.test.com:8080/job/FractureAUT/171/170http://test.corp.test.com:8080/job/FractureAUT/170/169http://test.corp.test.com:8080/job/FractureAUT/169/168http://test.corp.test.com:8080/job/FractureAUT/168/167http://test.corp.test.com:8080/job/FractureAUT/167/166http://test.corp.test.com:8080/job/FractureAUT/166/165http://test.corp.test.com:8080/job/FractureAUT/165/164http://test.corp.test.com:8080/job/FractureAUT/164/163http://test.corp.test.com:8080/job/FractureAUT/163/162http://test.corp.test.com:8080/job/FractureAUT/162/161http://test.corp.test.com:8080/job/FractureAUT/161/160http://test.corp.test.com:8080/job/FractureAUT/160/159http://test.corp.test.com:8080/job/FractureAUT/159/158http://test.corp.test.com:8080/job/FractureAUT/158/157http://test.corp.test.com:8080/job/FractureAUT/157/156http://test.corp.test.com:8080/job/FractureAUT/156/155http://test.corp.test.com:8080/job/FractureAUT/155/154http://test.corp.test.com:8080/job/FractureAUT/154/153http://test.corp.test.com:8080/job/FractureAUT/153/152http://test.corp.test.com:8080/job/FractureAUT/152/151http://test.corp.test.com:8080/job/FractureAUT/151/150http://test.corp.test.com:8080/job/FractureAUT/150/148http://test.corp.test.com:8080/job/FractureAUT/148/146http://test.corp.test.com:8080/job/FractureAUT/146/144http://test.corp.test.com:8080/job/FractureAUT/144/143http://test.corp.test.com:8080/job/FractureAUT/143/142http://test.corp.test.com:8080/job/FractureAUT/142/141http://test.corp.test.com:8080/job/FractureAUT/141/140http://test.corp.test.com:8080/job/FractureAUT/140/139http://test.corp.test.com:8080/job/FractureAUT/139/138http://test.corp.test.com:8080/job/FractureAUT/138/137http://test.corp.test.com:8080/job/FractureAUT/137/136http://test.corp.test.com:8080/job/FractureAUT/136/135http://test.corp.test.com:8080/job/FractureAUT/135/134http://test.corp.test.com:8080/job/FractureAUT/134/133http://test.corp.test.com:8080/job/FractureAUT/133/132http://test.corp.test.com:8080/job/FractureAUT/132/131http://test.corp.test.com:8080/job/FractureAUT/131/130http://test.corp.test.com:8080/job/FractureAUT/130/129http://test.corp.test.com:8080/job/FractureAUT/129/128http://test.corp.test.com:8080/job/FractureAUT/128/127http://test.corp.test.com:8080/job/FractureAUT/127/126http://test.corp.test.com:8080/job/FractureAUT/126/125http://test.corp.test.com:8080/job/FractureAUT/125/124http://test.corp.test.com:8080/job/FractureAUT/124/123http://test.corp.test.com:8080/job/FractureAUT/123/122http://test.corp.test.com:8080/job/FractureAUT/122/121http://test.corp.test.com:8080/job/FractureAUT/121/120http://test.corp.test.com:8080/job/FractureAUT/120/119http://test.corp.test.com:8080/job/FractureAUT/119/118http://test.corp.test.com:8080/job/FractureAUT/118/117http://test.corp.test.com:8080/job/FractureAUT/117/116http://test.corp.test.com:8080/job/FractureAUT/116/115http://test.corp.test.com:8080/job/FractureAUT/115/114http://test.corp.test.com:8080/job/FractureAUT/114/113http://test.corp.test.com:8080/job/FractureAUT/113/112http://test.corp.test.com:8080/job/FractureAUT/112/111http://test.corp.test.com:8080/job/FractureAUT/111/110http://test.corp.test.com:8080/job/FractureAUT/110/109http://test.corp.test.com:8080/job/FractureAUT/109/108http://test.corp.test.com:8080/job/FractureAUT/108/107http://test.corp.test.com:8080/job/FractureAUT/107/106http://test.corp.test.com:8080/job/FractureAUT/106/105http://test.corp.test.com:8080/job/FractureAUT/105/104http://test.corp.test.com:8080/job/FractureAUT/104/103http://test.corp.test.com:8080/job/FractureAUT/103/102http://test.corp.test.com:8080/job/FractureAUT/102/101http://test.corp.test.com:8080/job/FractureAUT/101/100http://test.corp.test.com:8080/job/FractureAUT/100/99http://test.corp.test.com:8080/job/FractureAUT/99/98http://test.corp.test.com:8080/job/FractureAUT/98/97http://test.corp.test.com:8080/job/FractureAUT/97/96http://test.corp.test.com:8080/job/FractureAUT/96/95http://test.corp.test.com:8080/job/FractureAUT/95/94http://test.corp.test.com:8080/job/FractureAUT/94/93http://test.corp.test.com:8080/job/FractureAUT/93/92http://test.corp.test.com:8080/job/FractureAUT/92/91http://test.corp.test.com:8080/job/FractureAUT/91/90http://test.corp.test.com:8080/job/FractureAUT/90/89http://test.corp.test.com:8080/job/FractureAUT/89/88http://test.corp.test.com:8080/job/FractureAUT/88/87http://test.corp.test.com:8080/job/FractureAUT/87/86http://test.corp.test.com:8080/job/FractureAUT/86/85http://test.corp.test.com:8080/job/FractureAUT/85/
Why do I get the output above?
Why are you invoking curl at all? Just retrieve the contents of the URL from groovy:
def xmlString = new URL("http://test.corp.test.com:8080/job/FractureAUT/api/xml").getText()
def projectXML = new XMLSlurper().parseText(xmlString)
XmlSlurper can parse the URL directly:
def projectXml = new XmlSlurper().parse('http://test.corp.test.com:8080/job/FractureAUT/api/xml')
I think the output on screen is because of curl. So can try to silence it with -s or --silent option:
def projectXml = new XmlSlurper().parseText("curl -s 'http://test.corp.test.com:8080/job/FractureAUT/api/xml'".execute().text);

Resources