How to tell jenkins to clean up locally created branches when the job starts - jenkins

In some jenkins shell command I create new git branch as follow:
git checkout -b new_branch
...
run more commands
..
sometimes running some commands is not successfull and the job exits.
Now when I run the job again it says that the branch new_branch already exists.
Is there any option in jenkins to cleans up the locally created branches every time when the job starts or something like that?

2 ways to go about it :
Run "git branch -d new_branch" to delete your local branch
Clean your workspace before checking out

Related

How to stop a build by buildnumber in a Jenkins pipeline

We uses notes (comments) from Gitlab to issue a couple of user-commands, for example retry a build that seems to have failed from a failed integration etc. We would now like to ask jenkins to stop a build. We have got the buildnumber from the comment (through a callback to to gitlab searching the comments) so we know what build to stop but now we stumbled on the problem. We don't seem to find an api-call to stop the build by buildnumber alone.
We could of course make a request to https://server/project/buildnumber/stop (same url as used by the ui) but then we have to enable the crumbIssuer and according to Ops open for a CSRF-attack.
Is there a way to do this operation from inside a pipeline?
Navigate to Manage Jenkins > Script Console.
Run the following script setting the job name and number of the hung build accordingly:
def build = Jenkins.instance.getItemByFullName("jobName").getBuildByNumber(jobNumber)
build.doStop()
build.doKill()
Otherwise you can create a separate pipeline job and configure the above script
Abort the job build from a cid node (if the previous option did not help):
Log in to any cid node.
Run:
cd /srv/volumes/jenkins/jobs/<job-name>/builds/
rm -rf <hung-build-number>

How to save Jenkins configuration?

Is there any way to save a pipeline configuration or an item configuration in Git or anywhere else, so that when my Jenkins machine is crashed, i can migrate the saved configuration in the new Jenkins instance?
I would ( as a start ) get yourself - https://wiki.jenkins.io/display/JENKINS/JobConfigHistory+Plugin which keeps history of all Changes made to Jobs , System config etc - has saved me multiple times.
Also , you could setup a cron job outside Jenkins to git push your Job config.
I setup to push the Jobs folder content ( including Build history - but you could exclude that - Correctly ignore all files recursively under a specific folder except for a specific file type ref ) .
My script ( i had SSH stuff previously setup )
cd /this/that/other/jenkins_data/jobs/
NOW=$(date +"%m-%d-%Y-%r")
git add .
git commit -m "Jenkins Backup $NOW"
git push -u origin jenkins-backup
This way gives me piece of mind , I have RSYNC to another box and I also have a Backup plugin running too... ( i was stung once - not again! )
Hope this helps.
All your jobs is stored in config.xml files inside $JENKINS_HOME/jobs/<path_to_your_job> folders. So, you can just backup these config.xml files (or you can backup all Jenkins configuration by saving full $JENKINS_HOME folder).
Hi you can write the pipeline script in file and publish that file into the git.
After that just create the pipeline job in the jenkins and use Pipeline script from SCM option for pipeline script.
The other option is take backup of Jenkins home directory to external hard disk(keep project workspace outside the jenkins home to reduce backup size).

How do I chain Jenkins pipelines from a checked out git repo?

I want to checkout a git repo and then run its build so I tried:
sh "git clone --depth 1 -b master git#github.com:user/repo.git"
build './repo'
but that yields:
ERROR: No item named ./repo found
I've tried to use dir('repo') but apparently that errors when you run it from within docker (because kubernetes is stuck on an old version of docker that doesnt support this).
Any idea on how to run the build pipeline from the checked out repo?
The 'build' pipeline steps expect a job name, not a pipeline folder with a Jenkinsfile in its root folder.
The correct way to do this is to set the pipeline job with the Jenkinsfile, as described here ('In SCM' section), and call it by its Job name from your pipeline.
Pipelines are not built for chaining unless you use shared libraries where you put the Pipeline code in a Groovy class or as a step, but that it is a subject for a full article.

Jenkins Pipeline building all branches simultaneously

I setup a simple Jenkinsfile that just echo a few steps.
I setup a new repo on Bitbucket (git) and two branches called master and develop.
When I commit something to master then both branches checkout and build in jenkins. Same behaviour on the develop branch.
Is it possible to limit only master to build in Jenkins once there is a commit to master branch? Similar behaviour to develop?
I think you can use a temporary text file to save last successful build SHA ($LAST_SUCCESSFUL_BUILD_SHA) of each branch. Then, when having a new commit from the repo, we'll check which branch the commit comes from.
CURRENT_SHA=$(git rev-parse HEAD)
if [ $FORCE_REBUILD = true ] || [ $CURRENT_SHA != $LAST_SUCCESSFUL_BUILD_SHA ]; then
echo "New commits available OR it was forced to build."
else
echo "Already up-to-date. Skip build."
curl -v -X POST --data "description=no changes, skip." ${JENKINS_BUILD_URL}submitDescription --user <username>:<password>
curl -v -X POST ${BUILD_URL}stop --user <username>:<password>
echo "Waiting for abort to take effect :D"
fi
If the new commit comes from another branch, it's good to use Jenkins open API to skip the build.
I have applied this for my freestyle jobs but haven't tried with Jenkinsfile.

Let Jenkins build project from a Mercurial commit

Is there a way to specify a hook in the single repository?
Now we have specified the hook in the "/etc/mercurial/hgrc" file, but every time it builds twice, and it builds for each commit in each repository.
So we want to specify a build per repository.
This is how we implemented the hook:
[hooks]
changegroup = curl --silent http://jenkins:8080/job/ourProject/build
It's on a Ubuntu server.
Select the Poll SCM option under Build Triggers.
Make sure that schedule form is empty.
You should be creating in the .hg directory, /home/user/mercurial/.hg/hgrc and add hooks as:
[hooks]
commit.jenkins = wget -q http://localhost:8080/mercurial/notifyCommit?url=file:///home/user/mercurial > /dev/null
incoming.jenkins = wget -q http://localhost:8080/mercurial/notifyCommit?url=file:///home/user/mercurial > /dev/null
You should make sure that
Your Jenkins project doesn't poll
You use the proper notifyCommit URLs for your Mercurial hooks: https://wiki.jenkins-ci.org/display/JENKINS/Mercurial+Plugin
Ok, I found what I looked for (I'm the bounty; my case is Mercurial with a specific branch).
In the main/origin repository, place a hook with your desired build script. Pregroupchange is to maintain the incoming changes. I have a rhodecode installed on the main repository and itself has its own hooks.
In this way, I still trigger Jenkins and still have the changes afther the trigger for rhodecode push notifications and others.
[hooks]
pregroupchange = /path/to/script.extention
In the script, place your desired actions, also a trigger for Jenkins. Don't forget to enable in Jenkins:Job:Configure:Build Triggers:checkbox Trigger builds remotely + put here your desired_token (for my case: Mercurial).
Because you can't trigger only to a specific branch in Mercurial, I found the branch name in this way. Also, to trigger from a remote script, you need to give in Jenkins read permission for anonymous overall, or create a specific user with credentials and put them into the trigger URL.
Bash example:
#!/bin/bash
BRANCH_NAME=`hg tip --template "{branch}"`
if [ $BRANCH_NAME = "branch_name" ]; then
curl --silent http://jenkins_domain:port/path/to/job?token=desired_token
fi
For the original question:
In this way you only execute one build, for a desired branch. Hooks are meant only for the main repository in case you work with multiple clones and multiple developers. You may have your local hooks, but don't trigger Jenkins from you local, for every developer. Trigger Jenkins only from the main repository when a push came (commit, incoming, and groupchange). Your local hooks are for other things, like email, logs, configuration, etc.

Resources