Jenkins是持续集成工具。
回想一个web项目从开发到发布的过程:
这些过程涉及到多个系统,以及繁琐的流程,容易出错并且浪费时间。有没有办法自动化构建、发布的过程?
开发人员只编写代码,此后所有的流程自动进行,做到“持续交付”。
默认工作目录是:/root/.jenkins/
docker pull jenkinsci/blueocean
docker run
–rm
-u root
-p 8080:8080
–name jenkins-tutorials
-v jenkins-data:/var/jenkins_home
-v /var/run/docker.sock:/var/run/docker.sock
-v “$HOME”:/home
jenkinsci/blueocean
两种主要的项目风格:
配置一系列的build step,构建项目。
通过脚本的方式,声明构建步骤:
脚本文件可以以Jenkinsfile文件的形式,放在git项目的根目录下,方便维护。
Jenkinsfile (Declarative Pipeline) pipeline { agent none stages { stage('Back-end') { agent { docker { image 'maven:3-alpine' } } steps { sh 'mvn --version' } } stage('Front-end') { agent { docker { image 'node:7-alpine' } } steps { sh 'node --version' } } } }
如何编写Jenkinsfile?
点击Pipeline Syntax
这个插件帮助更好得编写Pipeline脚本
具体语法参考官方文档。
pipeline支持 scripted风格 和 declarative风格。推荐scripted风格,因为scripted风格支持完整的groovy脚本语法,可构建更复杂的程序。
Jenkins有很多插件,推荐安装:
Jenkins提供了REST风格的API,处于安全考虑需要进行身份权限验证。
创建用户Token
http://JENKINS_URL/user/USER_NAME/configure
获取API
通过JENKINS_URL/api,可获取相关的REST风格API
通过浏览器F12监听网络请求:
HttpClient调用REST接口
https://wiki.jenkins.io/display/JENKINS/Remote+access+API
下面的代码实现触发一个Job的构建:
public class SendRest { public static void main(String[] args) throws Exception { URI uri = URI.create("http://192.168.142.137:8080/job/simple/build?delay=0sec"); HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials("root", "116bedfdda8414165e30bad1f284a6b3cd")); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(host, basicAuth); CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); HttpPost httppost = new HttpPost(uri); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); httppost.setEntity(entity); // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); HttpResponse response = httpClient.execute(host, httppost, localContext); System.out.println(EntityUtils.toString(response.getEntity())); } }