Skip to content

Jenkins 流水线

pipeline 声明式语法

注意

Jenkins 团队在一开始实现 Jenkins pipeline 时,Groovy 语言被选择作为基础来实现 pipeline。所以,在写 pipeline 脚本时,就是在写 groovy 脚本。但区别是,pipeline 是在上面封装了一层,需要用固定格式,jenkins 才可以识别。

groovy
pipeline {
  agent any

  stages {
    stage('pull') {
      steps {
        // 拉取指定代码库指定分支的代码
        // credentialsId表示jenkins的凭证的ID,如果是不需要凭证的项目则不需要使用credentialsId
        git branch: 'master', credentialsId: 'jenkins', url: 'https://gitlab.cghbh.com/open-source/open-docs.git'
          echo '开始拉取代码'
        }
    }

    stage('build') {
      // 这里可以执行多个步骤,但是每个stage应该有且仅有一个steps
      steps {
        echo '代码构建成功1'
        sh 'echo "Hello World"'
      }
    }
  }
}

以下声明式语法中,每个步骤都要有,少一个都会报错

  • pipeline:固定语法,代表整条流水线
  • agent:指定流水线在哪执行,默认 any 即可,也可以指定在 docker、虚拟机等等里执行
  • stages:流水线中多个 stage 的容器,至少包含一个 stage
  • stage:流水线的阶段,每个阶段都必须有名称,stage 必须有,且只能有一个 steps
  • steps:阶段中的一个或多个具体步骤(step)的容器,steps 部分至少包含一个步骤,echo 就是一个步骤
  • 顶层语句块只能是 pipeline {}
  • 每一个语句只能写在一行,没有分隔符,例如分号“;”

Jenkins 的脚本式语法

Jenkins 的 pipeline 动态切换 Nodejs 版本

需要先在 Jenkins 插件市场安装 nvm-wrapper。

shell
pipeline {
    agent any

    stages {
        stage('Hello') {
            steps {
                nvm(nvmInstallURL: 'https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh',
                    nvmIoJsOrgMirror: 'https://cdn.npmmirror.com/binaries/iojs',
                    nvmNodeJsOrgMirror: 'https://cdn.npmmirror.com/binaries/node',
                    version: '10.13.0'
                ) {
                    sh "node -v"
                }
            }
        }
    }
}