jenkinsfile-generator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Jenkinsfile Generator Skill

Jenkinsfile生成器技能

Generate production-ready Jenkinsfiles following best practices. All generated files are validated using devops-skills:jenkinsfile-validator skill.
遵循最佳实践生成可用于生产环境的Jenkinsfile。所有生成的文件都会通过devops-skills:jenkinsfile-validator技能进行验证。

Trigger Phrases

触发语句

  • "Generate a CI pipeline for Maven/Gradle/npm"
  • "Create a Jenkins deployment pipeline with approvals"
  • "Build a Jenkinsfile with parallel test stages"
  • "Create a scripted pipeline with dynamic stage logic"
  • "Scaffold a Jenkins shared library"
  • "Generate a Jenkinsfile for Docker or Kubernetes agents"
  • "为Maven/Gradle/npm生成CI流水线"
  • "创建带审批环节的Jenkins部署流水线"
  • "构建包含并行测试阶段的Jenkinsfile"
  • "创建带有动态阶段逻辑的脚本式流水线"
  • "搭建Jenkins共享库"
  • "为Docker或Kubernetes代理生成Jenkinsfile"

When to Use

使用场景

  • Creating new Jenkinsfiles (declarative or scripted)
  • CI/CD pipelines, Docker/Kubernetes deployments
  • Parallel execution, matrix builds, parameterized pipelines
  • DevSecOps pipelines with security scanning
  • Shared library scaffolding
  • 创建新的Jenkinsfile(声明式或脚本式)
  • CI/CD流水线、Docker/Kubernetes部署
  • 并行执行、矩阵构建、参数化流水线
  • 包含安全扫描的DevSecOps流水线
  • 共享库搭建

Declarative vs Scripted Decision Tree

声明式 vs 脚本式选择决策树

  1. Choose Declarative by default when stage order and behavior are mostly static.
  2. Choose Scripted when runtime-generated stages, complex loops, or dynamic control flow are required.
  3. Choose Shared Library scaffolding when request is about reusable pipeline functions (
    vars/
    ,
    src/
    ,
    resources/
    ).
  4. If unsure, start Declarative and only switch to Scripted if requirements cannot be expressed cleanly.
  1. 当阶段顺序和行为基本静态时,默认选择Declarative(声明式)
  2. 当需要运行时生成阶段、复杂循环或动态控制流时,选择Scripted(脚本式)
  3. 当需求涉及可重用流水线函数(
    vars/
    src/
    resources/
    )时,选择Shared Library(共享库)搭建
  4. 若不确定,先从声明式开始,仅当需求无法清晰表达时再切换到脚本式。

Template Map

模板映射

TemplatePathUse When
Declarative basic
assets/templates/declarative/basic.Jenkinsfile
Standard CI/CD with predictable stages
Declarative parallel example
examples/declarative-parallel.Jenkinsfile
Parallel test/build branches with fail-fast behavior
Declarative kubernetes example
examples/declarative-kubernetes.Jenkinsfile
Kubernetes agent execution using pod templates
Scripted basic
assets/templates/scripted/basic.Jenkinsfile
Complex conditional logic or generated stages
Shared library scaffoldGenerated by
scripts/generate_shared_library.py
Reusable pipeline functions and organization-wide patterns
模板路径使用场景
Declarative basic
assets/templates/declarative/basic.Jenkinsfile
具有可预测阶段的标准CI/CD流水线
Declarative parallel example
examples/declarative-parallel.Jenkinsfile
带有快速失败机制的并行测试/构建分支
Declarative kubernetes example
examples/declarative-kubernetes.Jenkinsfile
使用Pod模板的Kubernetes代理执行
Scripted basic
assets/templates/scripted/basic.Jenkinsfile
复杂条件逻辑或生成式阶段
Shared library scaffold
scripts/generate_shared_library.py
生成
可重用流水线函数和组织级通用模式

Quick Reference

快速参考

groovy
// Minimal Declarative Pipeline
pipeline {
    agent any
    stages {
        stage('Build') { steps { sh 'make' } }
        stage('Test') { steps { sh 'make test' } }
    }
}

// Error-tolerant stage
stage('Flaky Tests') {
    steps {
        catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE') {
            sh 'run-flaky-tests.sh'
        }
    }
}

// Conditional deployment with approval
stage('Deploy') {
    when { branch 'main'; beforeAgent true }
    input { message 'Deploy to production?' }
    steps { sh './deploy.sh' }
}
OptionPurpose
timeout(time: 1, unit: 'HOURS')
Prevent hung builds
buildDiscarder(logRotator(numToKeepStr: '10'))
Manage disk space
disableConcurrentBuilds()
Prevent race conditions
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE')
Continue on error
groovy
// 极简声明式流水线
pipeline {
    agent any
    stages {
        stage('Build') { steps { sh 'make' } }
        stage('Test') { steps { sh 'make test' } }
    }
}

// 容错阶段
stage('Flaky Tests') {
    steps {
        catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE') {
            sh 'run-flaky-tests.sh'
        }
    }
}

// 带审批的条件部署
stage('Deploy') {
    when { branch 'main'; beforeAgent true }
    input { message 'Deploy to production?' }
    steps { sh './deploy.sh' }
}
选项用途
timeout(time: 1, unit: 'HOURS')
防止构建挂起
buildDiscarder(logRotator(numToKeepStr: '10'))
管理磁盘空间
disableConcurrentBuilds()
防止竞争条件
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE')
出错后继续执行

Core Capabilities

核心能力

1. Declarative Pipelines (RECOMMENDED)

1. 声明式流水线(推荐)

Process:
  1. Read templates for structure reference:
    • Read
      assets/templates/declarative/basic.Jenkinsfile
      to understand the standard structure
    • Templates show the expected sections: pipeline → agent → environment → options → parameters → stages → post
    • For complex requests, adapt the structure rather than copying verbatim
  2. Consult reference documentation:
    • Read
      references/best_practices.md
      for performance, security, and reliability patterns
    • Read
      references/common_plugins.md
      for plugin-specific syntax
  3. Generate with required elements:
    • Proper stages with descriptive names
    • Environment block with credentials binding (never hardcode secrets)
    • Options: timeout, buildDiscarder, timestamps, disableConcurrentBuilds
    • Post conditions: always (cleanup), success (artifacts), failure (notifications)
    • Always add
      failFast true
      or
      parallelsAlwaysFailFast()
      for parallel blocks
    • Always include
      fingerprint: true
      when using
      archiveArtifacts
  4. ALWAYS validate using devops-skills:jenkinsfile-validator skill
流程:
  1. 参考模板结构:
    • 读取
      assets/templates/declarative/basic.Jenkinsfile
      了解标准结构
    • 模板展示了预期的部分:pipeline → agent → environment → options → parameters → stages → post
    • 对于复杂需求,调整结构而非直接复制
  2. 查阅参考文档:
    • 阅读
      references/best_practices.md
      获取性能、安全和可靠性模式
    • 阅读
      references/common_plugins.md
      获取插件特定语法
  3. 生成包含必要元素的流水线:
    • 具有描述性名称的合理阶段
    • 包含凭证绑定的Environment块(切勿硬编码密钥)
    • 选项:timeout、buildDiscarder、timestamps、disableConcurrentBuilds
    • Post条件:always(清理)、success(制品归档)、failure(通知)
    • 并行块中始终添加
      failFast true
      parallelsAlwaysFailFast()
    • 使用
      archiveArtifacts
      时始终包含
      fingerprint: true
  4. 必须验证:使用devops-skills:jenkinsfile-validator技能

2. Scripted Pipelines

2. 脚本式流水线

When: Complex conditional logic, dynamic generation, full Groovy control Process:
  1. Read templates for structure reference:
    • Read
      assets/templates/scripted/basic.Jenkinsfile
      for node/stage patterns
    • Understand try-catch-finally structure for error handling
  2. Implement try-catch-finally for error handling
  3. ALWAYS validate using devops-skills:jenkinsfile-validator skill
**适用场景:**复杂条件逻辑、动态生成、完整Groovy控制 流程:
  1. 参考模板结构:
    • 读取
      assets/templates/scripted/basic.Jenkinsfile
      了解node/stage模式
    • 理解用于错误处理的try-catch-finally结构
  2. 实现try-catch-finally错误处理
  3. 必须验证:使用devops-skills:jenkinsfile-validator技能

3. Parallel/Matrix Pipelines

3. 并行/矩阵流水线

Use
parallel {}
block or
matrix {}
with
axes {}
for multi-dimensional builds.
  • Default behavior is fail-fast for generated parallel pipelines (
    parallelsAlwaysFailFast()
    or stage-level
    failFast true
    ).
使用
parallel {}
块或带
axes {}
matrix {}
实现多维构建。
  • 生成的并行流水线默认启用快速失败机制(
    parallelsAlwaysFailFast()
    或阶段级
    failFast true
    )。

4. Security Scanning (DevSecOps)

4. 安全扫描(DevSecOps)

Add SonarQube, OWASP Dependency-Check, Trivy stages with fail thresholds.
添加SonarQube、OWASP Dependency-Check、Trivy阶段并设置失败阈值。

5. Shared Library Scaffolding

5. 共享库搭建

bash
python3 scripts/generate_shared_library.py --name my-library --package org.example
bash
python3 scripts/generate_shared_library.py --name my-library --package org.example

Declarative Syntax Reference

声明式语法参考

Agent Types

代理类型

groovy
agent any                                    // Any available agent
agent { label 'linux && docker' }           // Label-based
agent { docker { image 'maven:3.9.11-eclipse-temurin-21' } }
agent { kubernetes { yaml '...' } }         // K8s pod template
agent { kubernetes { yamlFile 'pod.yaml' } } // External YAML
groovy
agent any                                    // 任意可用代理
agent { label 'linux && docker' }           // 基于标签选择代理
agent { docker { image 'maven:3.9.11-eclipse-temurin-21' } }
agent { kubernetes { yaml '...' } }         // K8s Pod模板
agent { kubernetes { yamlFile 'pod.yaml' } } // 外部YAML文件

Environment & Credentials

环境变量与凭证

groovy
environment {
    VERSION = '1.0.0'
    AWS_KEY = credentials('aws-key-id')     // Creates _USR and _PSW vars
}
groovy
environment {
    VERSION = '1.0.0'
    AWS_KEY = credentials('aws-key-id')     // 创建_USR和_PSW变量
}

Options

选项

groovy
options {
    buildDiscarder(logRotator(numToKeepStr: '10'))
    timeout(time: 1, unit: 'HOURS')
    disableConcurrentBuilds()
    timestamps()
    parallelsAlwaysFailFast()
    durabilityHint('PERFORMANCE_OPTIMIZED')  // 2-6x faster for simple pipelines
}
groovy
options {
    buildDiscarder(logRotator(numToKeepStr: '10'))
    timeout(time: 1, unit: 'HOURS')
    disableConcurrentBuilds()
    timestamps()
    parallelsAlwaysFailFast()
    durabilityHint('PERFORMANCE_OPTIMIZED')  // 简单流水线速度提升2-6倍
}

Parameters

参数

groovy
parameters {
    string(name: 'VERSION', defaultValue: '1.0.0')
    choice(name: 'ENV', choices: ['dev', 'staging', 'prod'])
    booleanParam(name: 'SKIP_TESTS', defaultValue: false)
}
groovy
parameters {
    string(name: 'VERSION', defaultValue: '1.0.0')
    choice(name: 'ENV', choices: ['dev', 'staging', 'prod'])
    booleanParam(name: 'SKIP_TESTS', defaultValue: false)
}

When Conditions

条件判断

ConditionExample
branch
branch 'main'
or
branch pattern: 'release/*', comparator: 'GLOB'
tag
tag pattern: 'v*', comparator: 'GLOB'
changeRequest
changeRequest target: 'main'
changeset
changeset 'src/**/*.java'
expression
expression { env.DEPLOY == 'true' }
allOf/anyOf/not
Combine conditions
Add
beforeAgent true
to skip agent allocation if condition fails.
条件示例
branch
branch 'main'
branch pattern: 'release/*', comparator: 'GLOB'
tag
tag pattern: 'v*', comparator: 'GLOB'
changeRequest
changeRequest target: 'main'
changeset
changeset 'src/**/*.java'
expression
expression { env.DEPLOY == 'true' }
allOf/anyOf/not
组合条件
添加
beforeAgent true
可在条件不满足时跳过代理分配。

Error Handling

错误处理

groovy
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') { sh '...' }
warnError('msg') { sh '...' }      // Mark UNSTABLE but continue
unstable(message: 'Coverage low')   // Explicit UNSTABLE
error('Config missing')             // Fail without stack trace
groovy
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') { sh '...' }
warnError('msg') { sh '...' }      // 标记为UNSTABLE但继续执行
unstable(message: 'Coverage low')   // 显式标记为UNSTABLE
error('Config missing')             // 无堆栈跟踪直接失败

Post Section

Post环节

groovy
post {
    always { junit '**/target/*.xml'; cleanWs() }
    success { archiveArtifacts artifacts: '**/*.jar', fingerprint: true }
    failure { slackSend color: 'danger', message: 'Build failed' }
    fixed { echo 'Build fixed!' }
}
Order: always → changed → fixed → regression → failure → success → unstable → cleanup
NOTE: Always use
fingerprint: true
with
archiveArtifacts
for build traceability and artifact tracking.
groovy
post {
    always { junit '**/target/*.xml'; cleanWs() }
    success { archiveArtifacts artifacts: '**/*.jar', fingerprint: true }
    failure { slackSend color: 'danger', message: 'Build failed' }
    fixed { echo 'Build fixed!' }
}
执行顺序: always → changed → fixed → regression → failure → success → unstable → cleanup
注意: 使用
archiveArtifacts
时始终添加
fingerprint: true
,以实现构建可追溯性和制品跟踪。

Parallel & Matrix

并行与矩阵

IMPORTANT: Always ensure parallel blocks fail fast on first failure using one of these approaches:
Option 1: Global (RECOMMENDED) - Use
parallelsAlwaysFailFast()
in pipeline options:
groovy
options {
    parallelsAlwaysFailFast()  // Applies to ALL parallel blocks in pipeline
}
This is the preferred approach as it covers all parallel blocks automatically.
Option 2: Per-block - Use
failFast true
on individual parallel stages:
groovy
stage('Tests') {
    failFast true  // Only affects this parallel block
    parallel {
        stage('Unit') { steps { sh 'npm test:unit' } }
        stage('E2E') { steps { sh 'npm test:e2e' } }
    }
}
NOTE: When
parallelsAlwaysFailFast()
is set in options, explicit
failFast true
on individual parallel blocks is redundant.
groovy
stage('Matrix') {
    failFast true
    matrix {
        axes {
            axis { name 'PLATFORM'; values 'linux', 'windows' }
            axis { name 'BROWSER'; values 'chrome', 'firefox' }
        }
        excludes { exclude { axis { name 'PLATFORM'; values 'linux' }; axis { name 'BROWSER'; values 'safari' } } }
        stages { stage('Test') { steps { echo "Testing ${PLATFORM}/${BROWSER}" } } }
    }
}
重要提示: 始终确保并行块在首次失败时快速终止,可通过以下方式实现:
方式1:全局设置(推荐) - 在流水线选项中使用
parallelsAlwaysFailFast()
groovy
options {
    parallelsAlwaysFailFast()  // 应用于流水线中所有并行块
}
这是首选方式,可自动覆盖所有并行块。
方式2:按块设置 - 在单个并行阶段使用
failFast true
groovy
stage('Tests') {
    failFast true  // 仅影响此并行块
    parallel {
        stage('Unit') { steps { sh 'npm test:unit' } }
        stage('E2E') { steps { sh 'npm test:e2e' } }
    }
}
注意: 当在选项中设置
parallelsAlwaysFailFast()
后,在单个并行块上显式设置
failFast true
是多余的。
groovy
stage('Matrix') {
    failFast true
    matrix {
        axes {
            axis { name 'PLATFORM'; values 'linux', 'windows' }
            axis { name 'BROWSER'; values 'chrome', 'firefox' }
        }
        excludes { exclude { axis { name 'PLATFORM'; values 'linux' }; axis { name 'BROWSER'; values 'safari' } } }
        stages { stage('Test') { steps { echo "Testing ${PLATFORM}/${BROWSER}" } } }
    }
}

Input (Manual Approval)

人工审批

groovy
stage('Deploy') {
    input { message 'Deploy?'; ok 'Deploy'; submitter 'admin,ops' }
    steps { sh './deploy.sh' }
}
IMPORTANT: Place
input
outside steps to avoid holding agents.
groovy
stage('Deploy') {
    input { message 'Deploy?'; ok 'Deploy'; submitter 'admin,ops' }
    steps { sh './deploy.sh' }
}
重要提示:
input
放在steps外部,避免占用代理资源。

Scripted Syntax Reference

脚本式语法参考

groovy
node('agent-label') {
    try {
        stage('Build') { sh 'make build' }
        stage('Test') { sh 'make test' }
    } catch (Exception e) {
        currentBuild.result = 'FAILURE'
        throw e
    } finally {
        deleteDir()
    }
}

// Parallel
parallel(
    'Unit': { node { sh 'npm test:unit' } },
    'E2E': { node { sh 'npm test:e2e' } }
)

// Environment
withEnv(['VERSION=1.0.0']) { sh 'echo $VERSION' }
withCredentials([string(credentialsId: 'key', variable: 'KEY')]) { sh 'curl -H "Auth: $KEY" ...' }
groovy
node('agent-label') {
    try {
        stage('Build') { sh 'make build' }
        stage('Test') { sh 'make test' }
    } catch (Exception e) {
        currentBuild.result = 'FAILURE'
        throw e
    } finally {
        deleteDir()
    }
}

// 并行执行
parallel(
    'Unit': { node { sh 'npm test:unit' } },
    'E2E': { node { sh 'npm test:e2e' } }
)

// 环境变量
withEnv(['VERSION=1.0.0']) { sh 'echo $VERSION' }
withCredentials([string(credentialsId: 'key', variable: 'KEY')]) { sh 'curl -H "Auth: $KEY" ...' }

@NonCPS for Non-Serializable Operations

@NonCPS用于非序列化操作

groovy
@NonCPS
def parseJson(String json) {
    new groovy.json.JsonSlurper().parseText(json)
}
Rules: No pipeline steps (
sh
,
echo
) inside @NonCPS. Use for JsonSlurper, iterators, regex Matchers.
groovy
@NonCPS
def parseJson(String json) {
    new groovy.json.JsonSlurper().parseText(json)
}
规则: @NonCPS内部不能包含流水线步骤(如
sh
echo
)。适用于JsonSlurper、迭代器、正则匹配器等场景。

Docker & Kubernetes

Docker与Kubernetes

Docker Agent

Docker代理

groovy
agent { docker { image 'maven:3.9.11'; args '-v $HOME/.m2:/root/.m2'; reuseNode true } }
groovy
agent { docker { image 'maven:3.9.11'; args '-v $HOME/.m2:/root/.m2'; reuseNode true } }

Build & Push

构建与推送

groovy
def img = docker.build("myapp:${BUILD_NUMBER}")
docker.withRegistry('https://registry.example.com', 'creds') { img.push(); img.push('latest') }
groovy
def img = docker.build("myapp:${BUILD_NUMBER}")
docker.withRegistry('https://registry.example.com', 'creds') { img.push(); img.push('latest') }

Kubernetes Pod

Kubernetes Pod

groovy
agent {
    kubernetes {
        yaml '''
apiVersion: v1
kind: Pod
spec:
  containers:
  - name: maven
    image: maven:3.9.11-eclipse-temurin-21
    command: [sleep, 99d]
'''
    }
}
// Use: container('maven') { sh 'mvn package' }
groovy
agent {
    kubernetes {
        yaml '''
apiVersion: v1
kind: Pod
spec:
  containers:
  - name: maven
    image: maven:3.9.11-eclipse-temurin-21
    command: [sleep, 99d]
'''
    }
}
// 使用方式: container('maven') { sh 'mvn package' }

Shared Libraries

共享库

groovy
@Library('my-shared-library') _
// or dynamically: library 'my-library@1.0.0'

// vars/log.groovy
def info(msg) { echo "INFO: ${msg}" }

// Usage
log.info 'Starting build'
groovy
@Library('my-shared-library') _
// 或动态加载: library 'my-library@1.0.0'

// vars/log.groovy
def info(msg) { echo "INFO: ${msg}" }

// 使用示例
log.info 'Starting build'

Validation Workflow

验证流程

CRITICAL: ALWAYS validate using devops-skills:jenkinsfile-validator skill:
  1. Generate Jenkinsfile
  2. Invoke
    devops-skills:jenkinsfile-validator
    skill
  3. Handle validation results by severity:
    • ERRORS: MUST fix before presenting to user - these break the pipeline
    • WARNINGS: SHOULD fix - these indicate potential issues
    • INFO/SUGGESTIONS: Consider applying based on use case:
      • failFast true
        for parallel blocks → apply by default
      • Build triggers → ask user if they want automated builds
      • Other optimizations → apply if they improve the pipeline
  4. Re-validate after fixes
  5. Only present validated Jenkinsfiles to user
Validation commands:
bash
undefined
关键要求:必须使用devops-skills:jenkinsfile-validator技能进行验证:
  1. 生成Jenkinsfile
  2. 调用
    devops-skills:jenkinsfile-validator
    技能
  3. 按严重程度处理验证结果:
    • ERRORS(错误): 必须修复后再交付给用户——这些问题会导致流水线失败
    • WARNINGS(警告): 应该修复——这些问题表示潜在风险
    • INFO/SUGGESTIONS(信息/建议): 根据使用场景考虑是否应用:
      • 并行块的
        failFast true
        → 默认应用
      • 构建触发器 → 询问用户是否需要自动构建
      • 其他优化 → 若能提升流水线则应用
  4. 修复后重新验证
  5. 仅向用户交付已通过验证的Jenkinsfile
验证命令:
bash
undefined

Full validation (syntax + security + best practices)

完整验证(语法+安全+最佳实践)

bash ../jenkinsfile-validator/scripts/validate_jenkinsfile.sh Jenkinsfile
bash ../jenkinsfile-validator/scripts/validate_jenkinsfile.sh Jenkinsfile

Syntax only (fastest)

仅语法验证(最快)

bash ../jenkinsfile-validator/scripts/validate_jenkinsfile.sh --syntax-only Jenkinsfile
undefined
bash ../jenkinsfile-validator/scripts/validate_jenkinsfile.sh --syntax-only Jenkinsfile
undefined

Generator Scripts

生成脚本

When to use scripts vs manual generation:
  • Use scripts for: Simple, standard pipelines with common patterns (basic CI, straightforward CD)
  • Use manual generation for: Complex pipelines with multiple features (parallel tests + security scanning + Docker + K8s deployments), custom logic, or non-standard requirements
何时使用脚本vs手动生成:
  • 使用脚本: 具有通用模式的简单标准流水线(基础CI、简单CD)
  • 手动生成: 包含多特性的复杂流水线(并行测试+安全扫描+Docker+K8s部署)、自定义逻辑或非标准需求

Script Arguments: Required vs Optional

脚本参数:必填vs可选

  • generate_declarative.py
  • Required:
    --output
  • Optional:
    --stages
    ,
    --agent
    ,
    --build-tool
    ,
    --build-cmd
    ,
    --test-cmd
    ,
    --deploy-*
    ,
    --notification-*
    ,
    --archive-artifacts
    ,
    --k8s-yaml
  • Notes:
  • --k8s-yaml
    accepts either inline YAML content or a path to an existing
    .yaml
    /
    .yml
    file.
  • Stage keys are validated (
    [a-z0-9_-]
    ) and shell commands are emitted as escaped Groovy literals.
  • generate_scripted.py
  • Required:
    --output
  • Optional: stage/agent/SCM/notification parameters depending on requested pipeline features.
  • generate_shared_library.py
  • Required:
    --name
  • Optional:
    --package
    ,
    --output
  • Shared library deployment helper now includes explicit rollout target (
    deployment/<name>
    ) and notification helper emits valid HTML email bodies.
bash
undefined
  • generate_declarative.py
  • 必填:
    --output
  • 可选:
    --stages
    ,
    --agent
    ,
    --build-tool
    ,
    --build-cmd
    ,
    --test-cmd
    ,
    --deploy-*
    ,
    --notification-*
    ,
    --archive-artifacts
    ,
    --k8s-yaml
  • 说明:
  • --k8s-yaml
    接受内联YAML内容或现有
    .yaml
    /
    .yml
    文件路径。
  • 阶段键会被验证(
    [a-z0-9_-]
    ),Shell命令会被转义为Groovy字面量。
  • generate_scripted.py
  • 必填:
    --output
  • 可选:根据请求的流水线特性提供阶段/代理/SCM/通知参数。
  • generate_shared_library.py
  • 必填:
    --name
  • 可选:
    --package
    ,
    --output
  • 共享库部署助手现在包含显式的部署目标(
    deployment/<name>
    ),通知助手会生成有效的HTML邮件内容。
bash
undefined

Declarative (simple pipelines)

声明式(简单流水线)

python3 scripts/generate_declarative.py --output Jenkinsfile --stages build,test,deploy --agent docker
python3 scripts/generate_declarative.py --output Jenkinsfile --stages build,test,deploy --agent docker

Scripted (simple pipelines)

脚本式(简单流水线)

python3 scripts/generate_scripted.py --output Jenkinsfile --stages build,test --agent label:linux
python3 scripts/generate_scripted.py --output Jenkinsfile --stages build,test --agent label:linux

Shared Library (always use script for scaffolding)

共享库(始终使用脚本搭建)

python3 scripts/generate_shared_library.py --name my-library --package com.example
undefined
python3 scripts/generate_shared_library.py --name my-library --package com.example
undefined

Done Criteria

完成标准

  • Pipeline style selection (Declarative vs Scripted) is explicit and justified.
  • Generated Jenkinsfiles pass smoke validation with executable validator commands.
  • Parallel pipelines are fail-fast by default unless user explicitly requests otherwise.
  • Custom stage names and shell commands are safely emitted (no unescaped Groovy literals).
  • --k8s-yaml
    works with both inline YAML and existing file paths.
  • Notification-enabled post blocks still archive artifacts when requested.
  • 流水线类型选择(声明式vs脚本式)明确且有合理依据。
  • 生成的Jenkinsfile可通过可执行的验证命令完成冒烟验证。
  • 并行流水线默认启用快速失败,除非用户明确要求不启用。
  • 自定义阶段名称和Shell命令被安全生成(无未转义的Groovy字面量)。
  • --k8s-yaml
    同时支持内联YAML和现有文件路径。
  • 启用通知的Post环节在请求时仍会归档制品。

Plugin Documentation Lookup

插件文档查询

Always consult Context7 or WebSearch for:
  • Plugins NOT covered in
    references/common_plugins.md
  • Version-specific documentation requests
  • Complex plugin configurations or advanced options
  • When user explicitly asks for latest documentation
May skip external lookup when:
  • Using basic plugin syntax already documented in
    references/common_plugins.md
  • Simple, well-documented plugin steps (e.g., basic
    sh
    ,
    checkout scm
    ,
    junit
    )
Plugins covered in common_plugins.md: Git, Docker, Kubernetes, Credentials, JUnit, Slack, SonarQube, OWASP Dependency-Check, Email, AWS, Azure, HTTP Request, Microsoft Teams, Nexus, Artifactory, GitHub
Lookup methods (in order of preference):
  1. Context7:
    mcp__context7__resolve-library-id
    with
    /jenkinsci/<plugin-name>-plugin
  2. WebSearch:
    Jenkins [plugin-name] plugin documentation 2025
  3. Official: plugins.jenkins.io, jenkins.io/doc/pipeline/steps/
始终通过Context7或WebSearch查询以下内容:
  • references/common_plugins.md
    未覆盖的插件
  • 特定版本的文档请求
  • 复杂插件配置或高级选项
  • 用户明确要求最新文档时
可跳过外部查询的场景:
  • 使用
    references/common_plugins.md
    中已记录的基础插件语法
  • 简单且文档完善的插件步骤(如基础
    sh
    checkout scm
    junit
common_plugins.md覆盖的插件: Git、Docker、Kubernetes、Credentials、JUnit、Slack、SonarQube、OWASP Dependency-Check、Email、AWS、Azure、HTTP Request、Microsoft Teams、Nexus、Artifactory、GitHub
查询方式(优先级从高到低):
  1. Context7: 使用
    mcp__context7__resolve-library-id
    ,参数为
    /jenkinsci/<plugin-name>-plugin
  2. WebSearch: 搜索
    Jenkins [plugin-name] plugin documentation 2025
  3. 官方渠道: plugins.jenkins.io、jenkins.io/doc/pipeline/steps/

References

参考资料

  • references/best_practices.md
    - Performance, security, reliability patterns
  • references/common_plugins.md
    - Git, Docker, K8s, credentials, notifications
  • assets/templates/
    - Declarative and scripted templates
  • devops-skills:jenkinsfile-validator
    skill - Syntax and best practices validation
Always prefer Declarative unless scripted flexibility is required.
  • references/best_practices.md
    - 性能、安全、可靠性模式
  • references/common_plugins.md
    - Git、Docker、K8s、凭证、通知
  • assets/templates/
    - 声明式和脚本式模板
  • devops-skills:jenkinsfile-validator
    技能 - 语法和最佳实践验证
始终优先选择声明式,除非需要脚本式的灵活性。