ansible-validator
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAnsible Validator
Ansible Validator
Overview
概述
Comprehensive toolkit for validating, linting, and testing Ansible playbooks, roles, and collections. This skill provides automated workflows for ensuring Ansible code quality, syntax validation, dry-run testing with check mode and molecule, and intelligent documentation lookup for custom modules and collections with version awareness.
IMPORTANT BEHAVIOR: When validating any Ansible role, this skill AUTOMATICALLY runs molecule tests if a directory is detected in the role. This is non-negotiable and happens without asking for user permission. If molecule tests cannot run due to environmental issues (Docker, version compatibility), the skill documents the blocker but continues with other validation steps.
molecule/用于验证、Lint检查和测试Ansible剧本、角色及集合的综合工具包。本技能提供自动化工作流,用于保障Ansible代码质量、语法验证、结合check模式与Molecule的试运行测试,以及针对自定义模块和集合的带版本感知的智能文档查询。
重要行为说明: 验证任何Ansible角色时,若在角色中检测到目录,本技能将自动运行Molecule测试,无需征求用户许可。若因环境问题(Docker、版本兼容性)导致Molecule测试无法运行,技能会记录该障碍,但继续执行其他验证步骤。
molecule/When to Use This Skill
适用场景
Apply this skill when encountering any of these scenarios:
- Working with Ansible files (,
.ymlplaybooks, roles, inventories, vars).yaml - Validating Ansible playbook syntax and structure
- Linting and formatting Ansible code
- Performing dry-run testing with
ansible-playbook --check - Testing roles and playbooks with Molecule
- Debugging Ansible errors or misconfigurations
- Understanding custom Ansible modules, collections, or roles
- Ensuring infrastructure-as-code best practices
- Security validation of Ansible playbooks
- Version compatibility checks for collections and modules
在遇到以下场景时使用本技能:
- 处理Ansible文件(、
.yml剧本、角色、清单、变量文件).yaml - 验证Ansible剧本的语法与结构
- 对Ansible代码进行Lint检查与格式化
- 使用执行试运行测试
ansible-playbook --check - 使用Molecule测试角色与剧本
- 调试Ansible错误或配置问题
- 了解自定义Ansible模块、集合或角色
- 确保基础设施即代码(IaC)的最佳实践
- 对Ansible剧本进行安全验证
- 检查集合与模块的版本兼容性
Validation Workflow
验证工作流
Follow this decision tree for comprehensive Ansible validation:
0. Tool Prerequisites Check (RECOMMENDED for first-time validation)
├─> Run bash scripts/setup_tools.sh for diagnostics
├─> Verify required tools are available
├─> Get installation instructions if tools are missing
└─> NOTE: Validation scripts auto-install tools in temp venv if missing,
but running setup_tools.sh first helps identify system issues early
1. Identify Ansible files in scope
├─> Single playbook validation
├─> Role validation
├─> Collection validation
└─> Multi-playbook/inventory validation
2. Syntax Validation
├─> Run ansible-playbook --syntax-check
├─> Run yamllint for YAML syntax
└─> Report syntax errors
3. Lint and Best Practices
├─> Run ansible-lint (comprehensive linting)
├─> Check for deprecated modules (see references/module_alternatives.md)
├─> **DETECT NON-FQCN MODULE USAGE** (apt vs ansible.builtin.apt)
│ └─> Run bash scripts/check_fqcn.sh to identify short module names
│ └─> Recommend FQCN alternatives from references/module_alternatives.md
├─> Verify role structure
└─> Report linting issues
4. Dry-Run Testing (check mode)
├─> Run ansible-playbook --check (if inventory available)
├─> Analyze what would change
└─> Report potential issues
5. Molecule Testing (for roles) - AUTOMATIC
├─> Check if molecule/ directory exists in role
├─> If present, ALWAYS run molecule test automatically
├─> Test against multiple scenarios
├─> Report test results (pass/fail/blocked)
└─> Report any environmental issues if tests cannot run
6. Custom Module/Collection Analysis (if detected)
├─> Extract module/collection information
├─> Identify versions
├─> Lookup documentation (WebSearch or Context7)
└─> Provide version-specific guidance
7. Security and Best Practices Review - DUAL SCANNING REQUIRED
├─> Run bash scripts/validate_playbook_security.sh or validate_role_security.sh (Checkov)
├─> **ALSO run bash scripts/scan_secrets.sh** for hardcoded secret detection
│ └─> This catches secrets Checkov may miss (passwords, API keys, tokens)
├─> Validate privilege escalation
├─> Review file permissions
└─> Identify common anti-patterns
8. Reference Documentation - MANDATORY CONSULTATION
├─> **MUST READ** references/common_errors.md when ANY errors are detected
│ └─> Extract specific remediation steps for the error type
│ └─> Include relevant guidance in validation report
├─> **MUST READ** references/best_practices.md when warnings are detected
│ └─> Cite specific best practice recommendations
├─> **MUST READ** references/module_alternatives.md when:
│ └─> Deprecated modules are detected
│ └─> Non-FQCN module names are used (apt, service, etc.)
│ └─> Provide specific FQCN migration recommendations
└─> **MUST READ** references/security_checklist.md when security issues found
└─> Include specific remediation guidance from checklistCRITICAL: Reference files are NOT optional. When issues are detected, the corresponding reference file MUST be read and its guidance applied to provide actionable remediation steps to the user. Simply mentioning the reference file path is insufficient - the content must be consulted and relevant guidance extracted.
遵循以下决策树完成全面的Ansible验证:
0. 工具前置检查(首次验证推荐执行)
├─> 运行bash scripts/setup_tools.sh进行诊断
├─> 验证所需工具是否可用
├─> 若工具缺失,获取安装说明
└─> 注意:若工具缺失,验证脚本会在临时虚拟环境中自动安装,但提前运行setup_tools.sh有助于尽早发现系统问题
1. 确定范围内的Ansible文件
├─> 单个剧本验证
├─> 角色验证
├─> 集合验证
└─> 多剧本/清单验证
2. 语法验证
├─> 运行ansible-playbook --syntax-check
├─> 运行yamllint检查YAML语法
└─> 报告语法错误
3. Lint检查与最佳实践
├─> 运行ansible-lint(全面Lint检查)
├─> 检查已弃用的模块(参考references/module_alternatives.md)
├─> **检测非FQCN模块使用**(如apt vs ansible.builtin.apt)
│ └─> 运行bash scripts/check_fqcn.sh识别短模块名
│ └─> 参考references/module_alternatives.md推荐FQCN替代方案
├─> 验证角色结构
└─> 报告Lint检查问题
4. 试运行测试(check模式)
├─> 若清单可用,运行ansible-playbook --check
├─> 分析将会产生的变更
└─> 报告潜在问题
5. Molecule测试(针对角色)- 自动执行
├─> 检查角色中是否存在molecule/目录
├─> 若存在,始终自动运行molecule test
├─> 在多个场景下进行测试
├─> 报告测试结果(通过/失败/受阻)
└─> 若测试无法运行,报告相关环境问题
6. 自定义模块/集合分析(若检测到)
├─> 提取模块/集合信息
├─> 识别版本
├─> 查询文档(WebSearch或Context7)
└─> 提供版本特定的指导
7. 安全与最佳实践审查 - 需双重扫描
├─> 运行bash scripts/validate_playbook_security.sh或validate_role_security.sh(基于Checkov)
├─> **同时运行bash scripts/scan_secrets.sh**检测硬编码密钥
│ └─> 此脚本可捕获Checkov可能遗漏的密钥(密码、API密钥、令牌等)
├─> 验证权限提升配置
├─> 审查文件权限
└─> 识别常见反模式
8. 参考文档 - 必须查阅
├─> 当检测到任何错误时,**必须阅读**references/common_errors.md
│ └─> 提取针对该错误类型的具体修复步骤
│ └─> 在验证报告中包含相关指导
├─> 当检测到警告时,**必须阅读**references/best_practices.md
│ └─> 引用具体的最佳实践建议
├─> 在以下情况时**必须阅读**references/module_alternatives.md:
│ └─> 检测到已弃用的模块
│ └─> 使用了非FQCN模块名(如apt、service等)
│ └─> 提供具体的FQCN迁移建议
└─> 当发现安全问题时,**必须阅读**references/security_checklist.md
└─> 包含清单中的具体修复指导关键提示:参考文件为必填项。当检测到问题时,必须阅读对应的参考文件并应用其指导,为用户提供可执行的修复步骤。仅提及参考文件路径是不够的,必须查阅内容并提取相关指导。
Core Capabilities
核心功能
1. YAML Syntax Validation
1. YAML语法验证
Purpose: Ensure YAML files are syntactically correct before Ansible parsing.
Tools:
- - YAML linter for syntax and formatting
yamllint - - Ansible-specific syntax validation
ansible-playbook --syntax-check
Workflow:
bash
undefined目的: 在Ansible解析前确保YAML文件语法正确。
工具:
- - 用于语法和格式化的YAML Lint工具
yamllint - - Ansible专属语法验证工具
ansible-playbook --syntax-check
工作流:
bash
undefinedCheck YAML syntax with yamllint
使用yamllint检查YAML语法
yamllint playbook.yml
yamllint playbook.yml
Or for entire directory
或检查整个目录
yamllint -c .yamllint .
yamllint -c .yamllint .
Check Ansible playbook syntax
检查Ansible剧本语法
ansible-playbook playbook.yml --syntax-check
**Common Issues Detected:**
- Indentation errors
- Invalid YAML syntax
- Duplicate keys
- Trailing whitespace
- Line length violations
- Missing colons or quotes
**Best Practices:**
- Always run yamllint before ansible-lint
- Use 2-space indentation consistently
- Configure yamllint rules in `.yamllint`
- Fix YAML syntax errors first, then Ansible-specific issuesansible-playbook playbook.yml --syntax-check
**常见检测问题:**
- 缩进错误
- 无效YAML语法
- 重复键
- 尾随空格
- 行长度违规
- 缺少冒号或引号
**最佳实践:**
- 始终在ansible-lint之前运行yamllint
- 统一使用2空格缩进
- 在`.yamllint`中配置yamllint规则
- 先修复YAML语法错误,再处理Ansible专属问题2. Ansible Lint
2. Ansible Lint
Purpose: Enforce Ansible best practices and catch common errors.
Workflow:
bash
undefined目的: 强制执行Ansible最佳实践并捕获常见错误。
工作流:
bash
undefinedLint a single playbook
Lint单个剧本
ansible-lint playbook.yml
ansible-lint playbook.yml
Lint all playbooks in directory
Lint目录下所有剧本
ansible-lint .
ansible-lint .
Lint with specific rules
使用特定规则进行Lint检查
ansible-lint -t yaml,syntax playbook.yml
ansible-lint -t yaml,syntax playbook.yml
Skip specific rules
跳过特定规则
ansible-lint -x yaml[line-length] playbook.yml
ansible-lint -x yaml[line-length] playbook.yml
Output parseable format
输出可解析格式
ansible-lint -f pep8 playbook.yml
ansible-lint -f pep8 playbook.yml
Show rule details
显示规则详情
ansible-lint -L
**Common Issues Detected:**
- Deprecated modules or syntax
- Missing task names
- Improper use of `command` vs `shell`
- Unquoted template expressions
- Hard-coded values that should be variables
- Missing `become` directives
- Inefficient task patterns
- Jinja2 template errors
- Incorrect variable usage
- Role dependencies issues
**Severity Levels:**
- **Error:** Must fix - will cause failures
- **Warning:** Should fix - potential issues
- **Info:** Consider fixing - best practice violations
**Auto-fix approach:**
- ansible-lint supports `--fix` for auto-fixable issues
- Always review changes before applying
- Some issues require manual interventionansible-lint -L
**常见检测问题:**
- 已弃用的模块或语法
- 缺少任务名称
- 不当使用`command`与`shell`模块
- 未加引号的模板表达式
- 应使用变量的硬编码值
- 缺少`become`指令
- 低效的任务模式
- Jinja2模板错误
- 变量使用错误
- 角色依赖问题
**严重级别:**
- **错误:** 必须修复 - 会导致执行失败
- **警告:** 建议修复 - 存在潜在问题
- **信息:** 考虑修复 - 违反最佳实践
**自动修复方式:**
- ansible-lint支持`--fix`参数修复可自动修复的问题
- 应用前务必审查变更
- 部分问题需要手动干预3. Security Scanning (Checkov)
3. 安全扫描(Checkov)
Purpose: Identify security vulnerabilities and compliance violations in Ansible code using Checkov, a static code analysis tool for infrastructure-as-code.
What Checkov Provides Beyond ansible-lint:
While ansible-lint focuses on code quality and best practices, Checkov specifically targets security policies and compliance:
- SSL/TLS Security: Certificate validation enforcement
- HTTPS Enforcement: Ensures secure protocols for downloads
- Package Security: GPG signature verification for packages
- Cloud Security: AWS, Azure, GCP misconfiguration detection
- Compliance Frameworks: Maps to security standards
- Network Security: Firewall and network policy validation
Workflow:
bash
undefined目的: 使用Checkov(基础设施即代码静态代码分析工具)识别Ansible代码中的安全漏洞与合规性违规。
Checkov相较于ansible-lint的额外能力:
ansible-lint聚焦于代码质量与最佳实践,而Checkov专门针对安全策略与合规性:
- SSL/TLS安全: 证书验证强制检查
- HTTPS强制: 确保下载使用安全协议
- 包安全: 包的GPG签名验证
- 云安全: AWS、Azure、GCP配置错误检测
- 合规框架: 映射至安全标准
- 网络安全: 防火墙与网络策略验证
工作流:
bash
undefinedScan playbook for security issues
扫描剧本中的安全问题
bash scripts/validate_playbook_security.sh playbook.yml
bash scripts/validate_playbook_security.sh playbook.yml
Scan entire directory
扫描整个目录
bash scripts/validate_playbook_security.sh /path/to/playbooks/
bash scripts/validate_playbook_security.sh /path/to/playbooks/
Scan role for security issues
扫描角色中的安全问题
bash scripts/validate_role_security.sh roles/webserver/
bash scripts/validate_role_security.sh roles/webserver/
Direct checkov usage
直接使用checkov
checkov -d . --framework ansible
checkov -d . --framework ansible
Scan with specific output format
使用特定格式输出扫描结果
checkov -d . --framework ansible --output json
checkov -d . --framework ansible --output json
Scan and skip specific checks
扫描并跳过特定检查项
checkov -d . --framework ansible --skip-check CKV_ANSIBLE_1
**Common Security Issues Detected:**
**Certificate Validation:**
- **CKV_ANSIBLE_1:** URI module disabling certificate validation
- **CKV_ANSIBLE_2:** get_url disabling certificate validation
- **CKV_ANSIBLE_3:** yum disabling certificate validation
- **CKV_ANSIBLE_4:** yum disabling SSL verification
**HTTPS Enforcement:**
- **CKV2_ANSIBLE_1:** URI module using HTTP instead of HTTPS
- **CKV2_ANSIBLE_2:** get_url using HTTP instead of HTTPS
**Package Security:**
- **CKV_ANSIBLE_5:** apt installing packages without GPG signature
- **CKV_ANSIBLE_6:** apt using force parameter bypassing signatures
- *
- *CKV2_ANSIBLE_4:** dnf installing packages without GPG signature
- **CKV2_ANSIBLE_5:** dnf disabling SSL verification
- **CKV2_ANSIBLE_6:** dnf disabling certificate validation
**Error Handling:**
- **CKV2_ANSIBLE_3:** Block missing error handling
**Cloud Security (when managing cloud resources):**
- **CKV_AWS_88:** EC2 instances with public IPs
- **CKV_AWS_135:** EC2 instances without EBS optimization
**Example Violation:**
```yamlcheckov -d . --framework ansible --skip-check CKV_ANSIBLE_1
**常见检测到的安全问题:**
**证书验证:**
- **CKV_ANSIBLE_1:** URI模块禁用证书验证
- **CKV_ANSIBLE_2:** get_url禁用证书验证
- **CKV_ANSIBLE_3:** yum禁用证书验证
- **CKV_ANSIBLE_4:** yum禁用SSL验证
**HTTPS强制:**
- **CKV2_ANSIBLE_1:** URI模块使用HTTP而非HTTPS
- **CKV2_ANSIBLE_2:** get_url使用HTTP而非HTTPS
**包安全:**
- **CKV_ANSIBLE_5:** apt安装包时未验证GPG签名
- **CKV_ANSIBLE_6:** apt使用force参数绕过签名验证
- **CKV2_ANSIBLE_4:** dnf安装包时未验证GPG签名
- **CKV2_ANSIBLE_5:** dnf禁用SSL验证
- **CKV2_ANSIBLE_6:** dnf禁用证书验证
**错误处理:**
- **CKV2_ANSIBLE_3:** Block缺失错误处理
**云安全(当管理云资源时):**
- **CKV_AWS_88:** EC2实例配置了公网IP
- **CKV_AWS_135:** EC2实例未启用EBS优化
**违规示例:**
```yamlBAD - Disables certificate validation
错误示例 - 禁用证书验证
- name: Download file get_url: url: https://example.com/file.tar.gz dest: /tmp/file.tar.gz validate_certs: false # Security issue!
- name: 下载文件 get_url: url: https://example.com/file.tar.gz dest: /tmp/file.tar.gz validate_certs: false # 安全问题!
GOOD - Certificate validation enabled
正确示例 - 启用证书验证
- name: Download file get_url: url: https://example.com/file.tar.gz dest: /tmp/file.tar.gz validate_certs: true # Or omit (true by default)
**Integration with Validation Workflow:**
Checkov complements ansible-lint:
1. **ansible-lint** catches code quality issues, deprecated modules, best practices
2. **Checkov** catches security vulnerabilities, compliance violations, cryptographic issues
**Best Practice:** Run both tools for comprehensive validation:
```bash- name: 下载文件 get_url: url: https://example.com/file.tar.gz dest: /tmp/file.tar.gz validate_certs: true # 或省略(默认值为true)
**与验证工作流的集成:**
Checkov与ansible-lint互补:
1. **ansible-lint** 捕获代码质量问题、已弃用模块、最佳实践违规
2. **Checkov** 捕获安全漏洞、合规性违规、加密相关问题
**最佳实践:** 同时运行两个工具以实现全面验证:
```bashComplete validation workflow
完整验证工作流
bash scripts/validate_playbook.sh playbook.yml # Syntax + Lint
bash scripts/validate_playbook_security.sh playbook.yml # Security
**Output Format:**
Checkov provides clear security scan results:Security Scan Results:
Passed: 15 checks
Failed: 2 checks
Skipped: 0 checks
Failed Checks:
Check: CKV_ANSIBLE_2 - "Ensure that certificate validation isn't disabled with get_url"
FAILED for resource: tasks/main.yml:download_file
File: /roles/webserver/tasks/main.yml:10-15
**Remediation Resources:**
- Checkov Policy Index: https://www.checkov.io/5.Policy%20Index/ansible.html
- Ansible Security Checklist: `references/security_checklist.md`
- Ansible Best Practices: `references/best_practices.md`
**Installation:**
Checkov is automatically installed in a temporary environment if not available system-wide. For permanent installation:
```bash
pip3 install checkovWhen to Use:
- Before deploying to production
- In CI/CD pipelines for automated security checks
- When working with sensitive infrastructure
- For compliance audits and security reviews
- When downloading files or installing packages
- When managing cloud resources with Ansible
bash scripts/validate_playbook.sh playbook.yml # 语法 + Lint检查
bash scripts/validate_playbook_security.sh playbook.yml # 安全扫描
**输出格式:**
Checkov提供清晰的安全扫描结果:安全扫描结果:
通过: 15项检查
失败: 2项检查
跳过: 0项检查
失败的检查项:
检查项:CKV_ANSIBLE_2 - "确保get_url未禁用证书验证"
违规资源:tasks/main.yml:download_file
文件:/roles/webserver/tasks/main.yml:10-15
**修复资源:**
- Checkov策略索引:https://www.checkov.io/5.Policy%20Index/ansible.html
- Ansible安全清单:`references/security_checklist.md`
- Ansible最佳实践:`references/best_practices.md`
**安装:**
若系统中未安装Checkov,会自动在临时环境中安装。如需永久安装:
```bash
pip3 install checkov适用场景:
- 部署至生产环境前
- 在CI/CD流水线中进行自动安全检查
- 处理敏感基础设施时
- 合规审计与安全审查
- 下载文件或安装包时
- 使用Ansible管理云资源时
4. Playbook Syntax Check
4. 剧本语法检查
Purpose: Validate playbook syntax without executing tasks.
Workflow:
bash
undefined目的: 在不执行任务的情况下验证剧本语法。
工作流:
bash
undefinedBasic syntax check
基础语法检查
ansible-playbook playbook.yml --syntax-check
ansible-playbook playbook.yml --syntax-check
Syntax check with inventory
结合清单进行语法检查
ansible-playbook -i inventory playbook.yml --syntax-check
ansible-playbook -i inventory playbook.yml --syntax-check
Syntax check with extra vars
结合额外变量进行语法检查
ansible-playbook playbook.yml --syntax-check -e @vars.yml
ansible-playbook playbook.yml --syntax-check -e @vars.yml
Check all playbooks
检查所有剧本
for file in *.yml; do
ansible-playbook "$file" --syntax-check
done
**Validation Checks:**
- YAML parsing
- Playbook structure
- Task definitions
- Variable references
- Module parameter syntax
- Jinja2 template syntax
- Include/import statements
**Error Handling:**
- Parse error messages for specific issues
- Check for typos in module names
- Verify variable definitions
- Ensure proper indentation
- Check file paths for includes/importsfor file in *.yml; do
ansible-playbook "$file" --syntax-check
done
**验证检查项:**
- YAML解析
- 剧本结构
- 任务定义
- 变量引用
- 模块参数语法
- Jinja2模板语法
- Include/Import语句
**错误处理:**
- 解析错误消息以定位具体问题
- 检查模块名称拼写错误
- 验证变量定义
- 确保缩进正确
- 检查Include/Import的文件路径5. Dry-Run Testing (Check Mode)
5. 试运行测试(Check模式)
Purpose: Preview changes that would be made without actually applying them.
Workflow:
bash
undefined目的: 预览将会执行的变更,而不实际应用这些变更。
工作流:
bash
undefinedRun in check mode (dry-run)
以check模式运行(试运行)
ansible-playbook -i inventory playbook.yml --check
ansible-playbook -i inventory playbook.yml --check
Check mode with diff
结合diff输出的check模式
ansible-playbook -i inventory playbook.yml --check --diff
ansible-playbook -i inventory playbook.yml --check --diff
Check mode with verbose output
带详细输出的check模式
ansible-playbook -i inventory playbook.yml --check -v
ansible-playbook -i inventory playbook.yml --check -v
Check mode for specific hosts
针对特定主机的check模式
ansible-playbook -i inventory playbook.yml --check --limit webservers
ansible-playbook -i inventory playbook.yml --check --limit webservers
Check mode with tags
带标签的check模式
ansible-playbook -i inventory playbook.yml --check --tags deploy
ansible-playbook -i inventory playbook.yml --check --tags deploy
Step through tasks
逐步执行任务
ansible-playbook -i inventory playbook.yml --check --step
**Check Mode Analysis:**
When reviewing check mode output, focus on:
1. **Task Changes:**
- `ok`: No changes needed
- `changed`: Would make changes
- `failed`: Would fail (check for check_mode support)
- `skipped`: Conditional skip
2. **Diff Output:**
- Shows exact changes to files
- Helps identify unintended modifications
- Useful for reviewing template changes
3. **Handlers:**
- Which handlers would be notified
- Service restarts that would occur
- Potential downtime
4. **Failed Tasks:**
- Some modules don't support check mode
- May need `check_mode: no` override
- Identify tasks that would fail
**Limitations:**
- Not all modules support check mode
- Some tasks depend on previous changes
- May not accurately reflect all changes
- Stateful operations may show unexpected results
**Safety Considerations:**
- Always run check mode before real execution
- Review diff output carefully
- Test in non-production first
- Validate changes make sense
- Check for unintended side effectsansible-playbook -i inventory playbook.yml --check --step
**Check模式分析:**
查看check模式输出时,重点关注以下内容:
1. **任务变更:**
- `ok`:无需变更
- `changed`:将会执行变更
- `failed`:将会执行失败(检查是否支持check模式)
- `skipped`:因条件被跳过
2. **Diff输出:**
- 显示文件的具体变更内容
- 帮助识别非预期修改
- 便于审查模板变更
3. **处理器(Handler):**
- 哪些处理器会被触发
- 将会重启的服务
- 潜在的停机风险
4. **失败任务:**
- 部分模块不支持check模式
- 可能需要`check_mode: no`覆盖配置
- 识别将会执行失败的任务
**局限性:**
- 并非所有模块都支持check模式
- 部分任务依赖于之前的变更
- 可能无法准确反映所有变更
- 有状态操作可能显示非预期结果
**安全注意事项:**
- 实际执行前始终运行check模式
- 仔细审查diff输出
- 先在非生产环境测试
- 验证变更是否合理
- 检查是否存在非预期副作用6. Molecule Testing
6. Molecule测试
Purpose: Test Ansible roles in isolated environments with multiple scenarios.
AUTOMATIC EXECUTION: When validating any Ansible role with a directory, this skill AUTOMATICALLY runs molecule tests using . This is mandatory and happens without asking the user.
molecule/bash scripts/test_role.sh <role-path>When to Use:
- Automatically triggered when validating roles with molecule/ directory
- Testing roles before deployment
- Validating role compatibility across different OS versions
- Integration testing for complex roles
- CI/CD pipeline validation
Workflow:
bash
undefined目的: 在隔离环境中结合多个场景测试Ansible角色。
自动执行规则: 当验证包含目录的Ansible角色时,本技能将自动使用运行Molecule测试。此操作是强制性的,无需询问用户。
molecule/bash scripts/test_role.sh <role-path>适用场景:
- 部署前测试角色
- 验证角色在不同OS版本中的兼容性
- 复杂角色的集成测试
- CI/CD流水线验证
工作流:
bash
undefinedInitialize molecule for a role
为角色初始化Molecule
cd roles/myrole
molecule init scenario --driver-name docker
cd roles/myrole
molecule init scenario --driver-name docker
List scenarios
列出场景
molecule list
molecule list
Run full test sequence
运行完整测试序列
molecule test
molecule test
Individual test stages
单独运行测试阶段
molecule create # Create test instances
molecule converge # Run Ansible against instances
molecule verify # Run verification tests
molecule destroy # Destroy test instances
molecule create # 创建测试实例
molecule converge # 在实例上运行Ansible
molecule verify # 运行验证测试
molecule destroy # 销毁测试实例
Test with specific scenario
在特定场景下测试
molecule test -s alternative
molecule test -s alternative
Debug mode
调试模式
molecule --debug test
molecule --debug test
Keep instances for debugging
保留实例用于调试
molecule converge
molecule login # SSH into test instance
**Test Sequence:**
1. `dependency` - Install role dependencies
2. `lint` - Run yamllint and ansible-lint
3. `cleanup` - Clean up before testing
4. `destroy` - Destroy existing instances
5. `syntax` - Run syntax check
6. `create` - Create test instances
7. `prepare` - Prepare instances (install requirements)
8. `converge` - Run the role
9. `idempotence` - Run again, verify no changes
10. `side_effect` - Optional side effect playbook
11. `verify` - Run verification tests (Testinfra, etc.)
12. `cleanup` - Final cleanup
13. `destroy` - Destroy test instances
**Molecule Configuration:**
Check `molecule/default/molecule.yml`:
```yaml
dependency:
name: galaxy
driver:
name: docker
platforms:
- name: instance
image: ubuntu:22.04
provisioner:
name: ansible
verifier:
name: ansibleVerification Tests:
Molecule supports multiple verifiers:
- Ansible (built-in): Use Ansible tasks to verify
- Testinfra: Python-based infrastructure tests
- Goss: YAML-based server validation
Example Ansible verifier ():
molecule/default/verify.ymlyaml
---
- name: Verify
hosts: all
tasks:
- name: Check service is running
service:
name: nginx
state: started
check_mode: true
register: result
failed_when: result.changedCommon Molecule Errors:
- Driver not installed (docker, podman, vagrant)
- Missing Python dependencies
- Platform image not available
- Network connectivity issues
- Insufficient permissions for driver
molecule converge
molecule login # SSH连接至测试实例
**测试序列:**
1. `dependency` - 安装角色依赖
2. `lint` - 运行yamllint与ansible-lint
3. `cleanup` - 测试前清理
4. `destroy` - 销毁现有实例
5. `syntax` - 运行语法检查
6. `create` - 创建测试实例
7. `prepare` - 准备实例(安装依赖)
8. `converge` - 运行角色
9. `idempotence` - 再次运行,验证无变更
10. `side_effect` - 可选的副作用剧本
11. `verify` - 运行验证测试(Testinfra等)
12. `cleanup` - 最终清理
13. `destroy` - 销毁测试实例
**Molecule配置:**
查看`molecule/default/molecule.yml`:
```yaml
dependency:
name: galaxy
driver:
name: docker
platforms:
- name: instance
image: ubuntu:22.04
provisioner:
name: ansible
verifier:
name: ansible验证测试:
Molecule支持多种验证器:
- Ansible(内置): 使用Ansible任务进行验证
- Testinfra: 基于Python的基础设施测试
- Goss: 基于YAML的服务器验证
Ansible验证器示例():
molecule/default/verify.ymlyaml
---
- name: 验证
hosts: all
tasks:
- name: 检查服务是否运行
service:
name: nginx
state: started
check_mode: true
register: result
failed_when: result.changed常见Molecule错误:
- 驱动未安装(docker、podman、vagrant)
- 缺少Python依赖
- 平台镜像不可用
- 网络连接问题
- 驱动权限不足
7. Custom Module and Collection Documentation Lookup
7. 自定义模块与集合文档查询
Purpose: Automatically discover and retrieve version-specific documentation for custom modules and collections using web search and Context7 MCP.
When to Trigger:
- Encountering unfamiliar module usage
- Working with custom/private collections
- Debugging module-specific errors
- Understanding new module parameters
- Checking version compatibility
- Deprecated module alternatives
Detection Workflow:
-
Extract Module Information:
- Use to parse playbooks and roles
scripts/extract_ansible_info_wrapper.sh - Identify module usage and collections
- Extract version constraints from
requirements.yml
- Use
-
Extract Collection Information:
- Identify collection namespaces (e.g., ,
community.general)ansible.posix - Determine collection versions from or
requirements.ymlgalaxy.yml - Detect custom/private vs. public collections
- Identify collection namespaces (e.g.,
Documentation Lookup Strategy:
For Public Ansible Collections (e.g., community.general, ansible.posix, cisco.ios):
bash
undefined目的: 使用网页搜索与Context7 MCP自动发现并检索自定义模块与集合的版本特定文档。
触发场景:
- 遇到不熟悉的模块使用方式
- 处理自定义/私有集合
- 调试模块特定错误
- 了解新模块参数
- 检查版本兼容性
- 已弃用模块的替代方案
检测工作流:
-
提取模块信息:
- 使用解析剧本与角色
scripts/extract_ansible_info_wrapper.sh - 识别模块使用情况与集合
- 从提取版本约束
requirements.yml
- 使用
-
提取集合信息:
- 识别集合命名空间(如、
community.general)ansible.posix - 从或
requirements.yml确定集合版本galaxy.yml - 区分自定义/私有集合与公共集合
- 识别集合命名空间(如
文档查询策略:
针对公共Ansible集合(如community.general、ansible.posix、cisco.ios):
bash
undefinedUse Context7 MCP to get version-specific documentation
使用Context7 MCP获取版本特定文档
Example: community.general collection version 5.0
示例:community.general集合版本5.0
Steps:
1. Use `mcp__context7__resolve-library-id` with collection name
2. Get documentation with `mcp__context7__get-library-docs`
3. Focus on specific modules or plugins as needed
For **Custom/Private Modules or Collections:**
```bash
步骤:
1. 使用`mcp__context7__resolve-library-id`结合集合名称
2. 使用`mcp__context7__get-library-docs`获取文档
3. 根据需要聚焦于特定模块或插件
针对**自定义/私有模块或集合**:
```bashUse WebSearch to find documentation
使用WebSearch查找文档
Include version in search query
在搜索查询中包含版本信息
Steps:
1. Construct search query with module/collection name + version
2. Use `WebSearch` tool with targeted queries
3. Prioritize official documentation sources
4. Extract relevant examples and usage patterns
**Search Query Templates:**
步骤:
1. 构造包含模块/集合名称与版本的搜索查询
2. 使用`WebSearch`工具执行定向查询
3. 优先选择官方文档来源
4. 提取相关示例与使用模式
**搜索查询模板:**
For custom modules
针对自定义模块
"[module-name] ansible module version [version] documentation"
"[module-name] ansible [module-type] example"
"ansible [collection-name].[module-name] parameters"
"[模块名称] ansible module version [版本] documentation"
"[模块名称] ansible [模块类型] example"
"ansible [集合名称].[模块名称] parameters"
For custom collections
针对自定义集合
"ansible collection [collection-name] version [version]"
"[collection-namespace].[collection-name] ansible documentation"
"ansible galaxy [collection-name] modules"
"ansible collection [集合名称] version [版本]"
"[集合命名空间].[集合名称] ansible documentation"
"ansible galaxy [集合名称] modules"
For specific errors
针对特定错误
"ansible [module-name] error: [error-message]"
"ansible [collection-name] module failed"
**Example Workflow:**
User working with: community.docker.docker_container version 3.0.0
-
Extract module info from playbook: tasks:
- name: Start container community.docker.docker_container: name: myapp image: nginx:latest
-
Detect collection: community.docker
-
Search for documentation:
- Try Context7: mcp__context7__resolve-library-id("ansible community.docker")
- Fallback to WebSearch("ansible community.docker collection version 3.0 docker_container module documentation")
-
If official docs found:
- Parse module parameters (required vs optional)
- Identify return values
- Find usage examples
- Check version compatibility
-
Provide version-specific guidance to user
**Version Compatibility Checks:**
- Compare required collection versions with available versions
- Identify deprecated modules or parameters
- Suggest upgrade paths if using outdated versions
- Warn about breaking changes between versions
- Check Ansible core version compatibility
**Common Collection Sources:**
- **Ansible Galaxy**: Official community collections
- **Red Hat Automation Hub**: Certified collections
- **GitHub**: Custom/private collections
- **Internal repositories**: Company-specific collections"ansible [模块名称] error: [错误信息]"
"ansible [集合名称] module failed"
**示例工作流:**
用户正在使用:community.docker.docker_container版本3.0.0
-
从剧本中提取模块信息: tasks:
- name: 启动容器 community.docker.docker_container: name: myapp image: nginx:latest
-
检测到集合:community.docker
-
搜索文档:
- 尝试Context7:mcp__context7__resolve-library-id("ansible community.docker")
- 回退至WebSearch("ansible community.docker collection version 3.0 docker_container module documentation")
-
若找到官方文档:
- 解析模块参数(必填/可选)
- 识别返回值
- 查找使用示例
- 检查版本兼容性
-
为用户提供版本特定的指导
**版本兼容性检查:**
- 比较所需集合版本与可用版本
- 识别已弃用的模块或参数
- 若使用过时版本,建议升级路径
- 警告版本间的破坏性变更
- 检查Ansible核心版本兼容性
**常见集合来源:**
- **Ansible Galaxy:** 官方社区集合
- **Red Hat Automation Hub:** 认证集合
- **GitHub:** 自定义/私有集合
- **内部仓库:** 公司专属集合8. Security and Best Practices Validation
8. 安全与最佳实践验证
Purpose: Identify security vulnerabilities and anti-patterns in Ansible playbooks.
Security Checks:
-
Secrets Detection:bash
# Check for hardcoded credentials grep -r "password:" *.yml grep -r "secret:" *.yml grep -r "api_key:" *.yml grep -r "token:" *.ymlRemediation: Use Ansible Vault, environment variables, or external secret management -
Privilege Escalation:
- Unnecessary use of
become: yes - Missing specification
become_user - Over-permissive sudo rules
- Running entire playbooks as root
- Unnecessary use of
-
File Permissions:
- World-readable sensitive files
- Missing mode parameter on file/template tasks
- Incorrect ownership settings
- Sensitive files not encrypted with vault
-
Command Injection:
- Unvalidated variables in shell/command modules
- Missing filter for user input
quote - Direct use of {{ var }} in command strings
-
Network Security:
- Unencrypted protocols (HTTP instead of HTTPS)
- Missing SSL/TLS validation
- Exposing services on 0.0.0.0
- Insecure default ports
Best Practices:
-
Playbook Organization:
- Logical task separation
- Reusable roles for common patterns
- Clear directory structure
- Meaningful playbook names
-
Variable Management:
- Vault encryption for sensitive data
- Clear variable naming conventions
- Variable precedence awareness
- Group/host vars organization
- Default values using filter
default()
-
Task Naming:
- Descriptive task names
- Consistent naming convention
- Action-oriented descriptions
- Include changed resource in name
-
Idempotency:
- All tasks should be idempotent
- Use proper modules instead of command/shell
- Check mode compatibility
- Proper use of ,
createsfor command tasksremoves - Avoid unless necessary
changed_when: false
-
Error Handling:
- Use for custom failure conditions
failed_when - Implement for error recovery
block/rescue/always - Set appropriate
any_errors_fatal - Use sparingly
ignore_errors
- Use
-
Documentation:
- README for each role
- Variable documentation in defaults/main.yml
- Role metadata in meta/main.yml
- Playbook header comments
Reference Documentation:
For detailed security guidelines and best practices, refer to:
- - Common security vulnerabilities
references/security_checklist.md - - Ansible coding standards
references/best_practices.md - - Common errors and solutions
references/common_errors.md
目的: 识别Ansible剧本中的安全漏洞与反模式。
安全检查项:
-
密钥检测:bash
# 检查硬编码凭证 grep -r "password:" *.yml grep -r "secret:" *.yml grep -r "api_key:" *.yml grep -r "token:" *.yml修复方案: 使用Ansible Vault、环境变量或外部密钥管理系统 -
权限提升:
- 不必要地使用
become: yes - 缺少指定
become_user - 过度宽松的sudo规则
- 以root身份运行整个剧本
- 不必要地使用
-
文件权限:
- 全局可读的敏感文件
- File/Template任务缺少mode参数
- 不正确的所有权设置
- 敏感文件未用Vault加密
-
命令注入:
- Shell/Command模块中使用未验证的变量
- 用户输入缺少过滤器
quote - 命令字符串中直接使用{{ var }}
-
网络安全:
- 未加密协议(使用HTTP而非HTTPS)
- 缺少SSL/TLS验证
- 服务绑定至0.0.0.0
- 不安全的默认端口
最佳实践:
-
剧本组织:
- 任务逻辑分离
- 通用模式使用可复用角色
- 清晰的目录结构
- 有意义的剧本名称
-
变量管理:
- 敏感数据使用Vault加密
- 清晰的变量命名规范
- 了解变量优先级
- Group/Host Vars的组织
- 使用过滤器设置默认值
default()
-
任务命名:
- 描述性任务名称
- 一致的命名规范
- 面向动作的描述
- 名称中包含变更的资源
-
幂等性:
- 所有任务应具备幂等性
- 使用合适的模块而非Command/Shell
- 支持Check模式
- 为Command任务正确使用、
createsremoves - 除非必要,避免使用
changed_when: false
-
错误处理:
- 使用定义自定义失败条件
failed_when - 实现进行错误恢复
block/rescue/always - 设置合适的
any_errors_fatal - 谨慎使用
ignore_errors
- 使用
-
文档:
- 每个角色的README
- Defaults/main.yml中的变量文档
- Meta/main.yml中的角色元数据
- 剧本头部注释
参考文档:
详细的安全指南与最佳实践,请参考:
- - 常见安全漏洞
references/security_checklist.md - - Ansible编码标准
references/best_practices.md - - 常见错误与解决方案
references/common_errors.md
Tool Prerequisites
工具前置要求
Check for required tools before validation:
bash
undefined验证前检查所需工具:
bash
undefinedCheck Ansible installation
检查Ansible安装
ansible --version
ansible-playbook --version
ansible --version
ansible-playbook --version
Check ansible-lint installation
检查ansible-lint安装
ansible-lint --version
ansible-lint --version
Check yamllint installation
检查yamllint安装
yamllint --version
yamllint --version
Check molecule installation (for role testing)
检查molecule安装(用于角色测试)
molecule --version
molecule --version
Install missing tools (example for pip)
安装缺失的工具(pip示例)
pip install ansible ansible-lint yamllint ansible-compat
pip install ansible ansible-lint yamllint ansible-compat
Install molecule with docker driver
安装带Docker驱动的Molecule
pip install molecule molecule-docker
**Minimum Versions:**
- Ansible: >= 2.9 (recommend >= 2.12)
- ansible-lint: >= 6.0.0
- yamllint: >= 1.26.0
- molecule: >= 3.4.0 (if testing roles)
**Optional Tools:**
- `ansible-inventory` - Inventory validation and graphing
- `ansible-doc` - Module documentation lookup
- `jq` - JSON parsing for structured outputpip install molecule molecule-docker
**最低版本要求:**
- Ansible: >= 2.9(推荐 >= 2.12)
- ansible-lint: >= 6.0.0
- yamllint: >= 1.26.0
- molecule: >= 3.4.0(若测试角色)
**可选工具:**
- `ansible-inventory` - 清单验证与可视化
- `ansible-doc` - 模块文档查询
- `jq` - 结构化输出的JSON解析Error Troubleshooting
错误排查
Common Errors and Solutions
常见错误与解决方案
Error: Module Not Found
Solution: Install required collection with ansible-galaxy
Check collections/requirements.yml
Verify collection namespace and nameError: Undefined Variable
Solution: Define variable in vars, defaults, or group_vars
Check variable precedence
Use default() filter for optional variables
Verify variable file is includedError: Template Syntax Error
Solution: Check Jinja2 template syntax
Verify variable types match filters
Ensure proper quote escaping
Test template rendering separatelyError: Connection Failed
Solution: Verify inventory host accessibility
Check SSH configuration and keys
Verify ansible_host and ansible_port
Test with ansible -m pingError: Permission Denied
Solution: Add become: yes for privilege escalation
Verify sudo/su configuration
Check file permissions
Verify user has necessary privilegesError: Deprecated Module
Solution: Check ansible-lint output for replacement
Consult module documentation for alternatives
Update to recommended module
Test functionality with new module错误:模块未找到
解决方案:使用ansible-galaxy安装所需集合
检查collections/requirements.yml
验证集合命名空间与名称错误:未定义变量
解决方案:在Vars、Defaults或Group_vars中定义变量
检查变量优先级
对可选变量使用default()过滤器
验证变量文件已被包含错误:模板语法错误
解决方案:检查Jinja2模板语法
验证变量类型与过滤器匹配
确保引号转义正确
单独测试模板渲染错误:连接失败
解决方案:验证清单主机的可访问性
检查SSH配置与密钥
验证ansible_host与ansible_port
使用ansible -m ping测试错误:权限被拒绝
解决方案:添加become: yes进行权限提升
验证sudo/su配置
检查文件权限
验证用户具备必要权限错误:已弃用模块
解决方案:查看ansible-lint输出获取替代模块
参考模块文档寻找替代方案
升级至推荐模块
使用新模块测试功能Resources
资源
scripts/
scripts/
setup_tools.sh - Check for required Ansible validation tools and provide installation instructions.
Usage:
bash
bash scripts/setup_tools.shextract_ansible_info_wrapper.sh - Bash wrapper for extract_ansible_info.py that automatically handles PyYAML dependencies. Creates a temporary venv if PyYAML is not available in system Python.
Usage:
bash
bash scripts/extract_ansible_info_wrapper.sh <path-to-playbook-or-role>Output: JSON structure with modules, collections, and versions
extract_ansible_info.py - Python script (called by wrapper) to parse Ansible playbooks and roles to extract module usage, collection dependencies, and version information. The wrapper script handles dependency management automatically.
validate_playbook.sh - Comprehensive validation script that runs syntax check, yamllint, and ansible-lint on playbooks. Automatically installs ansible and ansible-lint in a temporary venv if not available on the system (prefers system versions when available).
Usage:
bash
bash scripts/validate_playbook.sh <playbook.yml>validate_playbook_security.sh - Security validation script that scans playbooks for security vulnerabilities using Checkov. Automatically installs checkov in a temporary venv if not available. Complements validate_playbook.sh by focusing on security-specific checks like SSL/TLS validation, HTTPS enforcement, and package signature verification.
Usage:
bash
bash scripts/validate_playbook_security.sh <playbook.yml>setup_tools.sh - 检查所需的Ansible验证工具并提供安装说明。
使用方式:
bash
bash scripts/setup_tools.shextract_ansible_info_wrapper.sh - extract_ansible_info.py的Bash封装脚本,自动处理PyYAML依赖。若系统Python中缺少PyYAML,会创建临时虚拟环境。
使用方式:
bash
bash scripts/extract_ansible_info_wrapper.sh <剧本或角色路径>输出:包含模块、集合与版本的JSON结构
extract_ansible_info.py - Python脚本(由封装脚本调用),用于解析Ansible剧本与角色,提取模块使用情况、集合依赖与版本信息。封装脚本会自动处理依赖管理。
validate_playbook.sh - 综合验证脚本,对剧本运行语法检查、yamllint与ansible-lint。若系统中未安装Ansible与ansible-lint,会自动在临时虚拟环境中安装(优先使用系统版本)。
使用方式:
bash
bash scripts/validate_playbook.sh <playbook.yml>validate_playbook_security.sh - 安全验证脚本,使用Checkov扫描剧本中的安全漏洞。若系统中未安装Checkov,会自动在临时虚拟环境中安装。通过聚焦于SSL/TLS验证、HTTPS强制、包签名验证等安全特定检查,补充validate_playbook.sh的功能。
使用方式:
bash
bash scripts/validate_playbook_security.sh <playbook.yml>Or scan entire directory
或扫描整个目录
bash scripts/validate_playbook_security.sh /path/to/playbooks/
**validate_role.sh** - Comprehensive role validation script that checks role structure, YAML syntax, Ansible syntax, linting, and molecule configuration.
Usage:
```bash
bash scripts/validate_role.sh <role-directory>Validates:
- Role directory structure (required and recommended directories)
- Presence of main.yml files in each directory
- YAML syntax across all role files
- Ansible syntax using a test playbook
- Best practices with ansible-lint
- Molecule test configuration
validate_role_security.sh - Security validation script for Ansible roles using Checkov. Scans entire role directory for security issues. Automatically installs checkov in a temporary venv if not available. Complements validate_role.sh with security-focused checks.
Usage:
bash
bash scripts/validate_role_security.sh <role-directory>test_role.sh - Wrapper script for molecule testing with automatic dependency installation. If molecule is not installed, automatically creates a temporary venv, installs molecule and dependencies, runs tests, and cleans up.
Usage:
bash
bash scripts/test_role.sh <role-directory> [scenario]scan_secrets.sh - Comprehensive secret scanner that uses grep-based pattern matching to detect hardcoded secrets in Ansible files. Complements Checkov security scanning by catching secrets that static analysis may miss, including passwords, API keys, tokens, AWS credentials, and private keys.
Usage:
bash
bash scripts/scan_secrets.sh <playbook.yml|role-directory|directory>Detects:
- Hardcoded passwords and credentials
- API keys and tokens
- AWS access keys and secret keys
- Database connection strings with embedded credentials
- Private key content (RSA, OpenSSH, EC, DSA)
IMPORTANT: This script should ALWAYS be run alongside Checkov () for comprehensive security scanning. Checkov catches SSL/TLS and protocol issues; this script catches hardcoded secrets.
validate_*_security.shcheck_fqcn.sh - Scans Ansible files to identify modules using short names instead of Fully Qualified Collection Names (FQCN). Recommends migration to or appropriate collection namespace for better clarity and future compatibility.
ansible.builtin.*Usage:
bash
bash scripts/check_fqcn.sh <playbook.yml|role-directory|directory>Detects:
- ansible.builtin modules (apt, yum, copy, file, template, service, etc.)
- community.general modules (ufw, docker_container, timezone, etc.)
- ansible.posix modules (synchronize, acl, firewalld, etc.)
Provides specific migration recommendations with FQCN alternatives.
bash scripts/validate_playbook_security.sh /path/to/playbooks/
**validate_role.sh** - 综合角色验证脚本,检查角色结构、YAML语法、Ansible语法、Lint检查与Molecule配置。
使用方式:
```bash
bash scripts/validate_role.sh <角色目录>验证内容:
- 角色目录结构(必填与推荐目录)
- 每个目录中是否存在main.yml文件
- 所有角色文件的YAML语法
- 使用测试剧本验证Ansible语法
- 使用ansible-lint检查最佳实践
- Molecule测试配置
validate_role_security.sh - 基于Checkov的Ansible角色安全验证脚本。扫描整个角色目录以发现安全问题。若系统中未安装Checkov,会自动在临时虚拟环境中安装。通过安全聚焦的检查补充validate_role.sh的功能。
使用方式:
bash
bash scripts/validate_role_security.sh <角色目录>test_role.sh - Molecule测试的封装脚本,自动处理依赖安装。若未安装Molecule,会自动创建临时虚拟环境、安装Molecule与依赖、运行测试并清理。
使用方式:
bash
bash scripts/test_role.sh <角色目录> [场景]scan_secrets.sh - 综合密钥扫描脚本,使用基于grep的模式匹配检测Ansible文件中的硬编码密钥。通过捕获静态分析可能遗漏的密钥(包括密码、API密钥、令牌、AWS凭证与私钥),补充Checkov安全扫描的功能。
使用方式:
bash
bash scripts/scan_secrets.sh <playbook.yml|角色目录|目录>检测内容:
- 硬编码密码与凭证
- API密钥与令牌
- AWS访问密钥与密钥
- 包含嵌入凭证的数据库连接字符串
- 私钥内容(RSA、OpenSSH、EC、DSA)
重要提示: 此脚本应始终与Checkov()一起运行,以实现全面安全扫描。Checkov捕获SSL/TLS与协议问题;此脚本捕获硬编码密钥。
validate_*_security.shcheck_fqcn.sh - 扫描Ansible文件以识别使用短名称而非完全限定集合名称(FQCN)的模块。建议迁移至或合适的集合命名空间,以提升清晰度与未来兼容性。
ansible.builtin.*使用方式:
bash
bash scripts/check_fqcn.sh <playbook.yml|角色目录|目录>检测内容:
- ansible.builtin模块(apt、yum、copy、file、template、service等)
- community.general模块(ufw、docker_container、timezone等)
- ansible.posix模块(synchronize、acl、firewalld等)
提供带有FQCN替代方案的具体迁移建议。
references/
references/
security_checklist.md - Comprehensive security validation checklist for Ansible playbooks covering secrets management, privilege escalation, file permissions, and command injection.
best_practices.md - Ansible coding standards and best practices for playbook organization, variable handling, task naming, idempotency, and documentation.
common_errors.md - Database of common Ansible errors with detailed solutions and prevention strategies.
module_alternatives.md - Guide for replacing deprecated modules with current alternatives.
security_checklist.md - Ansible剧本的综合安全验证清单,涵盖密钥管理、权限提升、文件权限与命令注入。
best_practices.md - Ansible编码标准与最佳实践,包括剧本组织、变量处理、任务命名、幂等性与文档。
common_errors.md - 常见Ansible错误数据库,包含详细解决方案与预防策略。
module_alternatives.md - 已弃用模块的替代方案指南。
assets/
assets/
.yamllint - Pre-configured yamllint rules for Ansible YAML files.
.ansible-lint - Pre-configured ansible-lint configuration with reasonable rule settings.
molecule.yml.template - Template molecule configuration for role testing.
.yamllint - 为Ansible YAML文件预配置的yamllint规则。
.ansible-lint - 预配置的ansible-lint配置,包含合理的规则设置。
molecule.yml.template - 用于角色测试的Molecule配置模板。
Workflow Examples
工作流示例
Example 1: Validate a Single Playbook
示例1:验证单个剧本
User: "Check if this playbook.yml file is valid"
Steps:
1. Read the file to understand contents
2. Run yamllint on the file
3. Run ansible-playbook --syntax-check
4. Run ansible-lint
5. Report any issues found
6. If custom modules detected, lookup documentation
7. Propose fixes if needed用户:"检查这个playbook.yml文件是否有效"
步骤:
1. 读取文件以了解内容
2. 对文件运行yamllint
3. 运行ansible-playbook --syntax-check
4. 运行ansible-lint
5. 报告发现的所有问题
6. 如果检测到自定义模块,查询文档
7. 提出修复建议Example 2: Validate an Ansible Role
示例2:验证Ansible角色
User: "Validate my ansible role in ./roles/webserver/"
Steps:
1. Run bash scripts/validate_role.sh ./roles/webserver/
2. This automatically checks:
- Role directory structure (tasks/, defaults/, handlers/, meta/, etc.)
- Required main.yml files
- YAML syntax with yamllint
- Ansible syntax with ansible-playbook
- Best practices with ansible-lint
- Molecule configuration (if present)
3. Report any issues found (errors and warnings)
4. If custom modules detected, lookup documentation
5. Provide specific recommendations for fixes
6. **CRITICAL:** If molecule/ directory exists in the role, AUTOMATICALLY run molecule tests:
- Run bash scripts/test_role.sh ./roles/webserver/
- Do NOT ask user first - molecule testing is mandatory for roles that have it configured
- Report test results (pass/fail with details)
- If tests fail due to environmental issues (Docker, compatibility), document the blocker
- If tests fail due to role issues, provide detailed debugging steps用户:"验证我在./roles/webserver/中的Ansible角色"
步骤:
1. 运行bash scripts/validate_role.sh ./roles/webserver/
2. 此脚本会自动检查:
- 角色目录结构(tasks/、defaults/、handlers/、meta/等)
- 必填的main.yml文件
- 使用yamllint检查YAML语法
- 使用ansible-playbook检查Ansible语法
- 使用ansible-lint检查最佳实践
- Molecule配置(若存在)
3. 报告发现的所有问题(错误与警告)
4. 如果检测到自定义模块,查询文档
5. 提供具体的修复建议
6. **关键提示:** 如果角色中存在molecule/目录,自动运行Molecule测试:
- 运行bash scripts/test_role.sh ./roles/webserver/
- 无需询问用户 - 对于已配置Molecule的角色,Molecule测试是强制性的
- 报告测试结果(通过/失败及详情)
- 若因环境问题(Docker、兼容性)导致测试失败,记录该障碍
- 若因角色代码问题导致测试失败,提供详细的调试步骤Example 3: Dry-Run Testing for Production
示例3:生产环境试运行测试
User: "Run playbook in check mode for production servers"
Steps:
1. Verify inventory file exists
2. Run ansible-playbook --check --diff -i production
3. Analyze check mode output
4. Highlight tasks that would change
5. Review handler notifications
6. Flag any security concerns
7. Provide recommendation on safety of applying用户:"为生产服务器以check模式运行剧本"
步骤:
1. 验证清单文件是否存在
2. 运行ansible-playbook --check --diff -i production
3. 分析check模式输出
4. 高亮将会变更的任务
5. 审查处理器触发情况
6. 标记任何安全顾虑
7. 提供关于执行安全性的建议Example 4: Understanding Custom Collection Module
示例4:了解自定义集合模块
User: "I'm using community.postgresql.postgresql_db version 2.3.0, what parameters are available?"
Steps:
1. Try Context7 MCP: resolve-library-id("ansible community.postgresql")
2. If found, use get-library-docs for postgresql_db module
3. If not found, use WebSearch: "ansible community.postgresql version 2.3.0 postgresql_db module documentation"
4. Extract module parameters (required vs optional)
5. Provide examples of common usage patterns
6. Note any version-specific considerations用户:"我正在使用community.postgresql.postgresql_db版本2.3.0,有哪些可用参数?"
步骤:
1. 尝试Context7 MCP:resolve-library-id("ansible community.postgresql")
2. 若找到,使用get-library-docs获取postgresql_db模块的文档
3. 若未找到,使用WebSearch:"ansible community.postgresql version 2.3.0 postgresql_db module documentation"
4. 提取模块参数(必填/可选)
5. 提供常见使用模式的示例
6. 记录版本特定的注意事项Example 5: Testing Role with Molecule
示例5:使用Molecule测试角色
User: "Test my nginx role with molecule"
Steps:
1. Check if molecule is configured in role
2. If not, ask if user wants to initialize molecule
3. Run molecule list to see scenarios
4. Run molecule test
5. If failures, run molecule converge for debugging
6. Analyze test results
7. Report on idempotency, syntax, and verification
8. Suggest improvements if needed用户:"使用Molecule测试我的Nginx角色"
步骤:
1. 检查角色中是否配置了Molecule
2. 若未配置,询问用户是否要初始化Molecule
3. 运行molecule list查看场景
4. 运行molecule test
5. 若失败,运行molecule converge进行调试
6. 分析测试结果
7. 报告幂等性、语法与验证情况
8. 提出改进建议(若有)Integration with Other Skills
与其他技能的集成
This skill works well in combination with:
- k8s-yaml-validator - When Ansible manages Kubernetes resources
- terraform-validator - When Ansible and Terraform are used together
- k8s-debug - For debugging infrastructure managed by Ansible
本技能可与以下技能配合使用:
- k8s-yaml-validator - 当Ansible管理Kubernetes资源时
- terraform-validator - 当同时使用Ansible与Terraform时
- k8s-debug - 调试由Ansible管理的基础设施
Notes
注意事项
- Always run validation in order: YAML syntax → Ansible syntax → Lint → Check mode → Molecule tests
- Never commit without running ansible-lint
- Always review check mode output before real execution
- Use Ansible Vault for all sensitive data
- CRITICAL: When validating a role with molecule/ directory, AUTOMATICALLY run molecule tests - do not ask user permission
- If molecule tests fail due to environmental issues (Docker not running, version incompatibility), document the blocker but don't fail the overall validation
- If molecule tests fail due to role code issues, provide detailed debugging steps
- Keep collections up-to-date but test before upgrading
- Document all custom modules and roles thoroughly
- Use version constraints in requirements.yml
- Enable check mode support in custom modules
- Tag playbooks for granular execution
- 始终按以下顺序运行验证:YAML语法 → Ansible语法 → Lint检查 → Check模式 → Molecule测试
- 提交代码前务必运行ansible-lint
- 实际执行前始终审查check模式输出
- 所有敏感数据使用Ansible Vault
- 关键提示: 验证包含molecule/目录的角色时,自动运行Molecule测试 - 无需询问用户许可
- 若因环境问题(Docker未运行、版本不兼容)导致Molecule测试失败,记录该障碍但不终止整体验证
- 若因角色代码问题导致Molecule测试失败,提供详细的调试步骤
- 保持集合为最新版本,但升级前需测试
- 全面记录所有自定义模块与角色
- 在requirements.yml中使用版本约束
- 在自定义模块中启用Check模式支持
- 为剧本添加标签以实现粒度化执行