linux

Linux Jenkins怎样实现持续集成

小樊
40
2025-11-18 12:50:14
栏目: 智能运维

Linux 上用 Jenkins 实现持续集成的落地步骤

一 环境准备与安装

二 初始化与安全配置

三 创建任务与触发器

四 示例 Jenkinsfile 模板

pipeline {
  agent any
  tools {
    maven 'Maven-3'   // 需在 Global Tool Configuration 中定义
    jdk   'JDK-11'   // 需在 Global Tool Configuration 中定义
  }
  stages {
    stage('Checkout') {
      steps { git url: 'https://github.com/your-org/your-app.git', branch: 'main' }
    }
    stage('Build') {
      steps { sh 'mvn clean package -DskipTests' }
    }
    stage('Test') {
      steps { sh 'mvn test' }
    }
    stage('Deploy') {
      when { branch 'main' }
      steps {
        sh 'mvn deploy'   // 结合 settings.xml 与仓库凭证
        // 或使用 sshPublisher 将产物发布到目标主机
      }
    }
  }
  post {
    always { cleanWs() }
    success { echo 'Build & Test SUCCESS' }
    failure { echo 'Build FAILED' }
  }
}
pipeline {
  agent any
  tools { nodejs 'Node-16' }  // 需在 Global Tool Configuration 中定义
  stages {
    stage('Checkout') { steps { git url: 'https://github.com/your-org/your-web.git', branch: 'main' } }
    stage('Install')  { steps { sh 'npm ci' } }
    stage('Build')    { steps { sh 'npm run build' } }
    stage('Deploy')   {
      when { branch 'main' }
      steps {
        // 示例:使用 sshPublisher 发布到 Nginx 目录
        sshPublisher(publishers: [sshPublisherDesc(
          configName: 'prod-ssh',
          transfers: [sshTransfer(execCommand: 'cd /var/www && git pull', remoteDirectory: '/var/www')]
        )])
      }
    }
  }
}
pipeline {
  agent any
  stages {
    stage('Checkout') { steps { git url: 'https://github.com/your-org/your-cpp.git', branch: 'main' } }
    stage('Build')    { steps { sh 'make -j$(nproc)' } }
    stage('Test')     { steps { sh 'make test || true' } } // 视测试框架调整
    stage('Archive')  { steps { archiveArtifacts artifacts: '**/target/*.zip,**/build/*.tar.gz', fingerprint: true } }
  }
}

说明:上述示例使用 Jenkins Pipeline拉取代码、构建、测试、部署 串联为可重复执行的流水线;SSH 发布可借助 sshPublisher 插件完成远程部署。

五 运维与优化要点

0
看了该问题的人还看了