How to build when a change is pushed to GitHub in Jenkins?

build-when-a-change-is-pushed-to-github-in-jenkins
The GitHub plugin for Jenkins is the most basic plugin for integrating Jenkins with GitHub projects. If you are a GitHub user, this plugin enables you to:
  • Schedule your build
  • Pull your code and data files from your GitHub repository to your Jenkins machine
  • Automatically trigger each build on the Jenkins server, after each Commit on your Git repository

This saves you time and lets you incorporate your project into the Continuous Integration (CI) process.

How to Start Working with the GitHub Plugin for Jenkins
Install the Github Jenkins plugin
Go to “Manage Jenkins” –> “Manage Plugins” –> “Available” Tab –> Search for “GitHub plugin” and install it.
Configure the plugin with github accounts and keys
Go to “Manage Jenkins” –> “Configure System” –> Locate “Github” section and “Add Github Server”.

API URL – If you server is github.com, your “API URL” would be “https://api.github.com” Otherwise if you use GitHub Enterprise, specify its API endpoint here (e.g., https://ghe.acme.com/api/v3/).

Credentials – You can create your own personal access token in your account GitHub settings.
Token should be registered with scopes: Refer https://github.com/settings/tokens/new.
Add credentials (your Github token), Apply and “Test Connection”.

Open your Jenkins Project

a) Check the GitHub project checkbox and set the Project URL to point to your GitHub Repository

b) Under Source Code Management, check Git and set the Repository URL to point to your GitHub Repository
c) Under Build Triggers, check the “Build when a change is pushed to GitHub” checkbox
4. Install the Jenkins (GitHub plugin) and set a webhook to your Jenkins machine
a) From your GitHub repository, go to Settings and then to Integrations & Services
b) Click on Add Service and add ‘Jenkins (GitHub plugin)’

c) Set the Jenkins hook URL as the URL for your Jenkins machine, and add /github-webhook/



Congratulations! Every time you publish your changes to Github, GitHub will trigger your new Jenkins job.
Another Approach noted by suprakash
Actually if you do the web hook settings from Jenkins -> Github plugin configuration (mentioned above), you will still see webhooks get created in github. So , above two approaches basically doing the same thing.
I personally like it to create webhook from Github, because in this way you don’t have to share or store github user info in jenkins.
Steps : 1. Login into Github (with Admin) 2. Go to the repository you want to hook with jenkins 3. Click on settings tab -> webhooks & services 4. Click on Add Webhook 5. Enter payload url : like : http://:8080/github-webhook/ 6. Select content type as json 7. you are done

Now you do the changes and commit , you will see jenkins build get trigger automatically. Don’t forget to do the settings in jenkins jobs to start the build when push code in github.

Reference

Tagged : / / / / / / / /

Complete guide to use Jenkins CLI / Command line | Jenkins Tutorials

jenkins-cli-command-line
Complete guide to use Jenkins CLI / Command line?
Run Jenkins build from command is very simple in Linux system. If you are using using windows, gitbash is a recommended which has bash shell in built. You can use windows command line as well. Jenkins has support to command line client that allows you to access Jenkins from command line.
To Trigger Jenkins build from command line some prerequisite are there
Jenkins service is running.
Enable security option under “Configure Global Security”
Go to jenkins dashboard in Home page ( e.g http://localhost:8080/ ) -> Manage Jenkins
-> Configure Global Security -> Click on “Enable security” checkbox

You can also configure “Access Control” and “Authorization” option in Global Security page.

Download Jenkins-cli.jar
Download Jenkins-cli.jar from http://<your_jenkins_server_url>/jnlpJars/jenkins-cli.jar. (Here <your_jenkins_server_url> is your respective Jenkins server URL (development or staging))
Go to http://<your_jenkins_server_url>/cli and build your command by following the instructions there.
How to login to Jenkins using commands
If your Jenkins requires authentication, use –username and –password or –password-file options to specify the credentials. To avoid doing this for every command, you can also use the login CLI command once (with the same credentials parameters), and after that you may use other commands without specifying credentials.
Whenever the CLI tries to to connect to the Jenkins server, it offers the before mentioned SSH keys. When the user has those keys but don’t want use them to authenticate, preventing being prompted by the key’s password, it’s possible to use the -noKeyAuth argument. This way the CLI will never try to use the SSH keys available. failure to authenticate by itself does not constitute a fatal error. It will instead try to execute the command anyway, as the anonymous user.
Login Jenkins using username and Password
Jenkins allow us to trigger Jenkins build with any specific user, For that we have to pass username and password in command line.
$ java -jar “/tmp/kitchen/cache/jenkins-cli.jar” -s http://localhost:8080 who-am-i –username jenkins –password foobar
$ java -jar jenkins-cli.jar -s http://myjenkins help –username me –password mypassword
Login Jenkins using public keys
Starting 1.419 (which will be out July 4th), Jenkins CLI supports authentication based on the SSH key pair. Just like CloudBees DEV@cloud (or GitHub, or other similar sites), you interactively login from the web UI, then associate your public keys with your user account. Then CLI will silently authenticates itself using your ~/.ssh/id_rsa, ~/.ssh/id_dsa, or ~/.ssh/identity.
https://help.github.com/articles/generating-an-ssh-key/
Login Jenkins using private keys
You can also pass the priate key as follows
To use the -i option the syntax is as follows:
$ java -jar jenkins-cli.jar -s http://myjenkins help -i ~/.ssh/id_rsa
$ java -jar jenkins-cli.jar [-s JENKINS_URL] [-i PRIVATE_KEY] command [options…] [arguments…]
For compatibility reasons, unless you use the -i option,
Login Jenkins using initialAdminPassword
try user “admin” and password from “Jenkins\secrets\initialAdminPassword”
java -jar jenkins-cli.jar -s http://localhost:8080 who-am-i –username admin –password fe3f1e1624ea4be8873b7a35e28b24be
Login Jenkins using passphrase
Go to http://jenkins-serer:8085/user/admin/configure and set the passphrase in “SSH Public Keys” and use the same passphrase with jenkins commands.
E.g 1 – Getting help
The list of the available commands depends on the server you are talking to. Visit https://jenkins.example.com/cli or use ‘help’ command to list them all:
> java -jar jenkins-cli.jar -s https://jenkins.example.com help [command]
E.g 2 – Run Jenkins Build From Command Line
> java -jar jenkins-cli.jar -s http://<jenkins server>/ build build-name [-c] [-f] [-p] [-r N] [-s] [-v] [-w]
build-name : Name of the job to build
-c  : Check for SCM changes before starting the build, and if there’s no change, exit without doing a build
-f  : Follow the build progress. Like -s only interrupts are not passed through to the build.
-p  : Specify the build parameters in the key=value format.
-s  : Wait until the completion/abortion of the command. Interrupts are passed through to the build.
-v  : Prints out the console output of the build. Use with -s
-w  : Wait until the start of the command
Example  – java -jar jenkins-cli.jar -s http://localhost:8080/ build ‘my-project-build’ –username roop –password roop
E.g 3 – List all jobs under the view: tools
$ java -jar jenkins-cli.jar -s http://jenkins/ list-jobs tools
E.g 4 – Get the configuration of the job: template
$ java -jar jenkins-cli.jar -s http://jenkins/ get-job template > template.xml
E.g 5 – Create a new job based on the configuration
$ java -jar jenkins-cli.jar -s http://jenkins/ create-job new_job_name < new_job_name.xml
E.g 6 – Run groovy script
$ java -jar jenkins-cli.jar -s http://jenkins/ groovy scripts/add_job_to_view.groovy
If there are any parameters in the script, just as:
import jenkins.model.*
if (args.length != 2 ) {
  println “Error on arguments!”
}
def jobName  = args[0] ?: ‘a_job’
def viewName = args[1] ?: ‘a_view’
println jobName + ‘ ‘ + viewName
def v = Jenkins.instance.getView(viewName)
def i = Jenkins.instance.getItemByFullName(jobName)
if (v && i) {
  v.add(i)
}
pass the parameters as:
$ java -jar jenkins-cli.jar -s http://jenkins/ groovy scripts/add_job_to_view.groovy JOB_NAME VIEM_NAME
E.g 7 – Build a job
$ java -jar jenkins-cli.jar -s http://jenkins/ build new_job_name
E.g 8 – Diable a job
$ java -jar jenkins-cli.jar -s http://jenkins/ disable-job new_job_name
E.g 8 – Passing parameters when triggering a job build
Job parameters are a very handy concept. Perhaps you’ve only ever used Jenkins or another CI system to automatically run builds when a remote SCM/git repo changes. You can also trigger builds manually from within Jenkins. And whilst you’re doing that, your job can prompt for parameters to the build.
For example, we have a job named similar to “Deploy XYZ App”. It has the git repo hardcoded in the job like a normal build, but when you press “Build”, it shows a list of options: string fields, drop-down lists, etc.
When the job runs, you can use these values anywhere within your job’s configuration. Its very cool.
But how to pass those same parameters via the CLI? You use the -p key=value flag for each parameter you want to pass.
So our finished product might look like:
$ java -jar jenkins-cli.jar -s http://myjenkins build ‘Deploy XYZ App’ -i ~/.ssh/id_rsa -s -v -p target_env=api.cloudfoundry.com -p branch=master
Commons problems
Operation timed out
$ java -jar jenkins-cli.jar -s YOUR_SERVER_URL help
Exception in thread “main” java.net.ConnectException: Operation timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at hudson.cli.CLI.<init>(CLI.java:97)
at hudson.cli.CLI.<init>(CLI.java:82)
at hudson.cli.CLI._main(CLI.java:250)
at hudson.cli.CLI.main(CLI.java:199)
Check that the JNLP port is opened if you are using a firewall on your server. You can configure its value in Jenkins configuration. By default it is set to use a random port.
java.io.IOException: No X-Jenkins-CLI2-Port
java.io.IOException: No X-Jenkins-CLI2-Port among [X-Jenkins, null, Server, X-Content-Type-Options, Connection, X-You-Are-In-Group, X-Hudson, X-Permission-Implied-By, Date, X-Jenkins-Session, X-You-Are-Authenticated-As, X-Required-Permission, Set-Cookie, Expires, Content-Length, Content-Type]
at hudson.cli.CLI.getCliTcpPort(CLI.java:284)
at hudson.cli.CLI.<init>(CLI.java:128)
at hudson.cli.CLIConnectionFactory.connect(CLIConnectionFactory.java:72)
at hudson.cli.CLI._main(CLI.java:473)
at hudson.cli.CLI.main(CLI.java:384)
Suppressed: java.io.IOException: Server returned HTTP response code: 403 for URL: http://citest.gce.px/cli
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1840)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at hudson.cli.FullDuplexHttpStream.<init>(FullDuplexHttpStream.java:78)
at hudson.cli.CLI.connectViaHttp(CLI.java:152)
at hudson.cli.CLI.<init>(CLI.java:132)
… 3 more
Solution: Go to Manage Jenkins -> Configure Global Security -> “TCP port for JNLP agents”: choose fixed or random
Reference
Tagged : / / / / / / / /

Generate Jenkins Job Configuration Automatically | Jenkins Tutorials

generate-jenkins-job-configuration-automatically
Generate Jenkins Job Configuration Automatically?
Job DSL Plugin
The job-dsl-plugin allows the programmatic creation of projects using a DSL. Pushing job creation into a script allows you to automate and standardize your Jenkins installation, unlike anything possible before.
More –
Multi-Branch Project Plugin
This plugin adds additional project types that create sub-projects for each branch using a shared configuration.
Job Generator Plugin
This plugin adds a new job type “Job Generator” which can generate new projects when executed.
Jenkins Job Builder
Jenkins Job Builder takes simple descriptions of Jenkins jobs in YAML or JSON format and uses them to configure Jenkins. You can keep your job descriptions in human readable text format in a version control system to make changes and auditing easier. It also has a flexible template system, so creating many similarly configured jobs is easy.
More –
Generating New Jenkins Jobs From Templates and Parameterised Builds
We use Jenkins to run our builds in a continuously. This is great, but you still have to do a fair bit of configuration each time you set up a new job. If you have a fairly static set of builds this isn’t a problem. We found ourselves in a situation where we had to create a lot of very similar builds quite regularly. Creating a new job by hand and manually changing the 10 or so tiny little things in each build is a pain and error prone. So…automate that too!
More
Tagged : / / / / / / /