mcpField
J
jenkins

jenkins

github.com/bagelhole云与 DevOps1.2k340 次安装23 周前更新
代码仓库

关于 jenkins

面向 Jenkins 管理员和开发团队的 CI/CD 技能,涵盖流水线、构建 Agent、凭据、插件及共享库配置,并提供声明式与脚本式示例。

主要功能

  1. 01声明式与脚本式流水线
  2. 02Docker、Kubernetes 和标签式 Agent
  3. 03参数与凭据配置
  4. 04并行阶段和多分支流水线
  5. 05共享库复用流水线代码
  6. 06插件与 Configuration as Code 管理

适用场景

  1. 01为应用仓库编写 Jenkinsfile
  2. 02配置容器或 Kubernetes 构建 Agent
  3. 03通过共享库复用构建和部署步骤
  4. 04管理 Jenkins 插件与服务器配置

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/bagelhole/devops-security-agent-skills --skill jenkins

安装后在 Claude Code 中输入/jenkins确认已加载。

附带文件references/pipeline-syntax.md

详细介绍

Jenkins

使用领先的开源自动化服务器 Jenkins 构建、测试和部署应用程序。

何时使用此技能

在以下情况下使用此技能:

  • 设置 Jenkins 流水线(声明式或脚本式)
  • 配置 Jenkins Agent 和执行器
  • 管理 Jenkins 插件和安全性
  • 创建用于复用流水线的共享库
  • 将 Jenkins 与外部工具集成

前提条件

  • Jenkins 服务(2.x 或更高版本)
  • Jenkins 管理员权限
  • Jenkins 服务上安装 Java 11+
  • 具备基本的 Groovy 知识,以便编写流水线

声明式流水线

在仓库根目录中创建 Jenkinsfile:

pipeline {
    agent any
    
    environment {
        DOCKER_REGISTRY = 'registry.example.com'
        APP_NAME = 'myapp'
    }
    
    stages {
        stage('Build') {
            steps {
                sh 'npm ci'
                sh 'npm run build'
            }
        }
        
        stage('Test') {
            steps {
                sh 'npm test'
            }
            post {
                always {
                    junit 'test-results/*.xml'
                }
            }
        }
        
        stage('Deploy') {
            when {
                branch 'main'
            }
            steps {
                sh './deploy.sh'
            }
        }
    }
    
    post {
        failure {
            mail to: '[email protected]',
                 subject: "Pipeline Failed: ${env.JOB_NAME}",
                 body: "Check console output at ${env.BUILD_URL}"
        }
    }
}

Agent 配置

Docker Agent
pipeline {
    agent {
        docker {
            image 'node:20'
            args '-v /tmp:/tmp'
        }
    }
    stages {
        stage('Build') {
            steps {
                sh 'npm ci && npm run build'
            }
        }
    }
}
Kubernetes Agent
pipeline {
    agent {
        kubernetes {
            yaml '''
                apiVersion: v1
                kind: Pod
                spec:
                  containers:
                  - name: node
                    image: node:20
                    command:
                    - sleep
                    args:
                    - infinity
                  - name: docker
                    image: docker:24-dind
                    securityContext:
                      privileged: true
            '''
        }
    }
    stages {
        stage('Build') {
            steps {
                container('node') {
                    sh 'npm ci && npm run build'
                }
            }
        }
    }
}
带标签的 Agent
pipeline {
    agent { label 'linux && docker' }
    stages {
        stage('Build') {
            steps {
                sh 'make build'
            }
        }
    }
}

参数

pipeline {
    agent any
    
    parameters {
        string(name: 'BRANCH', defaultValue: 'main', description: 'Branch to build')
        choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'prod'], description: 'Target environment')
        booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run tests?')
    }
    
    stages {
        stage('Deploy') {
            when {
                expression { params.ENVIRONMENT == 'prod' }
            }
            steps {
                sh "deploy.sh ${params.ENVIRONMENT}"
            }
        }
    }
}

凭据

使用凭据
pipeline {
    agent any
    
    environment {
        AWS_CREDS = credentials('aws-credentials')
        DOCKER_CREDS = credentials('docker-hub')
    }
    
    stages {
        stage('Deploy') {
            steps {
                withCredentials([
                    usernamePassword(
                        credentialsId: 'github-token',
                        usernameVariable: 'GH_USER',
                        passwordVariable: 'GH_TOKEN'
                    )
                ]) {
                    sh 'git push https://${GH_USER}:${GH_TOKEN}@github.com/repo.git'
                }
            }
        }
    }
}

并行阶段

pipeline {
    agent any
    
    stages {
        stage('Tests') {
            parallel {
                stage('Unit Tests') {
                    steps {
                        sh 'npm run test:unit'
                    }
                }
                stage('Integration Tests') {
                    steps {
                        sh 'npm run test:integration'
                    }
                }
                stage('E2E Tests') {
                    steps {
                        sh 'npm run test:e2e'
                    }
                }
            }
        }
    }
}

共享库

库结构
vars/
├── buildApp.groovy
├── deployApp.groovy
└── notifySlack.groovy
src/
└── com/example/
    └── Pipeline.groovy
resources/
└── templates/
    └── deployment.yaml
定义共享步骤
// vars/buildApp.groovy
def call(Map config = [:]) {
    def nodeVersion = config.nodeVersion ?: '20'
    
    docker.image("node:${nodeVersion}").inside {
        sh 'npm ci'
        sh 'npm run build'
    }
}
使用共享库
@Library('my-shared-library') _

pipeline {
    agent any
    
    stages {
        stage('Build') {
            steps {
                buildApp(nodeVersion: '20')
            }
        }
        stage('Deploy') {
            steps {
                deployApp(environment: 'staging')
            }
        }
    }
    
    post {
        failure {
            notifySlack(channel: '#builds', status: 'FAILED')
        }
    }
}

脚本式流水线

node('linux') {
    try {
        stage('Checkout') {
            checkout scm
        }
        
        stage('Build') {
            docker.image('node:20').inside {
                sh 'npm ci'
                sh 'npm run build'
            }
        }
        
        stage('Test') {
            sh 'npm test'
        }
        
        if (env.BRANCH_NAME == 'main') {
            stage('Deploy') {
                sh './deploy.sh'
            }
        }
    } catch (e) {
        currentBuild.result = 'FAILURE'
        throw e
    } finally {
        cleanWs()
    }
}

插件管理

必备插件
// Install via Jenkins CLI or init.groovy.d
def plugins = [
    'workflow-aggregator',      // Pipeline
    'git',                      // Git integration
    'docker-workflow',          // Docker Pipeline
    'kubernetes',               // Kubernetes agent
    'credentials-binding',      // Credentials
    'blueocean',               // Blue Ocean UI
    'job-dsl',                 // Job DSL
    'configuration-as-code'    // JCasC
]
配置即代码
# jenkins.yaml
jenkins:
  systemMessage: "Jenkins configured via JCasC"
  numExecutors: 2
  
  securityRealm:
    local:
      users:
        - id: admin
          password: ${ADMIN_PASSWORD}
  
  authorizationStrategy:
    globalMatrix:
      permissions:
        - "Overall/Administer:admin"
        - "Overall/Read:authenticated"

credentials:
  system:
    domainCredentials:
      - credentials:
          - usernamePassword:
              id: "docker-hub"
              username: "user"
              password: ${DOCKER_PASSWORD}

多分支流水线

// Automatically discovers branches with Jenkinsfile
// Configure in Jenkins UI: New Item > Multibranch Pipeline

// Branch-specific behavior in Jenkinsfile
pipeline {
    agent any
    
    stages {
        stage('Deploy') {
            when {
                anyOf {
                    branch 'main'
                    branch 'release/*'
                }
            }
            steps {
                sh './deploy.sh'
            }
        }
    }
}

常见问题

问题:流水线语法错误

问题:Jenkinsfile 解析失败 解决方案:使用 Jenkins UI 中的 Pipeline Syntax 生成器,并使用 jenkins-cli 验证

问题:Agent 无法连接

问题:构建 Agent 断开连接 解决方案:检查 Agent 日志,确认网络连接正常,并增加超时设置

问题:内存不足

问题:Jenkins 崩溃或构建因 OOM 失败 解决方案:在 JAVA_OPTS 中增加堆大小,并清理旧构建

最佳实践

  • 大多数情况下使用声明式流水线
  • 通过共享库实现代码复用
  • 将 Jenkinsfile 存入源代码管理系统
  • 使用凭据插件管理密钥
  • 在 post 块中实施适当的清理操作
  • 配置构建保留策略
  • 使用 Blue Ocean 获得现代化 UI 体验

相关技能

评论

支持 Markdown