Clone Bitbucket repository without starting ssh-agent - jenkins

I've set up Jenkins on my VPS and created a job which is set to execute a shell script containing the following command: ssh -T git#bitbucket.org
It turns out that i get a "Permission denied (publickey)." response because ssh-agent is not started. This can be solved by adding these two lines to the shell script:
eval `ssh-agent -s`
ssh-add ~/.ssh/bitbucket_key
However, I don't like to add these tho lines to every Jenkins item when I need to clone a repository. I would expect that if I log in via ssh to my VPS and change to the Jenkins user to execute the two lines myself, this would no longer be necessary. Unfortunately, this is not the case. I can successfully run ssh -T git#bitbucket.org myself, but the Jenkins job still fails without the two extra lines.
Is there a way to avoid this behavior, i.e. a way in which I only have to start the ssh-agent and add my key to it once instead of every time I want to clone a repository? I cannot imagine that it would be a good practice to start (a new) ssh-agent every time I want to clone and build my code.

Use ssh_config in your ~/.ssh/config. It has simple syntax as you can read in manual page for ssh_config. For your case should be enough
Host bitbucket.org
IdentityFile ~/.ssh/bitbucket_key

Related

Jenkins Pipeline - connect to Docker host using SSH credentials

We would like to use Jenkins Pipelines to work with AWS ECR images on a remote host that has Docker installed, but does not (and will not) expose the Docker socket over port 2376.
A couple of simpler options include:
using the existing Jenkins SSH/scripts
using the pipeline ssh-agent and running commands in-line there
However, because the declarative docker plugin seems to have everything needed it would be cleaner to use this since tags, etc., will all align with other parts of the pipeline.
All examples on the internet show
docker.withServer("tcp://X:2376","credentialsId") {...}
However from configuring the Jenkins Cloud Config -> Docker Templates it seems ssh is provided so we tried the following:
stages {
stage('Deploy to Remote Host') {
steps {
script {
docker.withServer("ssh://ec2-x-x-x-x.mars-1.compute.amazonaws.com:22", "ssh-credentials-id") {
docker.withRegistry("https://1234567890.dkr.ecr.mars-1.amazonaws.com", "ecr:mars-1:ecr-credentials-id") {
docker.pull('my-image:latest')
}
}
}
}
}
}
Unfortunately, we get the following connection error:
error during connect: Post http://docker/v1.40/auth: command [ssh -p 22 ec2-x-x-x-x.mars-1.compute.amazonaws.com -- docker system dial-stdio] has exited with exit status 255, please make sure the URL is valid, and Docker 18.09 or later is installed on the remote host: stderr=Host key verification failed.
We have Docker v19 on the server, and the ssh key is fine using ssh-agent.
Any ideas about what we need to do to get this working?
I solved this by adding SSH commands (invoked on the agent) to the remote/target host, then invoking 'docker pull...', 'docker run...' etc using the shell.... however doing this in Jenkins Pipeline is fragile - the ssh commands turn into scripts, the credentials lookups are fairly complex & messy to look at and the overall outcome, while presenting a nice pipeline in Blue Ocean, is going to become difficult to code/maintain.
So following the advice that 'doing everything in Jenkins Pipeline is an anti-pattern' I broke the process into two pieces - building/pushing the image using Jenkins Pipeline + Docker Plugin which is documented and supported as a first class concern, and then invoking a Ansible 'build job' from the Pipeline passing dev/stage/live parameters, and letting Ansible take care of all of the other variables and secrets needed. This means the end result is similar in Blue Ocean, but the complex deployment logic is coded more cleanly in an appropriate tool designed to handle my use-case, and looping through environments/hosts is much cleaner in Ansible [or substitute your preferred deployment tool here].
To get rid of the "Host key verification failed" error I used this in my pipeline:
sh '''
[ -d ~/.ssh ] || mkdir ~/.ssh && chmod 0700 ~/.ssh && ssh-keyscan HOSTNAME >> ~/.ssh/known_hosts
'''

jenkins shell build step with variable containing a single quote

I'm trying to use jenkins to schedule a repeated job to rsync from a remote directory. Unfortunately I only have ssh password access (no key) so I'm using sshpass to authenticate. The password contains a single quote, and no matter what I do, jenkins always puts a backslash in front of the single quote.
Details:
jenkins is running on centos, installed via yum
build step is a shell
command in shell is basically `sshpass -p my'pass rsync -avc me#remotehost.com: /my/dest/dir/
variations I've tried:
put the password in a file then use sshpass -f
reports authentication fails
put the above command in a script file, have the jenkins build run that script
use jenkins credentials / associated variables
all variations of double quoting / string concatenation
Note that all of the things I've tried work fine on the command line and/or via crontab (I'm trying to use jenkins instead of crontab though...)
Any ideas?
Try to use Groovy multiline string literal for the shell block:
stage{
sh """
sshpass -p my'pass rsync -avc me#remotehost.com: /my/dest/dir/
"""
}

Trigger step in Bitbucket pipelines

I have a CI pipeline in Bitbucket which is building, testing and deploying an application.
The thing is that after the deploy I want to run selenium tests.
Selenium tests are in an another repository in Bitbucket and they have their own pipeline.
Is there a trigger step in the Bitbucket pipeline to trigger a pipeline when a previous one has finished?
I do not want to do a fake push to the test repository to trigger those tests.
The most "correct" way I can think of doing this is to use the Bitbucket REST API to manually trigger a pipeline on the other repository, after your deployment completes.
There are several examples of how to create a pipeline here: https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Bworkspace%7D/%7Brepo_slug%7D/pipelines/#post
Copy + pasting the first example. How to trigger a pipeline for the latest commit on master:
$ curl -X POST -is -u username:password \
-H 'Content-Type: application/json' \
https://api.bitbucket.org/2.0/repositories/jeroendr/meat-demo2/pipelines/ \
-d '
{
"target": {
"ref_type": "branch",
"type": "pipeline_ref_target",
"ref_name": "master"
}
}'
according to their official documentation there is no "easy way" to do that, cause the job are isolated in scope of one repository, yet you can achieve your task in following way:
create docker image with minimum required setup for execution of your tests inside
upload to docker hub (or some other repo if you have such)
use docker image in last step of you pipeline after deploy to execute tests
Try out official component Bitbucket pipeline trigger: https://bitbucket.org/product/features/pipelines/integrations?p=atlassian/trigger-pipeline
You can run in after deploy step
script:
- pipe: atlassian/trigger-pipeline:4.1.7
variables:
BITBUCKET_USERNAME: $BITBUCKET_USERNAME
BITBUCKET_APP_PASSWORD: $BITBUCKET_APP_PASSWORD
REPOSITORY: 'your-awesome-repo'
ACCOUNT: 'teams-in-space'
#BigGinDaHouse I did something more or less like you say.
My step is built on top of docker image with headless chrome, npm and git.
I did follow the steps below:
I have set private key for the remote repo in the original repo. Encoded base 64. documentation. The public key is being set into the remote repo in SSH Access option in bitbucket menu.
In the pipeline step I am decoding it and setting it to a file. I am also changing its permission to be 400.
I am adding this Key inside the docker image. ssh-add
Then I am able to do a git clone followed by npm install and npm test
NOTE: The entry.sh is because I am starting the headless browser.
- step:
image: kimy82/headless-selenium-npm-git
script:
- echo $key_in_env_variable_in_bitbucket | base64 --decode > priv_key
- chmod 400 ./priv_key
- eval `ssh-agent -s`
- ssh-agent $(ssh-add priv_key; git clone git#bitbucket.org:project.git)
- cd project
- nohup bash /usr/bin/entry.sh >> out.log &
- npm install
- npm test
Top answers (this and this) are correct, they work.
Just adding that we found out (after a LOT of trial and error) that the user executing the pipeline must have WRITE permissions on the repo where the pipeline is invoked (even though his app password permissions were set to "WRITE" for repos and pipelines...)
Also, this works for executing pipelines in Bitbucket's cloud or on-premise, through local runners.
(Answering as I am lacking reputation for commenting)

How can I test a change made to Jenkinsfile locally?

When writing jenkins pipelines it seems to be very inconvenient to commit each new change in order to see if it works.
Is there a way to execute these locally without committing the code?
You cannot execute a Pipeline script locally, since its whole purpose is to script Jenkins. (Which is one reason why it is best to keep your Jenkinsfile short and limited to code which actually deals with Jenkins features; your actual build logic should be handled with external processes or build tools which you invoke via a one-line sh or bat step.)
If you want to test a change to Jenkinsfile live but without committing it, use the Replay feature added in 1.14.
JENKINS-33925 tracks the feature request for an automated test framework.
I have a solution that works well for me. It consists of a local jenkins running in docker and a git web hook to trigger the pipeline in the local jenkins on every commit. You no longer need to push to your github or bitbucket repository to test the pipeline.
This has only been tested in a linux environment.
It is fairly simple to make this work although this instruction is a tad long. Most steps are there.
This is what you need
Docker installed and working. This is not part of this instruction.
A Jenkins running in docker locally. Explained how below.
The proper rights (ssh access key) for your local Jenkins docker user to pull from your local git repo. Explained how below.
A Jenkins pipeline project that pulls from your local git repository. Explained below.
A git user in your local Jenkins with minimal rights. Explained below.
A git project with a post-commit web hook that triggers the pipeline project. Explained below.
This is how you do it
Jenkins Docker
Create a file called Dockerfile in place of your choosing. I'm placing it in /opt/docker/jenkins/Dockerfile fill it with this:
FROM jenkins/jenkins:lts
USER root
RUN apt-get -y update && apt-get -y upgrade
# Your needed installations goes here
USER jenkins
Build the local_jenkins image
This you will need to do only once or after you have added something to the Dockerfile.
$ docker build -t local_jenkins /opt/docker/jenkins/
Start and restart local_jenkins
From time to time you want to start and restart jenkins easily. E.g. after a reboot of your machine. For this I made an alias that I put in .bash_aliases in my home folder.
$ echo "alias localjenkinsrestart='docker stop jenkins;docker rm jenkins;docker run --name jenkins -i -d -p 8787:8080 -p 50000:50000 -v /opt/docker/jenkins/jenkins_home:/var/jenkins_home:rw local_jenkins'" >> ~/.bash_aliases
$ source .bash_aliases # To make it work
Make sure the /opt/docker/jenkins/jenkins_home folder exists and that you have user read and write rights to it.
To start or restart your jenkins just type:
$ localjenkinsrestart
Everything you do in your local jenkins will be stored in the folder /opt/docker/jenkins/jenkins_home and preserved between restarts.
Create a ssh access key in your docker jenkins
This is a very important part for this to work. First we start the docker container and create a bash shell to it:
$ localjenkinsrestart
$ docker exec -it jenkins /bin/bash
You have now entered into the docker container, this you can see by something like jenkins#e7b23bad10aa:/$ in your terminal. The hash after the # will for sure differ.
Create the key
jenkins#e7b23bad10aa:/$ ssh-keygen
Press enter on all questions until you get the prompt back
Copy the key to your computer. From within the docker container your computer is 172.17.0.1 should you wonder.
jenkins#e7b23bad10aa:/$ ssh-copy-id user#172.17.0.1
user = your username and 172.17.0.1 is the ip address to your computer from within the docker container.
You will have to type your password at this point.
Now lets try to complete the loop by ssh-ing to your computer from within the docker container.
jenkins#e7b23bad10aa:/$ ssh user#172.17.0.1
This time you should not need to enter you password. If you do, something went wrong and you have to try again.
You will now be in your computers home folder. Try ls and have a look.
Do not stop here since we have a chain of ssh shells that we need to get out of.
$ exit
jenkins#e7b23bad10aa:/$ exit
Right! Now we are back and ready to continue.
Install your Jenkins
You will find your local Jenkins in your browser at http://localhost:8787.
First time you point your browser to your local Jenkins your will be greated with a Installation Wizard.
Defaults are fine, do make sure you install the pipeline plugin during the setup though.
Setup your jenkins
It is very important that you activate matrix based security on http://localhost:8787/configureSecurity and give yourself all rights by adding yourself to the matrix and tick all the boxes. (There is a tick-all-boxes icon on the far right)
Select Jenkins’ own user database as the Security Realm
Select Matrix-based security in the Authorization section
Write your username in the field User/group to add: and click on the [ Add ] button
In the table above your username should pop up with a people icon next to it. If it is crossed over you typed your username incorrectly.
Go to the far right of the table and click on the tick-all-button or manually tick all the boxes in your row.
Please verify that the checkbox Prevent Cross Site Request Forgery exploits is unchecked. (Since this Jenkins is only reachable from your computer this isn't such a big deal)
Click on [ Save ] and log out of Jenkins and in again just to make sure it works.
If it doesn't you have to start over from the beginning and emptying the /opt/docker/jenkins/jenkins_home folder before restarting
Add the git user
We need to allow our git hook to login to our local Jenkins with minimal rights. Just to see and build jobs is sufficient. Therefore we create a user called git with password login.
Direct your browser to http://localhost:8787/securityRealm/addUser and add git as username and login as password.
Click on [ Create User ].
Add the rights to the git user
Go to the http://localhost:8787/configureSecurity page in your browser. Add the git user to the matrix:
Write git in the field User/group to add: and click on [ Add ]
Now it is time to check the boxes for minimal rights to the git user. Only these are needed:
overall:read
job:build
job:discover
job:read
Make sure that the Prevent Cross Site Request Forgery exploits checkbox is unchecked and click on [ Save ]
Create the pipeline project
We assume we have the username user and our git enabled project with the Jenkinsfile in it is called project and is located at /home/user/projects/project
In your http://localhost:8787 Jenkins add a new pipeline project. I named it hookpipeline for reference.
Click on New Item in the Jenkins menu
Name the project hookpipeline
Click on Pipeline
Click [ OK ]
Tick the checkbox Poll SCM in the Build Triggers section. Leave the Schedule empty.
In the Pipeline section:
select Pipeline script from SCM
in the Repository URL field enter user#172.17.0.1:projects/project/.git
in the Script Path field enter Jenkinsfile
Save the hookpipeline project
Build the hookpipeline manually once, this is needed for the Poll SCM to start working.
Create the git hook
Go to the /home/user/projects/project/.git/hooks folder and create a file called post-commit that contains this:
#!/bin/sh
BRANCHNAME=$(git rev-parse --abbrev-ref HEAD)
MASTERBRANCH='master'
curl -XPOST -u git:login http://localhost:8787/job/hookpipeline/build
echo "Build triggered successfully on branch: $BRANCHNAME"
Make this file executable:
$ chmod +x /home/user/projects/project/.git/hooks/post-commit
Test the post-commit hook:
$ /home/user/projects/project/.git/hooks/post-commit
Check in Jenkins if your hookpipeline project was triggered.
Finally make some arbitrary change to your project, add the changes and do a commit. This will now trigger the pipeline in your local Jenkins.
Happy Days!
TL;DR
Jenkins Pipeline Unit testing framework
Jenkinsfile Runner
Long Version
Jenkins Pipeline testing becomes more and more of a pain. Unlike the classic declarative job configuration approach where the user was limited to what the UI exposed the new Jenkins Pipeline is a full fledged programming language for the build process where you mix the declarative part with your own code. As good developers we want to have some unit tests for this kind of code as well.
There are three steps you should follow when developing Jenkins Pipelines. The step 1. should cover 80% of the uses cases.
Do as much as possible in build scripts (eg. Maven, Gradle, Gulp etc.). Then in your pipeline scripts just calls the build tasks in the right order. The build pipeline just orchestrates and executes the build tasks but does not have any major logic that needs a special testing.
If the previous rule can't be fully applied then move over to Pipeline Shared libraries where you can develop and test custom logic on its own and integrate them into the pipeline.
If all of the above fails you, you can try one of those libraries that came up recently (March-2017). Jenkins Pipeline Unit testing framework or pipelineUnit (examples). Since 2018 there is also Jenkinsfile Runner, a package to execution Jenkins pipelines from a command line tool.
Examples
The pipelineUnit GitHub repo contains some Spock examples on how to use Jenkins Pipeline Unit testing framework
Jenkins has a 'Replay' feature, which enables you to quickly replay a job without updating sources:
At the moment of writing (end of July 2017) with the Blue Ocean plugin you can check the syntax of a declarative pipeline directly in the visual pipeline editor. The editor, works from the Blue Ocean UI when you click "configure" only for github projects (this is a known issue and they are working to make it work also on git etc).
But, as explained in this question you can open the editor browsing to:
[Jenkins URL]/blue/organizations/jenkins/pipeline-editor/
Then click in the middle of the page, and press Ctrl+S, this will open a textarea where you can paste a pipeline declarative script. When you click on Update, if there is a syntax error, the editor will let you know where the syntax error is. Like in this screenshot:
If there is no syntax error, the textarea will close and the page will visualize your pipeline. Don't worry it won't save anything (if it's a github project it would commit the Jenkinsfile change).
I'm new to Jenkins and this is quite helpful, without this I had to commit a Jenkinsfile many times, till it works (very annoying!). Hope this helps. Cheers.
A bit late to the party, but that's why I wrote jenny, a small reimplementation of some core Jenkinsfile steps. (https://github.com/bmustiata/jenny)
In my development setup – missing a proper Groovy editor – a great deal of Jenkinsfile issues originates from simple syntax errors. To tackle this issue, you can validate the Jenkinsfile against your Jenkins instance (running at $JENKINS_HTTP_URL):
curl -X POST -H $(curl '$JENKINS_HTTP_URL/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)') -F "jenkinsfile=<Jenkinsfile" $JENKINS_HTTP_URL/pipeline-model-converter/validate
The above command is a slightly modified version from
https://github.com/jenkinsci/pipeline-model-definition-plugin/wiki/Validating-(or-linting)-a-Declarative-Jenkinsfile-from-the-command-line
As far as i know this Pipeline Plugin is the "Engine" of the new Jenkinsfile mechanics, so im quite positive you could use this to locally test your scripts.
Im not sure if there is any additional steps needed when you copy it into a Jenkinsfile, however the syntax etc should be exactly the same.
Edit: Found the reference on the "engine", check this feature description, last paragraph, first entry.
For simplicity, you can create a Jenkinsfile at the root of the git repository, similar to the below example 'Jenkinsfile' based on the groovy syntax of the declarative pipeline.
pipeline {
agent any
stages {
stage('Build the Project') {
steps {
git 'https://github.com/jaikrgupta/CarthageAPI-1.0.git'
echo pwd()
sh 'ls -alrt'
sh 'pip install -r requirements.txt'
sh 'python app.py &'
echo "Build stage gets finished here"
}
}
stage('Test') {
steps {
sh 'chmod 777 ./scripts/test-script.sh'
sh './scripts/test-script.sh'
sh 'cat ./test-reports/test_script.log'
echo "Test stage gets finished here"
}
}
}
https://github.com/jaikrgupta/CarthageAPI-1.0.git
You can now set up a new item in Jenkins as a Pipeline job.
Select the Definition as Pipeline script from SCM and Git for the SCM option.
Paste the project's git repo link in the Repository URL and Jenkinsfile in the script name box.
Then click on the lightweight checkout option and save the project.
So whenever you pushed a commit to the git repo, you can always test the changes running the Build Now every time in Jenkins.
Please follow the instructions in the below visuals for easy setup a Jenkins Pipeline's job.
Aside from the Replay feature that others already mentioned (ditto on its usefulness!), I found the following to be useful as well:
Create a test Pipeline job where you can type in Pipeline code or point to your repo/branch of a Jenkinsfile to quickly test out something. For more accurate testing, use a Multibranch Pipeline that points to your own fork where you can quickly make changes and commit without affecting prod. Stuff like BRANCH_NAME env is only available in Multibranch.
Since Jenkinsfile is Groovy code, simply invoke it with "groovy Jenkinsfile" to validate basic syntax.
Put your SSH key into your Jenkins profile, then use the declarative linter as follows:
ssh jenkins.hostname.here declarative-linter < Jenkinsfile
This will do a static analysis on your Jenkinsfile. In the editor of your choice, define a keyboard shortcut that runs that command automatically. In Visual Studio Code, which is what I use, go to Tasks > Configure Tasks, then use the following JSON to create a Validate Jenkinsfile command:
{
"version": "2.0.0",
"tasks": [
{
"label": "Validate Jenkinsfile",
"type": "shell",
"command": "ssh jenkins.hostname declarative-linter < ${file}"
}
]
}
You can just validate your pipeline to find out syntax issues. Jenkins has nice API for Jenkisfile validation - https://jenkins_url/pipeline-model-converter/validate
Using curl and passing your .Jenkinsfile, you will get syntax check instantly
curl --user username:password -X POST -F "jenkinsfile=<jenkinsfile" https://jenkins_url/pipeline-model-converter/validate
You can add this workflow to editors:
VS Code
Sublime Text
Using the VS Code Jenkins Jack extension, you can have a way to test your Jenkinsfiles without use the git push way, from your local files to a local or remote running Jenkins. And you will have the running log of the job inside VS Code, the ability to create jobs in Jenkins and more staff. I hope this help to more people looking for a way to develop Jenkinsfiles.
i am using replay future , to do some update and run quickly .
With some limitations and for scripted pipelines I use this solution:
Pipeline job with an inlined groovy script:
node('master') {
stage('Run!') {
def script = load('...you job file...')
}
}
Jenkinsfile for testing have same structure as for lesfurets:
def execute() {
... main job code here ...
}
execute()
This is a short solution that lets me test Pipeline code very quickly:
pipeline {
agent any
options {
skipDefaultCheckout true
timestamps()
}
parameters {
text(name: 'SCRIPT', defaultValue: params.SCRIPT,
description: 'Groovy script')
}
stages {
stage("main") {
steps {
script {
writeFile file: 'script.groovy',
text: params.SCRIPT
def groovyScript = load 'script.groovy'
echo "Return value: " + groovyScript
}
} // steps
} // stage
} // stages
} // pipeline
skipDefaultCheckout true because we do not need the files in this tool git repository.
defaultValue: params.SCRIPT sets the default to the latest execution. If used by just one user, it allows for a very quick cycle of short tests.
The given script is written to a file, and loaded and with load.
With this setup I can test everything I can do inside my other Jenkinsfiles, including using shared libraries.

Setting git private repository project on jenkins server

I am trying to set git private repo on jenkins server. I have installed git plugin and also github. when I set repo url in jenkins project ui the error is
Failed to connect to repository : Command "git -c core.askpass=true
ls-remote -h git#github.com:repo/project.git HEAD" returned
status code 128:
stdout:
stderr: Permission denied (publickey).
fatal: The remote end hung up unexpectedl
What I have done up to now:
My server user and jenkin user( both are in same server) are different. Though it seems to me these are not related. jenkins user are given all credintial.
In my server under var/lib/jenkins/.ssh(.ssh is created by me) I added ssh key . Public key is added to github repo.
By swithcting user to jenkins i can clone the project by this ssh. So i think there is not any public key adding problem.
I have googled the problem. there are many solutions. I tried most of them. But still no solution. Probably I am missing something.
My repo url is something like this
git#github.com:repo/project.git
If your HOME set in /var/lib/jenkins/ then i hope all the step you have been done successfully :)
Then one thing may be happen for your case. Like when you switch the user by using:
su jenkins
This command means that you switch the user but the home directory will be same as a root's home!
So you need to switch user by confirming the specific user home also switched. TO doing so, you need to follow:
su -s /bin/bash jenkins
Then you need to generate either the ssh public key once again or just update the known host. This will work.
Related Link
It depends on what HOME is set to when Jenkins is running: git will look for the ssh (public and private) keys under $HOME/.ssh.
Simply add a build step with an echo $HOME, and make sure your .ssh is in that folder.

Resources