jenkinsfile-validator
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseJenkinsfile Validator Skill
Jenkinsfile 验证工具技能
Comprehensive toolkit for validating, linting, and testing Jenkinsfile pipelines (both Declarative and Scripted). This skill applies when working with Jenkins pipeline files, validating pipeline syntax, checking best practices, debugging pipeline issues, or working with custom plugins that require documentation lookup.
一款用于验证、代码检查、测试Jenkinsfile流水线(包括声明式和脚本式)的综合工具包。当你处理Jenkins流水线文件、验证流水线语法、检查最佳实践、调试流水线问题或需要查阅自定义插件文档时,可使用此技能。
When to Use This Skill
何时使用此技能
- Validating Jenkinsfile syntax before committing to repository
- Checking Jenkins pipeline best practices compliance
- Debugging pipeline syntax errors or configuration issues
- Validating both Declarative and Scripted pipeline syntaxes
- Validating Jenkins Shared Library files (vars/*.groovy, src//*.groovy)**
- Working with plugin-specific steps that need documentation
- Ensuring proper credential handling and security practices
- Checking for common anti-patterns and performance issues
- Verifying variable usage and scope
- 提交到代码仓库前验证Jenkinsfile语法
- 检查Jenkins流水线是否符合最佳实践
- 调试流水线语法错误或配置问题
- 验证声明式和脚本式两种流水线语法
- 验证Jenkins共享库文件(vars/*.groovy、src//*.groovy)**
- 使用需要查阅文档的插件专属步骤
- 确保凭证处理和安全实践合规
- 检查常见反模式和性能问题
- 验证变量使用和作用域
Validation Capabilities
验证能力
Declarative Pipeline Validation
声明式流水线验证
- Syntax Structure: Validates required sections (pipeline, agent, stages, steps)
- Directive Validation: Checks proper usage of environment, options, parameters, triggers, tools, when, input
- Best Practices: Parallel execution, credential management, combined shell commands
- Section Placement: Ensures directives are in correct locations
- 语法结构:验证必填章节(pipeline、agent、stages、steps)
- 指令验证:检查environment、options、parameters、triggers、tools、when、input等指令的正确用法
- 最佳实践:并行执行、凭证管理、合并shell命令
- 章节位置:确保指令处于正确位置
Scripted Pipeline Validation
脚本式流水线验证
- Groovy Syntax: Validates Groovy code syntax and structure
- Node Blocks: Ensures proper node/agent block usage
- Error Handling: Checks for try-catch-finally patterns
- Best Practices: @NonCPS usage, agent-based operations, proper variable scoping
- Groovy语法:验证Groovy代码的语法和结构
- Node块:确保node/agent块的正确使用
- 错误处理:检查try-catch-finally模式
- 最佳实践:@NonCPS用法、基于agent的操作、正确的变量作用域
Common Validations (Both Types)
通用验证(两种类型均适用)
- Security: Detects hardcoded credentials, passwords, API keys
- Performance: Identifies controller-heavy operations (JsonSlurper, HttpRequest on controller)
- Variables: Validates variable declarations and usage
- Plugins: Detects and validates plugin-specific steps with dynamic documentation lookup
- 安全:检测硬编码凭证、密码、API密钥
- 性能:识别控制器密集型操作(如在控制器上使用JsonSlurper、HttpRequest)
- 变量:验证变量声明和使用
- 插件:通过动态文档查找检测并验证插件专属步骤
Shared Library Validation
共享库验证
- vars/*.groovy: Validates global variable files (callable steps)
- call() method presence and signature
- @NonCPS annotation correctness (no pipeline steps in @NonCPS methods)
- CPS compatibility (closures with .each{}, .collect{}, etc.)
- Hardcoded credentials detection
- Controller-heavy operations (JsonSlurper, new URL(), new File())
- Thread.sleep() vs sleep() step
- System.getenv() vs env.VAR_NAME
- File naming conventions (camelCase)
- Documentation comment presence
- src//*.groovy**: Validates Groovy source class files
- Package declaration presence
- Class naming matches filename
- Serializable implementation (required for CPS)
- Wildcard import warnings
- Static method CPS compatibility
- vars/*.groovy:验证全局变量文件(可调用步骤)
- call()方法的存在和签名
- @NonCPS注解的正确性(@NonCPS方法中不能包含流水线步骤)
- CPS兼容性(使用.each{}、.collect{}等闭包)
- 硬编码凭证检测
- 控制器密集型操作(JsonSlurper、new URL()、new File())
- Thread.sleep()与sleep()步骤的对比
- System.getenv()与env.VAR_NAME的对比
- 文件命名规范(小驼峰式)
- 文档注释是否存在
- src//*.groovy**:验证Groovy源类文件
- 包声明是否存在
- 类名与文件名匹配
- 实现Serializable接口(CPS要求)
- 通配符导入警告
- 静态方法的CPS兼容性
Pipeline Type Detection
流水线类型检测
The skill automatically detects the pipeline type:
- Declarative: Starts with block
pipeline { - Scripted: Starts with or contains Groovy code outside pipeline block
node - Ambiguous: Will ask for clarification if uncertain
本技能会自动检测流水线类型:
- 声明式:以块开头
pipeline { - 脚本式:以开头或在pipeline块外包含Groovy代码
node - 模糊类型:若无法确定,会请求澄清
Core Validation Workflow
核心验证流程
Follow this workflow when validating Jenkinsfiles to catch issues early and ensure pipeline quality:
遵循以下流程验证Jenkinsfile,提前发现问题并确保流水线质量:
Quick Start - Full Validation (Recommended)
快速开始 - 完整验证(推荐)
bash
undefinedbash
undefinedRun complete validation (syntax + security + best practices)
运行完整验证(语法+安全+最佳实践)
bash scripts/validate_jenkinsfile.sh Jenkinsfile
This single command:
1. Auto-detects pipeline type (Declarative/Scripted)
2. Runs syntax validation
3. Runs security scan (credential detection)
4. Runs best practices check
5. Provides a unified summary with pass/fail statusbash scripts/validate_jenkinsfile.sh Jenkinsfile
该单一命令会:
1. 自动检测流水线类型(声明式/脚本式)
2. 运行语法验证
3. 运行安全扫描(凭证检测)
4. 运行最佳实践检查
5. 提供包含通过/失败状态的统一汇总Validation Options
验证选项
bash
undefinedbash
undefinedFull validation (default)
完整验证(默认)
bash scripts/validate_jenkinsfile.sh Jenkinsfile
bash scripts/validate_jenkinsfile.sh Jenkinsfile
Syntax validation only (fastest)
仅语法验证(最快)
bash scripts/validate_jenkinsfile.sh --syntax-only Jenkinsfile
bash scripts/validate_jenkinsfile.sh --syntax-only Jenkinsfile
Security audit only
仅安全审计
bash scripts/validate_jenkinsfile.sh --security-only Jenkinsfile
bash scripts/validate_jenkinsfile.sh --security-only Jenkinsfile
Best practices check only
仅最佳实践检查
bash scripts/validate_jenkinsfile.sh --best-practices Jenkinsfile
bash scripts/validate_jenkinsfile.sh --best-practices Jenkinsfile
Skip security checks
跳过安全检查
bash scripts/validate_jenkinsfile.sh --no-security Jenkinsfile
bash scripts/validate_jenkinsfile.sh --no-security Jenkinsfile
Skip best practices
跳过最佳实践
bash scripts/validate_jenkinsfile.sh --no-best-practices Jenkinsfile
bash scripts/validate_jenkinsfile.sh --no-best-practices Jenkinsfile
Strict mode (fail on warnings)
严格模式(警告视为失败)
bash scripts/validate_jenkinsfile.sh --strict Jenkinsfile
undefinedbash scripts/validate_jenkinsfile.sh --strict Jenkinsfile
undefinedWorkflow Diagram
流程示意图
┌─────────────────────────────────────────────────────────────┐
│ 1. Type Detection (Automatic) │
│ ├─ Declarative: starts with 'pipeline {' │
│ └─ Scripted: starts with 'node' or Groovy code │
│ ↓ │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 2. Syntax Validation (Required) │
│ ├─ Structure validation │
│ ├─ Required sections │
│ └─ Groovy syntax │
│ ↓ │
│ Reports errors → Continues to next phase │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 3. Security Scan (Required) │
│ ├─ Hardcoded credentials │
│ ├─ API keys / tokens │
│ ├─ Cloud provider credentials │
│ └─ Private keys / certificates │
│ ↓ │
│ Reports issues → Continues to next phase │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 4. Best Practices Check (Recommended) │
│ ├─ Combined shell commands │
│ ├─ Timeout configuration │
│ ├─ Workspace cleanup │
│ ├─ Error handling │
│ └─ Test result publishing │
│ ↓ │
│ Reports suggestions → Complete with summary │
└─────────────────────────────────────────────────────────────┘
**Note:** All validation phases run regardless of errors found in previous phases.
This ensures comprehensive reporting of all issues in a single run.┌─────────────────────────────────────────────────────────────┐
│ 1. 类型检测(自动) │
│ ├─ 声明式:以'pipeline {'开头 │
│ └─ 脚本式:以'node'开头或包含Groovy代码 │
│ ↓ │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 2. 语法验证(必填) │
│ ├─ 结构验证 │
│ ├─ 必填章节 │
│ └─ Groovy语法 │
│ ↓ │
│ 报告错误 → 继续下一阶段 │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 3. 安全扫描(必填) │
│ ├─ 硬编码凭证 │
│ ├─ API密钥/令牌 │
│ ├─ 云服务商凭证 │
│ └─ 私钥/证书 │
│ ↓ │
│ 报告问题 → 继续下一阶段 │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 4. 最佳实践检查(推荐) │
│ ├─ 合并shell命令 │
│ ├─ 超时配置 │
│ ├─ 工作区清理 │
│ ├─ 错误处理 │
│ └─ 测试结果发布 │
│ ↓ │
│ 报告建议 → 生成汇总完成 │
└─────────────────────────────────────────────────────────────┘
**注意**:无论前一阶段是否发现错误,所有验证阶段都会运行。
这确保在单次运行中全面报告所有问题。Script Architecture
脚本架构
The validation system uses a modular script architecture:
scripts/
├── validate_jenkinsfile.sh # Main orchestrator (USE THIS)
│ ├── Auto-detects pipeline type
│ ├── Runs syntax validation
│ ├── Runs security scan
│ ├── Runs best practices check
│ └── Produces unified summary
│
├── validate_declarative.sh # Declarative syntax validator
│ └── Called automatically for pipeline {} blocks
│
├── validate_scripted.sh # Scripted syntax validator
│ └── Called automatically for node {} blocks
│
├── common_validation.sh # Shared functions + security scan
│ ├── detect_type: Determine pipeline type
│ ├── check_credentials: Security credential scan
│ └── Common utilities
│
├── best_practices.sh # 15-point best practices scorer
│ └── Performance, security, maintainability checks
│
└── validate_shared_library.sh # Shared library validator
└── For vars/*.groovy and src/**/*.groovy filesKey Point: Always use as the main entry point - it orchestrates all other scripts automatically.
validate_jenkinsfile.sh验证系统采用模块化脚本架构:
scripts/
├── validate_jenkinsfile.sh # 主协调器(请使用此脚本)
│ ├── 自动检测流水线类型
│ ├── 运行语法验证
│ ├── 运行安全扫描
│ ├── 运行最佳实践检查
│ └── 生成统一汇总
│
├── validate_declarative.sh # 声明式语法验证器
│ └── 自动针对pipeline {}块调用
│
├── validate_scripted.sh # 脚本式语法验证器
│ └── 自动针对node {}块调用
│
├── common_validation.sh # 共享函数+安全扫描
│ ├── detect_type: 确定流水线类型
│ ├── check_credentials: 安全凭证扫描
│ └── 通用工具函数
│
├── best_practices.sh # 15项最佳实践评分器
│ └── 性能、安全、可维护性检查
│
└── validate_shared_library.sh # 共享库验证器
└─ 针对vars/*.groovy和src/**/*.groovy文件关键点:始终使用作为主入口 - 它会自动协调所有其他脚本。
validate_jenkinsfile.shIndividual Scripts (Advanced Usage)
单独脚本使用(高级用法)
If you need to run validators separately (for debugging or specific checks):
bash
undefined如果你需要单独运行验证器(用于调试或特定检查):
bash
undefinedDetect pipeline type
检测流水线类型
bash scripts/common_validation.sh detect_type Jenkinsfile
bash scripts/common_validation.sh detect_type Jenkinsfile
Run syntax validation only
仅运行语法验证
bash scripts/validate_declarative.sh Jenkinsfile # For declarative
bash scripts/validate_scripted.sh Jenkinsfile # For scripted
bash scripts/validate_declarative.sh Jenkinsfile # 针对声明式
bash scripts/validate_scripted.sh Jenkinsfile # 针对脚本式
Run security checks only
仅运行安全检查
bash scripts/common_validation.sh check_credentials Jenkinsfile
bash scripts/common_validation.sh check_credentials Jenkinsfile
Run best practices check only
仅运行最佳实践检查
bash scripts/best_practices.sh Jenkinsfile
undefinedbash scripts/best_practices.sh Jenkinsfile
undefinedShared Library Validation
共享库验证
Validate Jenkins Shared Library files using :
validate_shared_library.shbash
undefined使用验证Jenkins共享库文件:
validate_shared_library.shbash
undefinedValidate a single vars file
验证单个vars文件
bash scripts/validate_shared_library.sh vars/myStep.groovy
bash scripts/validate_shared_library.sh vars/myStep.groovy
Validate entire shared library directory
验证整个共享库目录
bash scripts/validate_shared_library.sh /path/to/shared-library
bash scripts/validate_shared_library.sh /path/to/shared-library
Validate just vars directory
仅验证vars目录
bash scripts/validate_shared_library.sh vars/
bash scripts/validate_shared_library.sh vars/
Validate just src directory
仅验证src目录
bash scripts/validate_shared_library.sh src/
The shared library validator checks:
- **vars/*.groovy files**: call() method, @NonCPS usage, CPS compatibility, credential handling
- **src/**/*.groovy files**: Package declaration, class naming, Serializable implementation, imports
Example output:=== Validating Global Variable: myStep ===
File: vars/myStep.groovy
=== Validation Results ===
ERRORS (2):
ERROR [Line 15]: @NonCPS method contains pipeline steps (sh, echo, etc.)
ERROR [Line 15]: → Pipeline steps cannot be used in @NonCPS methods
WARNINGS (3):
WARNING [Line 22]: Using 'new File()' - prefer readFile/writeFile for pipeline compatibility
WARNING [Line 1]: No call() method found - file may not be callable as a step
WARNING [Line 1]: Filename 'BadStep' should be camelCase starting with lowercase
=== Summary ===
✗ Validation failed with 2 error(s) and 3 warning(s)
undefinedbash scripts/validate_shared_library.sh src/
共享库验证器会检查:
- **vars/*.groovy文件**:call()方法、@NonCPS用法、CPS兼容性、凭证处理
- **src/**/*.groovy文件**:包声明、类命名、Serializable实现、导入
示例输出:=== 验证全局变量: myStep ===
文件: vars/myStep.groovy
=== 验证结果 ===
错误 (2):
错误 [第15行]: @NonCPS方法包含流水线步骤(sh、echo等)
错误 [第15行]: → 流水线步骤不能在@NonCPS方法中使用
警告 (3):
警告 [第22行]: 使用了'new File()' - 优先使用readFile/writeFile以保证流水线兼容性
警告 [第1行]: 未找到call()方法 - 该文件可能无法作为步骤调用
警告 [第1行]: 文件名'BadStep'应使用小写开头的小驼峰式命名
=== 汇总 ===
✗ 验证失败,存在2个错误和3个警告
undefinedPlugin Documentation Lookup
插件文档查找
Important: Plugin documentation lookup is Claude's responsibility (not automated in scripts). After running validation, Claude should identify unknown plugins and look them up.
重要提示:插件文档查找是Claude的职责(脚本中未自动化)。运行验证后,Claude应识别未知插件并查找其文档。
When to Look Up Plugin Documentation
何时查找插件文档
Look up documentation when you encounter:
- Steps not in (e.g.,
references/common_plugins.md,customDeploy,sendToDatadog)grafanaNotify - Plugin-specific configuration (e.g., ,
nexusArtifactUploader)sonarQubeScanner - User questions about plugin parameters or best practices
当遇到以下情况时查找文档:
- 步骤不在中(例如
references/common_plugins.md、customDeploy、sendToDatadog)grafanaNotify - 插件专属配置(例如、
nexusArtifactUploader)sonarQubeScanner - 用户询问插件参数或最佳实践相关问题
Plugin Lookup Workflow (Claude's Responsibility)
插件查找流程(Claude职责)
┌─────────────────────────────────────────────────────────────┐
│ 1. Identify Unknown Plugin Step │
│ - Review Jenkinsfile for unrecognized steps │
│ - Example: customDeploy, nexusPublish, datadogEvent │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 2. Check Local Reference First │
│ - Read: references/common_plugins.md │
│ - Contains: git, docker, kubernetes, credentials, etc. │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 3. Use Context7 MCP (if not in local reference) │
│ - mcp__context7__resolve-library-id │
│ query: "jenkinsci <plugin-name>-plugin" │
│ - mcp__context7__get-library-docs │
│ for usage examples and parameters │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 4. Web Search Fallback (if Context7 has no results) │
│ - WebSearch: "Jenkins <plugin-name> plugin documentation"│
│ - Official source: https://plugins.jenkins.io/ │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 5. Provide Usage Guidance │
│ - Required vs optional parameters │
│ - Best practices for the plugin │
│ - Security considerations │
└─────────────────────────────────────────────────────────────┘┌─────────────────────────────────────────────────────────────┐
│ 1. 识别未知插件步骤 │
│ - 检查Jenkinsfile中的未识别步骤 │
│ - 示例:customDeploy、nexusPublish、datadogEvent │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 2. 首先检查本地参考文档 │
│ - 查阅:references/common_plugins.md │
│ - 包含:git、docker、kubernetes、credentials等 │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 3. 若本地参考中没有,使用Context7 MCP │
│ - mcp__context7__resolve-library-id │
│ 查询语句: "jenkinsci <plugin-name>-plugin" │
│ - mcp__context7__get-library-docs │
│ 获取使用示例和参数说明 │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 4. 若Context7无结果,使用网页搜索作为备选 │
│ - 网页搜索: "Jenkins <plugin-name> plugin documentation"│
│ - 官方来源: https://plugins.jenkins.io/ │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 5. 提供使用指导 │
│ - 必填与可选参数 │
│ - 插件最佳实践 │
│ - 安全注意事项 │
└─────────────────────────────────────────────────────────────┘Example: Unknown Plugin Detection
示例:未知插件检测
groovy
// User's Jenkinsfile contains:
stage('Deploy') {
steps {
nexusArtifactUploader artifacts: [[...]], nexusUrl: 'http://nexus'
datadogEvent title: 'Deployment', text: 'Deployed v1.0'
}
}Claude's Actions:
- Recognize and
nexusArtifactUploaderare not in common_plugins.mddatadogEvent - Use Context7: with "jenkinsci nexus-artifact-uploader"
mcp__context7__resolve-library-id - If not found, WebSearch: "Jenkins nexus artifact uploader plugin documentation"
- Provide guidance: "The nexusArtifactUploader step requires credentialsId for authentication..."
groovy
// 用户的Jenkinsfile包含:
stage('Deploy') {
steps {
nexusArtifactUploader artifacts: [[...]], nexusUrl: 'http://nexus'
datadogEvent title: 'Deployment', text: 'Deployed v1.0'
}
}Claude的操作:
- 识别和
nexusArtifactUploader不在common_plugins.md中datadogEvent - 使用Context7:,查询语句为"jenkinsci nexus-artifact-uploader"
mcp__context7__resolve-library-id - 若未找到,网页搜索"Jenkins nexus artifact uploader plugin documentation"
- 提供指导:"nexusArtifactUploader步骤需要credentialsId用于身份验证..."
Reference Documentation
参考文档
The skill includes comprehensive reference documentation:
- declarative_syntax.md: Complete Declarative pipeline syntax reference
- scripted_syntax.md: Scripted pipeline and Groovy patterns
- best_practices.md: Comprehensive best practices guide from official Jenkins docs
- common_plugins.md: Documentation for popular plugins (git, docker, kubernetes, credentials, etc.)
本技能包含全面的参考文档:
- declarative_syntax.md:完整的声明式流水线语法参考
- scripted_syntax.md:脚本式流水线和Groovy模式
- best_practices.md:来自Jenkins官方文档的综合最佳实践指南
- common_plugins.md:热门插件文档(git、docker、kubernetes、credentials等)
Validation Rules
验证规则
Syntax Issues
语法问题
- Missing required sections (agent, stages, steps)
- Invalid section names or misplaced directives
- Groovy syntax errors
- Missing braces, quotes, or brackets
- Semicolons at end of lines (unnecessary in Jenkins pipelines)
- 缺少必填章节(agent、stages、steps)
- 无效章节名称或指令位置错误
- Groovy语法错误
- 缺少大括号、引号或方括号
- 行尾存在分号(Jenkins流水线中不必要)
Best Practices
最佳实践
- Combine Shell Commands: Use single step with multiple commands instead of multiple
shstepssh - Credential Management: Use or
credentials(), never hardcode secretswithCredentials - Agent Operations: Perform heavy operations on agents, not controller
- Parallel Execution: Use for independent stages
parallel - Error Handling: Wrap critical sections in try-catch blocks
- Timeouts: Define timeouts in options to prevent hung builds
- Clean Workspace: Clean workspace before/after builds
- 合并Shell命令:使用单个步骤执行多个命令,而非多个
sh步骤sh - 凭证管理:使用或
credentials(),绝不硬编码密钥withCredentials - Agent操作:在agent上执行密集型操作,而非控制器
- 并行执行:对独立阶段使用
parallel - 错误处理:将关键部分包裹在try-catch块中
- 超时设置:在options中定义超时,防止构建挂起
- 工作区清理:构建前后清理工作区
Variable Usage
变量使用
- Proper variable declaration and scoping
- Correct interpolation syntax (vs
${VAR})$VAR - Undefined variable detection
- Environment variable usage
- 正确的变量声明和作用域
- 正确的插值语法(vs
${VAR})$VAR - 未定义变量检测
- 环境变量使用
Security
安全
- No hardcoded passwords, API keys, or tokens
- Proper use of Jenkins Credentials Manager
- Secrets management best practices
- Role-based access control recommendations
- 无硬编码密码、API密钥或令牌
- 正确使用Jenkins凭证管理器
- 密钥管理最佳实践
- 基于角色的访问控制建议
Error Reporting
错误报告
Validation results include:
- Line numbers for each issue
- Severity levels: Error, Warning, Info
- Descriptions: Clear explanation of the issue
- Suggestions: How to fix the problem
- References: Links to documentation
验证结果包含:
- 每个问题的行号
- 严重级别:错误、警告、信息
- 描述:问题的清晰说明
- 建议:修复问题的方法
- 参考:文档链接
Example Output
示例输出
ERROR [Line 5]: Missing required section 'agent'
→ Add 'agent any' or specific agent configuration at top level
WARNING [Line 12]: Multiple consecutive 'sh' steps detected
→ Combine into single sh step with triple-quoted string
→ See: best_practices.md#combine-shell-commands
INFO [Line 23]: Consider using parallel execution for independent stages
→ See: references/declarative_syntax.md#parallel-stages错误 [第5行]: 缺少必填章节'agent'
→ 在顶层添加'agent any'或特定的agent配置
警告 [第12行]: 检测到多个连续的'sh'步骤
→ 将其合并为单个使用三引号字符串的sh步骤
→ 参考: best_practices.md#combine-shell-commands
信息 [第23行]: 考虑对独立阶段使用并行执行
→ 参考: references/declarative_syntax.md#parallel-stagesUsage Instructions
使用说明
When a user provides a Jenkinsfile for validation:
-
Run the main validation script (recommended - handles everything automatically):bash
bash scripts/validate_jenkinsfile.sh <path-to-jenkinsfile>This single command auto-detects pipeline type, runs syntax validation, security scan, and best practices check. -
Optionally read the Jenkinsfile using the Read tool if you need to:
- Understand the pipeline structure before validation
- Provide context-specific advice
- Identify specific plugins being used
-
After validation, scan for unknown plugins (Claude's responsibility):
- Review the validation output for any unrecognized step names
- Check first for documentation
references/common_plugins.md - If not found, use Context7 MCP: with query "jenkinsci <plugin-name>"
mcp__context7__resolve-library-id - If still not found, use WebSearch: "Jenkins <plugin-name> plugin documentation"
- Provide usage guidance based on found documentation
-
Report results with line numbers, severity, and actionable suggestions
-
Provide inline fix suggestions when errors are found (do not use AskUserQuestion - include corrected code snippets directly in the response)
当用户提供Jenkinsfile进行验证时:
-
运行主验证脚本(推荐 - 自动处理所有事项):bash
bash scripts/validate_jenkinsfile.sh <jenkinsfile路径>该单一命令会自动检测流水线类型,运行语法验证、安全扫描和最佳实践检查. -
可选操作:读取Jenkinsfile 若你需要:
- 在验证前理解流水线结构
- 提供特定上下文的建议
- 识别正在使用特定插件
使用Read工具读取Jenkinsfile内容 -
验证后,扫描未知插件(Claude职责):
- 检查验证输出中的所有未识别步骤名称
- 首先查阅获取文档
references/common_plugins.md - 如果未找到,则使用Context7 MCP: ,查询语句为"jenkinsci <插件名称>"
mcp__context7__resolve-library-id - 如果仍未找到,则使用网页搜索: "Jenkins <插件名称> plugin documentation"
- 根据找到的文档提供使用指导
-
报告结果,包含行号、严重级别和可操作的建议
-
当发现错误时,提供内联修复建议(不要使用AskUserQuestion - 直接在响应中包含修正后的代码片段)
Common Validation Scenarios
常见验证场景
Scenario 1: Validate Declarative Pipeline
场景1:验证声明式流水线
markdown
User: "Validate my Jenkinsfile"
1. Read the Jenkinsfile
2. Detect type: Declarative (starts with 'pipeline {')
3. Run: bash scripts/validate_declarative.sh Jenkinsfile
4. Run: bash scripts/best_practices.sh Jenkinsfile
5. Report results with suggestionsmarkdown
用户: "验证我的Jenkinsfile"
1. 读取Jenkinsfile
2. 检测类型: 声明式(以'pipeline {'开头)
3. 运行: bash scripts/validate_declarative.sh Jenkinsfile
4. 运行: bash scripts/best_practices.sh Jenkinsfile
5. 报告结果并给出建议Scenario 2: Validate with Unknown Plugin
场景2:验证包含未知插件的流水线
markdown
User: "Check this pipeline with custom plugin steps"
1. Read Jenkinsfile
2. Run validation
3. Detect unknown step (e.g., 'customDeploy')
4. Search context7 for plugin docs
5. If not found, web search "Jenkins custom deploy plugin"
6. Validate plugin usage against found documentation
7. Report resultsmarkdown
用户: "检查这个包含自定义插件步骤的流水线"
1. 读取Jenkinsfile
2. 运行验证
3. 检测未知步骤(例如'customDeploy')
4. 在context7中搜索插件文档
5. 若未找到,网页搜索"Jenkins custom deploy plugin"
6. 根据找到的文档验证插件使用方式
7. 报告结果Scenario 3: Security Audit
场景3:安全审计
markdown
User: "Check for security issues in my pipeline"
1. Read Jenkinsfile
2. Run: bash scripts/common_validation.sh check_credentials Jenkinsfile
3. Scan for hardcoded secrets, passwords, API keys
4. Check credential management best practices
5. Report security findings with fix suggestionsmarkdown
用户: "检查我的流水线中的安全问题"
1. 读取Jenkinsfile
2. 运行: bash scripts/common_validation.sh check_credentials Jenkinsfile
3. 扫描硬编码密钥、密码、API密钥
4. 检查凭证管理最佳实践
5. 报告安全发现并给出修复建议Tools Available
可用工具
- Bash: Execute validation scripts
- Read: Read Jenkinsfile content
- Grep: Search for patterns in pipeline files
- WebSearch: Find plugin documentation online
- Context7 MCP: Access Jenkins and plugin documentation
- WebFetch: Retrieve specific documentation pages
- Bash:执行验证脚本
- Read:读取Jenkinsfile内容
- Grep:在流水线文件中搜索模式
- WebSearch:在线查找插件文档
- Context7 MCP:访问Jenkins和插件文档
- WebFetch:获取特定文档页面
Best Practice Examples
最佳实践示例
Good: Combined Shell Commands
良好实践:合并Shell命令
groovy
sh '''
echo "Building..."
mkdir build
./gradlew build
echo "Build complete"
'''groovy
sh '''
echo "构建中..."
mkdir build
./gradlew build
echo "构建完成"
'''Bad: Multiple Shell Steps
不良实践:多个Shell步骤
groovy
sh 'echo "Building..."'
sh 'mkdir build'
sh './gradlew build'
sh 'echo "Build complete"'groovy
sh 'echo "构建中..."'
sh 'mkdir build'
sh './gradlew build'
sh 'echo "构建完成"'Good: Credential Management
良好实践:凭证管理
groovy
withCredentials([string(credentialsId: 'api-key', variable: 'API_KEY')]) {
sh 'curl -H "Authorization: Bearer $API_KEY" ...'
}groovy
withCredentials([string(credentialsId: 'api-key', variable: 'API_KEY')]) {
sh 'curl -H "Authorization: Bearer $API_KEY" ...'
}Bad: Hardcoded Credentials
不良实践:硬编码凭证
groovy
sh 'curl -H "Authorization: Bearer abc123xyz" ...'groovy
sh 'curl -H "Authorization: Bearer abc123xyz" ...'Additional Capabilities
附加功能
- Dry-run Testing: Validate without Jenkins server (all validation is local)
- Plugin Version Checking: Warn about deprecated plugin versions
- Performance Analysis: Identify potential performance bottlenecks
- Compliance Checking: Validate against organizational standards
- Multi-file Support: Validate multiple Jenkinsfiles in a directory
- 试运行测试:无需Jenkins服务器即可验证(所有验证均为本地操作)
- 插件版本检查:警告已弃用的插件版本
- 性能分析:识别潜在的性能瓶颈
- 合规性检查:验证是否符合组织标准
- 多文件支持:验证目录中的多个Jenkinsfile
References
参考链接
- Official Jenkins Pipeline Syntax: https://www.jenkins.io/doc/book/pipeline/syntax/
- Pipeline Development Tools: https://www.jenkins.io/doc/book/pipeline/development/
- Pipeline Best Practices: https://www.jenkins.io/doc/book/pipeline/pipeline-best-practices/
- Jenkins Plugins: https://plugins.jenkins.io/
Automatic Actions
自动操作
When this skill is invoked:
- Always validate syntax first (errors block execution)
- Then check best practices (warnings for improvement)
- Look up unknown plugins automatically
- Provide actionable suggestions with every issue
- Reference documentation files for detailed guidance
当调用此技能时:
- 始终先验证语法(错误会阻止执行)
- 然后检查最佳实践(给出改进警告)
- 自动查找未知插件
- 为每个问题提供可操作的建议
- 参考文档文件提供详细指导
Troubleshooting
故障排除
Common Issues
常见问题
Issue: "Best practices check shows false negatives"
- Cause: Comment stripping may interfere with pattern detection
- Solution: update to latest version
Issue: "Syntax validation passes but pipeline fails on Jenkins"
- Explanation: Local validation catches structural issues but cannot verify:
- Plugin availability
- Agent/node availability
- Credential existence
- Network connectivity
- Solution: Validate on Jenkins using Replay feature or Pipeline Unit Testing Framework
Issue: "Security scan shows passed but best practices finds credentials"
- Solution: security scan now properly detects all credential patterns
Issue: "Scripts not executable"
- Solution: Run
chmod +x scripts/*.sh
问题:"最佳实践检查出现假阴性"
- 原因:注释剥离可能会干扰模式检测
- 解决方案:更新到最新版本
问题:"语法验证通过,但流水线在Jenkins上执行失败"
- 说明:本地验证可发现结构问题,但无法验证:
- 插件可用性
- Agent/节点可用性
- 凭证存在性
- 网络连接
- 解决方案:在Jenkins上使用Replay功能或Pipeline Unit Testing Framework进行验证
问题:"安全扫描显示通过,但最佳实践发现了凭证"
- 解决方案:安全扫描现在可正确检测所有凭证模式
问题:"脚本不可执行"
- 解决方案:运行
chmod +x scripts/*.sh
Debug Mode
调试模式
Enable verbose output for troubleshooting:
bash
undefined启用详细输出以进行故障排除:
bash
undefinedRun with bash debug mode
使用bash调试模式运行
bash -x scripts/validate_jenkinsfile.sh Jenkinsfile
bash -x scripts/validate_jenkinsfile.sh Jenkinsfile
Check individual validator output
检查单个验证器的输出
bash scripts/validate_declarative.sh Jenkinsfile
bash scripts/best_practices.sh Jenkinsfile
bash scripts/common_validation.sh check_credentials Jenkinsfile
undefinedbash scripts/validate_declarative.sh Jenkinsfile
bash scripts/best_practices.sh Jenkinsfile
bash scripts/common_validation.sh check_credentials Jenkinsfile
undefinedLimitations
局限性
- No Jenkins Server Required: All validation is local (no live testing)
- Plugin Steps: Cannot fully validate custom plugin steps without documentation
- Runtime Behavior: Cannot detect runtime issues (permissions, network, etc.)
- Complex Groovy: Advanced Groovy constructs may not be fully validated
- Shared Libraries: Remote shared libraries are not fetched or validated
- 无需Jenkins服务器:所有验证均为本地操作(无实时测试)
- 插件步骤:若无文档,无法完全验证自定义插件步骤
- 运行时行为:无法检测运行时问题(权限、网络等)
- 复杂Groovy:高级Groovy结构可能无法完全验证
- 共享库:不会获取或验证远程共享库