Jenkins Pipeline (流水线) 实战

1. 基于 Pipeline Script 创建任务

  1. 创建 Pipeline 任务

    • 新建任务 -> 输入名称 oldboyedu-linux98-yiliao-pipeline -> 选择 流水线 (Pipeline)。

    [此处插入图片22: Jenkins新建任务页面,红框标识了 “流水线” 选项]

    74297d5a9c8cbda26dd609ca230bc0d7

  2. 编写 Pipeline 脚本

    • 在配置页面的 Pipeline 部分,将以下脚本直接粘贴到 Script 文本框中。

      Generated groovy

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      pipeline {
      agent any

      stages {
      stage('pull code') {
      steps {
      git credentialsId: '83da8426-9aa0-42be-bef8-9688e5fa54f8', url: 'http://10.0.0.153/root/oldboyedu-yiliao.git'
      }
      }

      stage('build image') {
      steps {
      sh '''docker build -t harbor250.oldboyedu.com/oldboyedu-cicd/yiliao:v0.2 .'''
      }
      }

      stage('push image') {
      steps {
      sh '''docker login -u admin -p 1 harbor250.oldboyedu.com
      docker push harbor250.oldboyedu.com/oldboyedu-cicd/yiliao:v0.2'''
      }
      }


      stage('deploy or update image') {
      steps {
      sh '''kubectl set image deploy deploy-yiliao c1=harbor250.oldboyedu.com/oldboyedu-cicd/yiliao:v0.2
      kubectl get pods -o wide -l apps=yiliao
      kubectl get svc svc-yiliao
      kubectl describe svc svc-yiliao | grep Endpoints'''
      }
      }
      }
      }

    构建与验证

  • 保存并 Build with Parameters,流程将按阶段(Stage)执行,UI上会直观地展示每个阶段的状态。

2. 基于 Jenkinsfile 创建任务

  1. 在代码仓库中创建 Jenkinsfile

    • 在项目代码的根目录,创建一个名为 Jenkinsfile 的文件,内容为上面的 Pipeline 脚本。
    • git add Jenkinsfile, git commit, git push 推送到代码仓库。
  2. 修改 Pipeline 任务配置

    • 在 Pipeline 任务配置页面,将 Definition (定义) 从 Pipeline script 修改为 Pipeline script from SCM (从源码管理获取)。
    • SCM: 选择 Git。
    • 配置 Repository URL 和 Credentials。
    • Script Path: 保持默认的 Jenkinsfile。

    [此处插入图片24: Jenkins Pipeline SCM配置,红框标识了 “Pipeline script from SCM”、Git SCM选项、仓库URL和凭证]

    e815af76825f0d99ade633d796a26bc9

    [此处插入图片25: Jenkins Pipeline SCM配置,红框标识了 Script Path 输入框,值为 “Jenkinsfile”]

    cdae2eb2d837aaa99220aafc5e0fd949

  3. 构建与验证

    • 保存并构建。Jenkins 会自动从 Git 仓库拉取代码,并执行根目录下的 Jenkinsfile 文件中定义的流水线。这种方式实现了“流水线即代码”,便于版本控制和协作。

3. 如果不知道流水线语法,可以使用这个

屏幕截图 2025-07-24 213443

image-20250724213427342