Jenkins pipeline check URL exists or does not exists - jenkins

is it possible to check in jenkins whetehr a url exists or not . if exists i want do few action. Maybe curl or other method
if (sh(script: 'curl --head --silent --fail <url> 2> /dev/null')) {
echo 'Hi'
}

You can execute shell scripts (in one of your build steps) to check if given URL exists.
Here is the link that I've found, it might help you out.

Related

CURL response from Jenkinsfile, http_code problematic due to escape chars

I have written a function to record http code after the application is up to verify if response code is appropriate. This is on windows agent hosted on Azure VM.
def result = bat (returnStdout: true,
script: "curl --output /dev/null --silent --write-out '\\n%{http_code} http://localhost:8080")
echo "HTTP Code: ${result}"
So as I run the pipeline I get the following response in console log
**F:\jenkin_workspace\workspace\curl-test-pipeline>curl --write-out '\n//localhost:8080**
I tried various methods like using double quotes, single quotes and even without quotes but none helps.
Please suggest where am I wrong here?

Jenkins - shell script - find parameter format not correct

hope one of you can help - I'm running a script in jenkins pipeline, so that I can upload source maps to rollbar, so I need to loop through the minified js files - I'm trying to do this with the FIND command but it keeps giving me an error: find parameter format not correct - script below:
stages {
stage('Set correct environment link') {
steps {
script {
buildTarget = params.targetEnv
if(params.targetEnv.equals("prj1")){
linkTarget = "http://xxx.xxx.xx/xxx/"
} else if(params.targetEnv.equals(.......)..etc.
stage('Uploading source maps to Rollbar') {
steps {
sh ''' #!/bin/bash
# Save a short git hash, must be run from a git
# repository (or a child directory)
version=$(git rev-parse --short HEAD)
# Use the post_server_time access token, you can
# find one in your project access token settings
post_server_item=e1d04646bf614e039d0af3dec3fa03a7
echo "Uploading source maps for version $version!"
# We upload a source map for each resulting JavaScript
# file; the path depends on your build config
for path in $(find dist/renew -name "*.js"); do
# URL of the JavaScript file on the web server
url=${linkTarget}/$path
# a path to a corresponding source map file
source_map="#$path.map"
echo "Uploading source map for $url"
curl --silent --show-error https://api.rollbar.com/api/1/sourcemap \
-F access_token=$post_server_item \
-F version=$version \
-F minified_url=$url \
-F source_map=$source_map \
> /dev/null
done
'''
}
}
stage('Deploy') {
steps {
echo 'Deploying....'
From Bash CLI
With the help of #jeb I managed to resolve this FIND issue on jenkins by placing the absolute path for (find) in the shell script - initially it was using the windows FIND cmd, so i needed to point to cygwin find cmd
before: for path in $(find dist/renew -name "*.js"); do
and after: for path in $(/usr/bin/find dist/renew -name "*.js"); do
Thaks to all that commented

Fetching github payload in jenkinsfile

Need some help on fetching the GitHub payload into the Jenkins file without installing any plugin.
If anyone can provide the Jenkins file code snippet to access the GitHub payload from the webhook. it would be of great help.
I am able to call the Jenkins job from GitHub webhook. but need the payload as well to process further.
Any help would be appreciated. Thanks.
Please find the below groovy script:
stage('Pull Request Info') {
agent {
docker {
image 'maven'
args '-v $HOME/.m2:/home/jenkins/.m2 -ti -u 496 -e MAVEN_CONFIG=/home/jenkins/.m2 -e MAVEN_OPTS=-Xmx2048m'
}
}
steps {
script {
withCredentials([usernameColonPassword(credentialsId: "${env.STASH_CREDENTIAL_ID}",
variable: 'USERPASS')]) {
def hasChanges = maven.updateDependencies()
if (hasChanges != '') {
def pr1 = sh(
script: "curl -s -u ${"$USERPASS" } -H 'Content-Type: application/json' https://xx.example/rest/some/endpoint",
returnStdout: true
)
def pr = readJSON(text: pr1)
println pr.fromRef
}
}
}
}
}
Above script uses, curl to fetch the details about Pull request. I have stored the credentials in the jenkins and created an environment variable for the credentialId.
You can replace the url with your endpoint. You can also modify the script to use jq if you have jq installed in the machine.
In this case, I'm using readJSON to parse the JSON which is part of pipeline utilities plugin. My question would be, why not use the plugin as it provides the needed functionalities?
If you still dont want to use plugin, take a look at json parsing with groovy.

Can we define a variable inside a Jenkins parameterized build

My scenario is, I have parameterized build and inside the build section, I have executed shell where I define a variable and then echo to print it. But it doesn't print anything in the console output.
I hope I have made myself clear. Could anyone please answer my question?
current_folder=`date +%Y%m%d-%H%M%S`
echo $current_folder
enter image description here
I'm using Jenkins ver. 2.32.3 and a simple freestyle job, running on mac OS, using an execute shell build step of:
current_folder=`date +%Y%m%d-%H%M%S`
echo $current_folder
Gives output of:
$ /bin/sh -xe /var/folders/kh/4fl0eeldofefmmsfd/T/hudson89388543547899686.sh
++ date +%Y%m%d-%H%M%S
+ current_folder=20180613-081712
+ echo 20180613-081712
20180613-081712
Finished: SUCCESS
In a similar fashion, setting the shell:
#!/bin/bash
current_folder=`date +%Y%m%d-%H%M%S`
echo $current_folder
Gives:
$ /bin/bash /var/folders/kh/by0kd93dfew5fgjhy000h6/T/hudson62702345565786787.sh
20180613-081655
Finished: SUCCESS
The same applies to a parameter that is defined as part of the Jenkins job, underneath the
This project is parameterized checkbox once set. For example, if you have a string parameter called userName with a default value of User1, then you can print it's value in an Execute Shell build step using:
echo $userName
echo ${userName}
echo "In a string ${userName}"
Giving:
User1
User1
In a string User1

How to update Jenkins Job config.xml file using curl

How can I edit jenkins job's parameter by updating config.xml of jenkins job using curl?
You can use:
curl -X POST 'http://my-cool-jenkins.com:8080/createItem?name=mycooljob' -u username:password --data-binary #config.xml -H "Content-Type:text/xml"
Update:
That url for creating job, for updating use:
curl -X POST 'http://my-cool-jenkins.com:8080/job/mycooljob/config.xml' -u username:password --data-binary #config.xml -H "Content-Type:text/xml"
Just updating content of config.xml file is probably not enough to change in-memory state of Jenkins job. You still need to reload configuration from disk, which can be done either in GUI with jenkins/manage/, using groovy script or simply rebooting the server. After that your example should work.
This really goes down to the fact that Jenkins config.xml are XStream serialized java objects, not actual configuration files. So changing job parameters by manually editing xml files is likely not the best solution. Instead, you could change the job configuration using Jenkins script console. For example to change default parameter value for String parameter, you can run below script in Jenkins console (e.g. http://localhost:8080/jenkins/script):
import hudson.model.ParametersDefinitionProperty
def jobName = "job_name"
def paramName = "param_to_be_changed"
def newParamValue = "param_new_value"
def job = Jenkins.instance.getItem(jobName)
def params = job.getAction(ParametersDefinitionProperty)
def paramToModify = params.getParameterDefinitions().find { param -> param.getName() == paramName }
paramToModify.setDefaultValue(newParamValue)
job.save()
If the job is inside the folder or organization, it is necessary to go one level further, i.e.:
def folderName = "folder_name"
def job = Jenkins.instance.getItem(folderName).getItem(jobName)
After that job state will be stored in config.xml file. After that you can execute the script remotely using curl. Assuming you saved above script to script.groovy file:
# Get breadcrumb from Jenkins
curl -u <username>:<password> 'http://localhost:8080/jenkins/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)'
# Send script to Jenkins console
curl -X POST -u <username>:<password> -H 'Jenkins-Crumb: <crumb>' -H 'Content: text/plain' --data-urlencode "script=$(< script.groovy)" http://localhost:8080/jenkins/scriptText
More details on Parameter API in javadoc
Here is a link of a script that I've been using in order to modify a job's pipeline for the shell: https://raw.githubusercontent.com/iocanel/presentations/382074b5012d6c3ed87042298114e688424eeaed/workspace/editor/jenkins-run-pipeline

Resources