Jenkins食用指南

简介

Jenkins is a self-contained, open source automation server which can be used to automate all sorts of tasks related to building, testing, and delivering or deploying software.

Jenkins是一个开源的基于java开发的持续集成(CI)工具,它可以通过Docker容器,原生系统包,以及在已有JRE(Java运行环境)的机器上安装。Jenkins是高度可扩展的,拥有强大的插件机制。Jenkins 的核心特性是 Pipeline, 它给 Jenkins 提供了一组强大的自动化工具。

安装指引

重点介绍Docker方式安装,官网的教程需要构建自定义镜像完成,这里建议直接使用jenkinsci/blueocean

  1. 创建docker-compose文件
version: "3.9"

services:
  jenkins:
    image: jenkinsci/blueocean
    container_name: jenkins
    user: root
    # 需要特权权限运行,container内的root拥有真正的root权限
    privileged: true
    ports:
      - "8888:8080"
      - "50000:50000"
    volumes:
      # 容器内运行本机的docker daemon(Docker in Docker)
      - /var/run/docker.sock:/var/run/docker.sock
      - ./jenkins-data:/var/jenkins_home
      - ./workspace:/home
  1. 启动容器
docker-compose up -d
  1. 打开web UI
    Jenkins UI

流水线(Pipeline)

Jenkins Pipeline (or simply "Pipeline" with a capital "P") is a suite of plugins which supports implementing and integrating continuous delivery pipelines into Jenkins.

Pipeline 定义了一套DSL语法,能完成从简单到复杂的自动化过程,它可以在定义在项目仓库Jenkinsfile文件种,也可以定义在Jenkins web UI中(静态配置的 Jenkinsfile)。

Pipeline支持两种格式的语法,声明式(Declarative)和脚本式(Scripted)。最初Pipeline是选择Groovy语言作为DSL来完成一系列的自动化过程,直到Pipeline plugin 2.5以后才引入声明式DSL。脚本式拥有完整的编程环境,便于扩展,相当灵活但上手难度较大,需要熟悉Groovy语法,而声明式则严格定义了严格的结构,用户只能在有限的语法下编写,相对容易,且目前式官方推荐的方式。另外,Pipeline也提供YAML格式的预览特性。

Declarative Pipeline

pipeline {
  agent any

  stages {
    stage('build app') {
      agent {
        docker {
          image 'node:lts-buster-slim'
          reuseNode true
        }
      }
      steps {
        echo 'start build web app'
        sh 'yarn build'
      }
    }

    stage('deploy) {
      steps {
        script {
          def remote = [:]
          remote.name = "remote"
          remote.host = "fake-remote"
          remote.allowAnyHosts = true
          remote.fileTransfer = "scp"
          // remote.logLevel = "ALL"
          
          withCredentials([sshUserPrivateKey(
              credentialsId: 'ssh', 
              keyFileVariable: 'ssh_key', 
              usernameVariable: 'userName')]
          ) {
            remote.user = userName
            remote.identityFile = ssh_key
            sshPut remote: remote, from: 'build', into: '/home/'
          }
        }
      }
    }
  }
}

Groovy语法

TODO

参考