ansible-generator
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAnsible Generator
Ansible 生成器
Overview
概述
Generate production-ready Ansible resources (playbooks, roles, tasks, inventory files) following current best practices, naming conventions, and security standards. All generated resources are automatically validated using the devops-skills:ansible-validator skill to ensure syntax correctness and lint compliance.
生成符合当前最佳实践、命名规范和安全标准的可用于生产环境的Ansible资源(剧本、角色、任务、清单文件)。所有生成的资源都会自动通过devops-skills:ansible-validator工具进行验证,确保语法正确且符合代码规范。
Core Capabilities
核心功能
1. Generate Ansible Playbooks
1. 生成Ansible剧本
Create complete, production-ready playbooks with proper structure, error handling, and idempotency.
When to use:
- User requests: "Create a playbook to...", "Build a playbook for...", "Generate playbook that..."
- Scenarios: Application deployment, system configuration, backup automation, service management
Process:
- Understand the user's requirements (what needs to be automated)
- Identify target hosts, required privileges, and operating systems
- Use as structural foundation
assets/templates/playbook/basic_playbook.yml - Reference for implementation patterns
references/best-practices.md - Reference for correct module usage
references/module-patterns.md - Generate the playbook following these principles:
- Use Fully Qualified Collection Names (FQCN) for all modules
- Ensure idempotency (all tasks safe to run multiple times)
- Include proper error handling and conditionals
- Add meaningful task names starting with verbs
- Use appropriate tags for task categorization
- Include documentation header with usage instructions
- Add health checks in post_tasks when applicable
- ALWAYS validate the generated playbook using the devops-skills:ansible-validator skill
- If validation fails, fix the issues and re-validate
Example structure:
yaml
---创建结构规范、包含错误处理且具有幂等性的完整可用于生产环境的剧本。
适用场景:
- 用户需求:"创建一个剧本以..."、"构建用于...的剧本"、"生成可以...的剧本"
- 应用场景:应用部署、系统配置、备份自动化、服务管理
流程:
- 理解用户需求(需要自动化的内容)
- 确定目标主机、所需权限和操作系统
- 以作为结构基础
assets/templates/playbook/basic_playbook.yml - 参考获取实现模式
references/best-practices.md - 参考获取模块的正确用法
references/module-patterns.md - 遵循以下原则生成剧本:
- 所有模块使用完全限定集合名称(FQCN)
- 确保幂等性(所有任务可安全多次执行)
- 包含适当的错误处理和条件判断
- 添加以动词开头的有意义任务名称
- 使用合适的标签进行任务分类
- 包含带有使用说明的文档头部
- 适用时在post_tasks中添加健康检查
- 必须使用devops-skills:ansible-validator工具验证生成的剧本
- 如果验证失败,修复问题后重新验证
示例结构:
yaml
---Playbook: Deploy Web Application
Playbook: Deploy Web Application
Description: Deploy nginx web server with SSL
Description: Deploy nginx web server with SSL
Requirements:
Requirements:
- Ansible 2.10+
- Ansible 2.10+
- Target hosts: Ubuntu 20.04+
- Target hosts: Ubuntu 20.04+
Variables:
Variables:
- app_port: Application port (default: 8080)
- app_port: Application port (default: 8080)
Usage:
Usage:
ansible-playbook -i inventory/production deploy_web.yml
ansible-playbook -i inventory/production deploy_web.yml
-
name: Deploy and configure web server hosts: webservers become: true gather_facts: truevars: app_port: 8080 nginx_version: latestpre_tasks:
- name: Update package cache ansible.builtin.apt: update_cache: true cache_valid_time: 3600 when: ansible_os_family == "Debian"
tasks:-
name: Ensure nginx is installed ansible.builtin.package: name: nginx state: present tags:
- install
- nginx
-
name: Deploy nginx configuration ansible.builtin.template: src: templates/nginx.conf.j2 dest: /etc/nginx/nginx.conf mode: '0644' backup: true validate: 'nginx -t -c %s' notify: Reload nginx tags:
- configure
post_tasks:- name: Verify nginx is responding ansible.builtin.uri: url: "http://localhost:{{ app_port }}/health" status_code: 200 register: health_check until: health_check.status == 200 retries: 5 delay: 10
handlers:- name: Reload nginx ansible.builtin.service: name: nginx state: reloaded
undefined-
name: Deploy and configure web server hosts: webservers become: true gather_facts: truevars: app_port: 8080 nginx_version: latestpre_tasks:
- name: Update package cache ansible.builtin.apt: update_cache: true cache_valid_time: 3600 when: ansible_os_family == "Debian"
tasks:-
name: Ensure nginx is installed ansible.builtin.package: name: nginx state: present tags:
- install
- nginx
-
name: Deploy nginx configuration ansible.builtin.template: src: templates/nginx.conf.j2 dest: /etc/nginx/nginx.conf mode: '0644' backup: true validate: 'nginx -t -c %s' notify: Reload nginx tags:
- configure
post_tasks:- name: Verify nginx is responding ansible.builtin.uri: url: "http://localhost:{{ app_port }}/health" status_code: 200 register: health_check until: health_check.status == 200 retries: 5 delay: 10
handlers:- name: Reload nginx ansible.builtin.service: name: nginx state: reloaded
undefined2. Generate Ansible Roles
2. 生成Ansible角色
Create complete role structures with all required components organized following Ansible Galaxy conventions.
When to use:
- User requests: "Create a role for...", "Generate a role to...", "Build role that..."
- Scenarios: Reusable component creation, complex service setup, multi-environment deployments
Process:
- Understand the role's purpose and scope
- Copy and customize the complete role structure from :
assets/templates/role/- - Main task execution logic
tasks/main.yml - - Event handlers (service restarts, reloads)
handlers/main.yml - - Jinja2 configuration templates
templates/ - - Static files to copy
files/ - - Role-specific variables (high priority)
vars/main.yml - and
vars/Debian.yml- OS-specific variablesvars/RedHat.yml - - Default variables (easily overridable)
defaults/main.yml - - Role metadata and dependencies
meta/main.yml - - Role documentation
README.md
- Replace all with actual values:
[PLACEHOLDERS]- - The role name (lowercase with underscores)
[ROLE_NAME] - - Variable prefix for role variables
[role_name] - - Description of what the role does
[PLAYBOOK_DESCRIPTION] - ,
[package_name]- Actual package/service names[service_name] - - Default port numbers
[default_port] - All other placeholders as needed
- Implement role-specific logic following best practices:
- Use OS-specific variables via
include_vars - Prefix all role variables with role name
- Create handlers for all service changes
- Include validation in template tasks
- Add comprehensive tags
- Use OS-specific variables via
- Create proper role documentation in README.md
- ALWAYS validate the role using the devops-skills:ansible-validator skill
- Fix any validation errors and re-validate
Role variable naming convention:
- Prefix:
{{ role_name }}_ - Examples: ,
nginx_port,nginx_worker_processespostgres_max_connections
创建符合Ansible Galaxy规范的完整角色结构,包含所有必需组件。
适用场景:
- 用户需求:"创建一个用于...的角色"、"生成可以...的角色"、"构建用于...的角色"
- 应用场景:可复用组件创建、复杂服务部署、多环境部署
流程:
- 明确角色的用途和范围
- 复制并自定义中的完整角色结构:
assets/templates/role/- - 主要任务执行逻辑
tasks/main.yml - - 事件处理器(服务重启、重载)
handlers/main.yml - - Jinja2配置模板
templates/ - - 待复制的静态文件
files/ - - 角色特定变量(高优先级)
vars/main.yml - 和
vars/Debian.yml- 操作系统特定变量vars/RedHat.yml - - 默认变量(可轻松覆盖)
defaults/main.yml - - 角色元数据和依赖
meta/main.yml - - 角色文档
README.md
- 将所有替换为实际值:
[PLACEHOLDERS]- - 角色名称(小写,下划线分隔)
[ROLE_NAME] - - 角色变量的前缀
[role_name] - - 角色功能描述
[PLAYBOOK_DESCRIPTION] - 、
[package_name]- 实际的包/服务名称[service_name] - - 默认端口号
[default_port] - 其他所有需要替换的占位符
- 遵循最佳实践实现角色特定逻辑:
- 通过使用操作系统特定变量
include_vars - 所有角色变量添加角色名称前缀
- 为所有服务变更创建处理器
- 在模板任务中包含验证
- 添加全面的标签
- 通过
- 在README.md中创建完善的角色文档
- 必须使用devops-skills:ansible-validator工具验证角色
- 修复所有验证错误后重新验证
角色变量命名规范:
- 前缀:
{{ role_name }}_ - 示例:、
nginx_port、nginx_worker_processespostgres_max_connections
3. Generate Task Files
3. 生成任务文件
Create focused task files for specific operations that can be included in playbooks or roles.
When to use:
- User requests: "Create tasks to...", "Generate task file for..."
- Scenarios: Reusable task sequences, complex operations, conditional includes
Process:
- Define the specific operation to automate
- Reference for correct module usage
references/module-patterns.md - Generate task file with:
- Descriptive task names (verb-first)
- FQCN for all modules
- Proper error handling
- Idempotency checks
- Appropriate tags
- Conditional execution where needed
- ALWAYS validate using the devops-skills:ansible-validator skill
Example:
yaml
---创建针对特定操作的聚焦型任务文件,可在剧本或角色中引用。
适用场景:
- 用户需求:"创建用于...的任务"、"生成针对...的任务文件"
- 应用场景:可复用任务序列、复杂操作、条件引用
流程:
- 定义需要自动化的特定操作
- 参考获取模块的正确用法
references/module-patterns.md - 生成包含以下内容的任务文件:
- 描述性任务名称(动词开头)
- 所有模块使用FQCN
- 适当的错误处理
- 幂等性检查
- 合适的标签
- 适用时添加条件执行
- 必须使用devops-skills:ansible-validator工具验证
示例:
yaml
---Tasks: Database backup operations
Tasks: Database backup operations
-
name: Create backup directory ansible.builtin.file: path: "{{ backup_dir }}" state: directory mode: '0755' owner: postgres group: postgres
-
name: Dump PostgreSQL database ansible.builtin.command: > pg_dump -h {{ db_host }} -U {{ db_user }} -d {{ db_name }} -f {{ backup_dir }}/{{ db_name }}_{{ ansible_date_time.date }}.sql environment: PGPASSWORD: "{{ db_password }}" no_log: true changed_when: true
-
name: Compress backup file ansible.builtin.archive: path: "{{ backup_dir }}/{{ db_name }}{{ ansible_date_time.date }}.sql" dest: "{{ backup_dir }}/{{ db_name }}{{ ansible_date_time.date }}.sql.gz" format: gz remove: true
-
name: Remove old backups ansible.builtin.find: paths: "{{ backup_dir }}" patterns: "*.sql.gz" age: "{{ backup_retention_days }}d" register: old_backups
-
name: Delete old backup files ansible.builtin.file: path: "{{ item.path }}" state: absent loop: "{{ old_backups.files }}"
undefined-
name: Create backup directory ansible.builtin.file: path: "{{ backup_dir }}" state: directory mode: '0755' owner: postgres group: postgres
-
name: Dump PostgreSQL database ansible.builtin.command: > pg_dump -h {{ db_host }} -U {{ db_user }} -d {{ db_name }} -f {{ backup_dir }}/{{ db_name }}_{{ ansible_date_time.date }}.sql environment: PGPASSWORD: "{{ db_password }}" no_log: true changed_when: true
-
name: Compress backup file ansible.builtin.archive: path: "{{ backup_dir }}/{{ db_name }}{{ ansible_date_time.date }}.sql" dest: "{{ backup_dir }}/{{ db_name }}{{ ansible_date_time.date }}.sql.gz" format: gz remove: true
-
name: Remove old backups ansible.builtin.find: paths: "{{ backup_dir }}" patterns: "*.sql.gz" age: "{{ backup_retention_days }}d" register: old_backups
-
name: Delete old backup files ansible.builtin.file: path: "{{ item.path }}" state: absent loop: "{{ old_backups.files }}"
undefined4. Generate Inventory Files
4. 生成清单文件
Create inventory configurations with proper host organization, group hierarchies, and variable management.
When to use:
- User requests: "Create inventory for...", "Generate inventory file..."
- Scenarios: Environment setup, host organization, multi-tier architectures
Process:
- Understand the infrastructure topology
- Use as foundation:
assets/templates/inventory/- - Main inventory file (INI or YAML format)
hosts - - Global variables for all hosts
group_vars/all.yml - - Group-specific variables
group_vars/[groupname].yml - - Host-specific variables
host_vars/[hostname].yml
- Organize hosts into logical groups:
- Functional groups: ,
webservers,databasesloadbalancers - Environment groups: ,
production,stagingdevelopment - Geographic groups: ,
us-easteu-west
- Functional groups:
- Create group hierarchies with
[group:children] - Define variables at appropriate levels (all → group → host)
- Document connection settings and requirements
Inventory format preference:
- Use INI format for simple, flat inventories
- Use YAML format for complex, hierarchical inventories
Dynamic Inventory (Cloud Environments):
For AWS, Azure, GCP, and other cloud providers, use dynamic inventory plugins:
- AWS EC2: with filters and keyed_groups
plugin: amazon.aws.aws_ec2 - Azure: with resource group filters
plugin: azure.azcollection.azure_rm - Enables automatic host discovery based on tags, regions, and resource groups
- See for detailed examples
references/module-patterns.md
创建包含合理主机组织、组层级和变量管理的清单配置。
适用场景:
- 用户需求:"创建用于...的清单"、"生成清单文件"
- 应用场景:环境搭建、主机组织、多层架构
流程:
- 了解基础设施拓扑
- 以为基础:
assets/templates/inventory/- - 主清单文件(INI或YAML格式)
hosts - - 所有主机的全局变量
group_vars/all.yml - - 组特定变量
group_vars/[groupname].yml - - 主机特定变量
host_vars/[hostname].yml
- 将主机组织为逻辑组:
- 功能组:、
webservers、databasesloadbalancers - 环境组:、
production、stagingdevelopment - 地域组:、
us-easteu-west
- 功能组:
- 使用创建组层级
[group:children] - 在合适的层级定义变量(全局→组→主机)
- 记录连接设置和要求
清单格式偏好:
- 简单扁平清单使用INI格式
- 复杂层级清单使用YAML格式
动态清单(云环境):
对于AWS、Azure、GCP等云提供商,使用动态清单插件:
- AWS EC2:,配合过滤器和keyed_groups
plugin: amazon.aws.aws_ec2 - Azure:,配合资源组过滤器
plugin: azure.azcollection.azure_rm - 支持基于标签、地域和资源组自动发现主机
- 详细示例请参考
references/module-patterns.md
5. Generate Project Configuration Files
5. 生成项目配置文件
When to use:
- User requests: "Set up Ansible project", "Initialize Ansible configuration"
- Scenarios: New project initialization, standardizing project structure
Process:
- Use templates from :
assets/templates/project/- - Project configuration (forks, timeout, paths)
ansible.cfg - - Collections and roles dependencies
requirements.yml - - Lint rules for code quality
.ansible-lint
- Customize based on project requirements
- Document usage instructions
适用场景:
- 用户需求:"搭建Ansible项目"、"初始化Ansible配置"
- 应用场景:新项目初始化、项目结构标准化
流程:
- 使用中的模板:
assets/templates/project/- - 项目配置(forks、超时、路径)
ansible.cfg - - 集合和角色依赖
requirements.yml - - 代码质量检查规则
.ansible-lint
- 根据项目需求自定义
- 记录使用说明
6. Role Argument Specifications (Ansible 2.11+)
6. 角色参数规范(Ansible 2.11+)
When generating roles, include for automatic variable validation:
meta/argument_specs.yml- Define required and optional variables
- Specify types (str, int, bool, list, dict, path)
- Set default values and choices
- Enable automatic validation before role execution
- Template available at
assets/templates/role/meta/argument_specs.yml
生成角色时,包含以实现自动变量验证:
meta/argument_specs.yml- 定义必需和可选变量
- 指定类型(字符串、整数、布尔值、列表、字典、路径)
- 设置默认值和可选值
- 支持角色执行前的自动验证
- 模板位于
assets/templates/role/meta/argument_specs.yml
7. Handling Custom Modules and Collections
7. 处理自定义模块和集合
When generating Ansible resources that require custom modules, collections, or providers that are not part of ansible.builtin:
Detection:
- User mentions specific collections (e.g., "kubernetes.core", "amazon.aws", "community.docker")
- User requests integration with external tools/platforms
- Task requires modules not in ansible.builtin namespace
Process:
-
Identify the collection/module:
- Extract collection name and module name
- Determine if version-specific information is needed
-
Search for current documentation using WebSearch:
Search query pattern: "ansible [collection.name] [module] [version] documentation examples" Examples: - "ansible kubernetes.core k8s module latest documentation" - "ansible amazon.aws ec2_instance 2024 examples" - "ansible community.docker docker_container latest documentation" -
Analyze search results for:
- Current module parameters and their types
- Required vs optional parameters
- Version compatibility and deprecation notices
- Working examples and best practices
- Collection installation requirements
-
If Context7 MCP is available:
- First try to resolve library ID using
mcp__context7__resolve-library-id - Then fetch documentation using
mcp__context7__get-library-docs - This provides more structured and reliable documentation
- First try to resolve library ID using
-
Generate resource using discovered information:
- Use correct FQCN (e.g., , not just
kubernetes.core.k8s)k8s - Apply current parameter names and values
- Include collection installation instructions in comments
- Add version compatibility notes
- Use correct FQCN (e.g.,
-
Include installation instructions:yaml
# Requirements: # - ansible-galaxy collection install kubernetes.core:2.4.0 # or in requirements.yml: # --- # collections: # - name: kubernetes.core # version: "2.4.0"
Example with custom collection:
yaml
---当生成需要使用自定义模块、集合或不属于ansible.builtin的提供程序的Ansible资源时:
检测:
- 用户提及特定集合(如"kubernetes.core"、"amazon.aws"、"community.docker")
- 用户请求与外部工具/平台集成
- 任务需要使用ansible.builtin命名空间外的模块
流程:
-
识别集合/模块:
- 提取集合名称和模块名称
- 确定是否需要特定版本信息
-
使用WebSearch查找最新文档:
搜索查询模式:"ansible [collection.name] [module] [version] documentation examples" 示例: - "ansible kubernetes.core k8s module latest documentation" - "ansible amazon.aws ec2_instance 2024 examples" - "ansible community.docker docker_container latest documentation" -
分析搜索结果以获取:
- 当前模块参数及其类型
- 必需和可选参数
- 版本兼容性和弃用通知
- 可用示例和最佳实践
- 集合安装要求
-
如果Context7 MCP可用:
- 首先尝试使用解析库ID
mcp__context7__resolve-library-id - 然后使用获取文档
mcp__context7__get-library-docs - 此方式可提供更结构化、更可靠的文档
- 首先尝试使用
-
使用获取的信息生成资源:
- 使用正确的FQCN(如,而非仅
kubernetes.core.k8s)k8s - 使用当前参数名称和值
- 在注释中包含集合安装说明
- 添加版本兼容性说明
- 使用正确的FQCN(如
-
包含安装说明:yaml
# Requirements: # - ansible-galaxy collection install kubernetes.core:2.4.0 # or in requirements.yml: # --- # collections: # - name: kubernetes.core # version: "2.4.0"
使用自定义集合的示例:
yaml
---Playbook: Deploy Kubernetes Resources
Playbook: Deploy Kubernetes Resources
Requirements:
Requirements:
- Ansible 2.10+
- Ansible 2.10+
- Collection: kubernetes.core >= 2.4.0
- Collection: kubernetes.core >= 2.4.0
- Install: ansible-galaxy collection install kubernetes.core
- Install: ansible-galaxy collection install kubernetes.core
Variables:
Variables:
- k8s_namespace: Target namespace (default: default)
- k8s_namespace: Target namespace (default: default)
- k8s_kubeconfig: Path to kubeconfig (default: ~/.kube/config)
- k8s_kubeconfig: Path to kubeconfig (default: ~/.kube/config)
-
name: Deploy application to Kubernetes hosts: localhost gather_facts: false vars: k8s_namespace: production k8s_kubeconfig: ~/.kube/configtasks:
-
name: Create namespace kubernetes.core.k8s: kubeconfig: "{{ k8s_kubeconfig }}" state: present definition: apiVersion: v1 kind: Namespace metadata: name: "{{ k8s_namespace }}" tags:
- namespace
-
name: Deploy application kubernetes.core.k8s: kubeconfig: "{{ k8s_kubeconfig }}" state: present namespace: "{{ k8s_namespace }}" definition: apiVersion: apps/v1 kind: Deployment metadata: name: myapp spec: replicas: 3 selector: matchLabels: app: myapp template: metadata: labels: app: myapp spec: containers: - name: myapp image: myapp:1.0.0 ports: - containerPort: 8080 tags:
- deployment
-
undefined-
name: Deploy application to Kubernetes hosts: localhost gather_facts: false vars: k8s_namespace: production k8s_kubeconfig: ~/.kube/configtasks:
-
name: Create namespace kubernetes.core.k8s: kubeconfig: "{{ k8s_kubeconfig }}" state: present definition: apiVersion: v1 kind: Namespace metadata: name: "{{ k8s_namespace }}" tags:
- namespace
-
name: Deploy application kubernetes.core.k8s: kubeconfig: "{{ k8s_kubeconfig }}" state: present namespace: "{{ k8s_namespace }}" definition: apiVersion: apps/v1 kind: Deployment metadata: name: myapp spec: replicas: 3 selector: matchLabels: app: myapp template: metadata: labels: app: myapp spec: containers: - name: myapp image: myapp:1.0.0 ports: - containerPort: 8080 tags:
- deployment
-
undefinedValidation Workflow
验证工作流
CRITICAL: Every generated Ansible resource MUST be validated before presenting to the user.
关键要求: 所有生成的Ansible资源在交付给用户前必须经过验证。
Validation Process
验证流程
-
After generating any Ansible file, immediately invoke theskill:
devops-skills:ansible-validatorSkill: devops-skills:ansible-validator -
The devops-skills:ansible-validator skill will:
- Validate YAML syntax
- Run ansible-lint for best practices
- Perform ansible-playbook --syntax-check
- Execute in check mode (dry-run) when applicable
- Report any errors, warnings, or issues
-
If validation fails:
- Analyze the reported errors
- Fix the issues in the generated file
- Re-validate until all checks pass
-
If validation succeeds, present the result formally:Required Presentation Format:
## Generated [Resource Type]: [Name] **Validation Status:** ✅ All checks passed - YAML syntax: Passed - Ansible syntax: Passed - Ansible lint: Passed **Summary:** - [Brief description of what was generated] - [Key features/sections included] - [Any notable implementation decisions] **Usage:** ```bash [Exact command to run the playbook/role]Prerequisites:- [Any required collections or dependencies]
- [Target system requirements]
This formal presentation ensures the user clearly understands: - That validation was successful - What was generated and why - How to use the generated resource - Any prerequisites or dependencies
-
生成任何Ansible文件后,立即调用工具:
devops-skills:ansible-validatorSkill: devops-skills:ansible-validator -
devops-skills:ansible-validator工具将执行:
- 验证YAML语法
- 运行ansible-lint检查最佳实践
- 执行ansible-playbook --syntax-check
- 适用时以检查模式(空运行)执行
- 报告任何错误、警告或问题
-
如果验证失败:
- 分析报告的错误
- 修复生成文件中的问题
- 重新验证直至所有检查通过
-
如果验证成功,以规范格式呈现结果:必需呈现格式:
## 生成的[资源类型]:[名称] **验证状态:** ✅ 所有检查通过 - YAML语法:通过 - Ansible语法:通过 - Ansible lint:通过 **摘要:** - [生成内容的简要描述] - [包含的关键功能/部分] - [任何值得注意的实现决策] **使用方法:** ```bash [运行剧本/角色的确切命令]前置条件:- [任何必需的集合或依赖]
- [目标系统要求]
这种规范呈现方式确保用户清晰了解: - 验证已成功完成 - 生成了什么内容以及原因 - 如何使用生成的资源 - 任何前置条件或依赖
When to Skip Validation
何时跳过验证
Only skip validation when:
- Generating partial code snippets (not complete files)
- Creating examples for documentation purposes
- User explicitly requests to skip validation
仅在以下情况可跳过验证:
- 生成部分代码片段(非完整文件)
- 创建文档示例
- 用户明确要求跳过验证
Best Practices to Enforce
需遵循的最佳实践
Reference for comprehensive guidelines. Key principles:
references/best-practices.md详细指南请参考。核心原则:
references/best-practices.mdMandatory Standards
强制标准
-
FQCN (Fully Qualified Collection Names):
- ✅ Correct: ,
ansible.builtin.copycommunity.general.ufw - ❌ Wrong: ,
copyufw
- ✅ Correct:
-
Idempotency:
- All tasks must be safe to run multiple times
- Use declarations
state: present/absent - Avoid /
commandwhen builtin modules existshell - When using /
command, useshell,creates, orremoveschanged_when
-
Naming:
- Task names: Descriptive, start with verb ("Ensure", "Create", "Deploy")
- Variables: snake_case with descriptive names
- Role variables: Prefixed with role name
- Files: lowercase with underscores
-
Security:
- Use for sensitive operations
no_log: true - Set restrictive file permissions (600 for secrets, 644 for configs)
- Never commit passwords/secrets in plain text
- Reference ansible-vault for secrets management
- Use
-
Error Handling:
- Include conditionals for OS-specific tasks
when - Use to capture task results
register - Add and
failed_whenfor command moduleschanged_when - Include parameter for configuration files
validate
- Include
-
Performance:
- Disable fact gathering when not needed:
gather_facts: false - Use with
update_cachefor package managerscache_valid_time - Implement async tasks for long-running operations
- Disable fact gathering when not needed:
-
Documentation:
- Add header comments to playbooks with requirements and usage
- Document all variables with descriptions and defaults
- Include examples in role README files
-
FQCN(完全限定集合名称):
- ✅ 正确:、
ansible.builtin.copycommunity.general.ufw - ❌ 错误:、
copyufw
- ✅ 正确:
-
幂等性:
- 所有任务必须可安全多次执行
- 使用声明
state: present/absent - 存在内置模块时避免使用/
commandshell - 使用/
command时,配合shell、creates或removeschanged_when
-
命名规范:
- 任务名称:描述性强,以动词开头(如"确保"、"创建"、"部署")
- 变量:使用蛇形命名法(snake_case),名称具有描述性
- 角色变量:添加角色名称前缀
- 文件:小写,下划线分隔
-
安全规范:
- 敏感操作使用
no_log: true - 设置严格的文件权限(机密文件用600,配置文件用644)
- 切勿以明文形式提交密码/机密信息
- 参考ansible-vault进行机密信息管理
- 敏感操作使用
-
错误处理:
- 针对操作系统特定任务添加条件
when - 使用捕获任务结果
register - 为command模块添加和
failed_whenchanged_when - 为配置文件任务添加参数
validate
- 针对操作系统特定任务添加
-
性能优化:
- 不需要时禁用事实收集:
gather_facts: false - 为包管理器使用配合
update_cachecache_valid_time - 为长时间运行的操作实现异步任务
- 不需要时禁用事实收集:
-
文档规范:
- 为剧本添加包含要求和使用方法的头部注释
- 记录所有变量的描述和默认值
- 在角色README文件中包含示例
Module Selection Priority
模块选择优先级
IMPORTANT: Always prefer builtin modules over collection modules when possible. This ensures:
- Better validation compatibility (validation environments may not have collections installed)
- Fewer external dependencies
- More reliable playbook execution across environments
Priority Order:
- Builtin modules () - ALWAYS first choice
ansible.builtin.*- Check for builtin alternatives before using collections
references/module-patterns.md - Example: Use with
ansible.builtin.commandinstead ofpsqlif collection isn't essentialcommunity.postgresql.postgresql_db
- Check
- Official collection modules (verified collections) - Second choice, only when builtin doesn't exist
- Community modules () - Third choice
community.* - Custom modules - Last resort
- Avoid /
command- Only when no module alternative existsshell
重要提示: 存在内置模块时,优先使用内置模块而非集合模块。这确保:
- 更好的验证兼容性(验证环境可能未安装集合)
- 更少的外部依赖
- 在不同环境中更可靠的剧本执行
优先级顺序:
- 内置模块() - 始终是首选
ansible.builtin.*- 使用集合前,先检查是否有内置替代方案
references/module-patterns.md - 示例:如果集合不是必需的,使用配合
ansible.builtin.command而非psqlcommunity.postgresql.postgresql_db
- 使用集合前,先检查
- 官方集合模块(已验证集合)- 次选,仅当不存在内置模块时使用
- 社区模块()- 第三选择
community.* - 自定义模块 - 最后选择
- 避免使用/
command- 仅当没有模块替代方案时使用shell
Handling Collection Dependencies in Validation
验证中处理集合依赖
When validation fails due to missing collections (e.g., "couldn't resolve module/action"):
-
First, check if a builtin alternative exists:
- Many collection modules have equivalents
ansible.builtin.* - Example: Instead of , use
community.postgresql.postgresql_dbwithansible.builtin.commandcommandspsql - Example: Instead of , use
community.docker.docker_containerwithansible.builtin.commandCLIdocker
- Many collection modules have
-
If collection is required (no builtin alternative):
- Document the collection requirement clearly in the playbook header
- Add installation instructions in comments
- Consider providing both approaches (collection-based and builtin fallback)
-
If validation environment lacks collections:
- Rewrite tasks using modules with equivalent CLI commands
ansible.builtin.* - Use and
changed_when/createsfor idempotency with command modulesremoves - Document that the collection-based approach is preferred in production
- Rewrite tasks using
Example - Builtin fallback for PostgreSQL:
yaml
undefined当因缺少集合导致验证失败时(如"无法解析模块/操作"):
-
首先检查是否存在内置替代方案:
- 许多集合模块有等效模块
ansible.builtin.* - 示例:使用配合
ansible.builtin.command命令替代psqlcommunity.postgresql.postgresql_db - 示例:使用配合
ansible.builtin.commandCLI替代dockercommunity.docker.docker_container
- 许多集合模块有
-
如果必须使用集合(无内置替代方案):
- 在剧本头部清晰记录集合要求
- 在注释中添加安装说明
- 考虑同时提供两种实现方式(基于集合的方式和内置回退方式)
-
如果验证环境缺少集合:
- 使用模块配合等效CLI命令重写任务
ansible.builtin.* - 为command模块使用和
changed_when/creates确保幂等性removes - 记录在生产环境中优先使用基于集合的方式
- 使用
示例 - PostgreSQL的内置回退方案:
yaml
undefinedPreferred (requires community.postgresql collection):
首选方案(需要community.postgresql集合):
- name: Create database
- name: Create database
community.postgresql.postgresql_db:
community.postgresql.postgresql_db:
name: mydb
name: mydb
state: present
state: present
Builtin fallback (works without collection):
内置回退方案(无需集合即可运行):
-
name: Check if database exists ansible.builtin.command: cmd: psql -tAc "SELECT 1 FROM pg_database WHERE datname='mydb'" become: true become_user: postgres register: db_check changed_when: false
-
name: Create database ansible.builtin.command: cmd: psql -c "CREATE DATABASE mydb" become: true become_user: postgres when: db_check.stdout != "1" changed_when: true
undefined-
name: Check if database exists ansible.builtin.command: cmd: psql -tAc "SELECT 1 FROM pg_database WHERE datname='mydb'" become: true become_user: postgres register: db_check changed_when: false
-
name: Create database ansible.builtin.command: cmd: psql -c "CREATE DATABASE mydb" become: true become_user: postgres when: db_check.stdout != "1" changed_when: true
undefinedResources
资源
References (Load on Skill Invocation)
参考资料(调用技能时加载)
IMPORTANT: These reference files should be read at the start of generation to inform implementation decisions. Do not just rely on general knowledge - explicitly read the references to ensure current best practices are applied.
-
- Comprehensive Ansible best practices guide
references/best-practices.md- Directory structures, naming conventions, task writing
- Variables, handlers, templates, security
- Testing, performance optimization, common pitfalls
- When to read: At the start of generating any Ansible resource
- How to use: Extract relevant patterns for the specific resource type being generated
-
- Common module usage patterns and examples
references/module-patterns.md- Complete examples for all common ansible.builtin modules
- Collection module examples (docker, postgresql, etc.)
- Copy-paste ready code snippets
- When to read: When selecting modules for tasks
- How to use: Find the correct module and parameter syntax for the operation needed
重要提示: 这些参考文件应在生成开始时阅读,以指导实现决策。不要仅依赖通用知识 - 明确参考这些文件以确保遵循当前最佳实践。
-
- 全面的Ansible最佳实践指南
references/best-practices.md- 目录结构、命名规范、任务编写
- 变量、处理器、模板、安全
- 测试、性能优化、常见陷阱
- 阅读时机: 生成任何Ansible资源前
- 使用方式: 提取与当前生成资源类型相关的模式
-
- 常见模块使用模式和示例
references/module-patterns.md- 所有常用ansible.builtin模块的完整示例
- 集合模块示例(docker、postgresql等)
- 可直接复制使用的代码片段
- 阅读时机: 为任务选择模块时
- 使用方式: 查找操作所需的正确模块和参数语法
Assets (Templates as Reference Structures)
资源文件(作为参考结构的模板)
Templates serve as structural references showing the expected format and organization. You do NOT need to literally copy and paste them - use them as guides for the correct structure, sections, and patterns.
- - Reference playbook structure
assets/templates/playbook/basic_playbook.yml- Shows: pre_tasks, tasks, post_tasks, handlers organization
- Shows: Header documentation format
- Shows: Variable declaration patterns
- - Reference role directory structure
assets/templates/role/*- Shows: Required files and their organization
- Shows: Variable naming conventions
- - Role variable validation (Ansible 2.11+)
meta/argument_specs.yml
- - Reference inventory organization
assets/templates/inventory/*- Shows: Host grouping patterns
- Shows: group_vars/host_vars structure
- - Reference project configuration
assets/templates/project/*- - Project-level Ansible configuration
ansible.cfg - - Collections and roles dependencies
requirements.yml - - Linting rules configuration
.ansible-lint
How to use templates:
- Review the relevant template to understand the expected structure
- Generate content following the same organizational pattern
- Replace all with actual values appropriate for the task
[PLACEHOLDERS] - Customize logic based on user requirements
- Remove unnecessary sections that don't apply
- Validate the result using devops-skills:ansible-validator skill
模板作为结构参考,展示预期的格式和组织方式。无需逐字复制粘贴 - 将其作为正确结构、部分和模式的指南。
- - 参考剧本结构
assets/templates/playbook/basic_playbook.yml- 展示:pre_tasks、tasks、post_tasks、handlers的组织方式
- 展示:头部文档格式
- 展示:变量声明模式
- - 参考角色目录结构
assets/templates/role/*- 展示:必需文件及其组织方式
- 展示:变量命名规范
- - 角色变量验证(Ansible 2.11+)
meta/argument_specs.yml
- - 参考清单组织方式
assets/templates/inventory/*- 展示:主机分组模式
- 展示:group_vars/host_vars结构
- - 参考项目配置
assets/templates/project/*- - 项目级Ansible配置
ansible.cfg - - 集合和角色依赖
requirements.yml - - 代码检查规则配置
.ansible-lint
模板使用方法:
- 查看相关模板以了解预期结构
- 生成内容时遵循相同的组织模式
- 替换所有为适合任务的实际值
[PLACEHOLDERS] - 自定义基于用户需求的逻辑
- 移除不适用的部分
- 验证结果使用devops-skills:ansible-validator工具
Typical Workflow Example
典型工作流示例
User request: "Create a playbook to deploy nginx with SSL"
Process:
-
✅ Understand requirements:
- Deploy nginx web server
- Configure SSL/TLS
- Ensure service is running
- Target: Linux servers (Ubuntu/RHEL)
-
✅ Reference resources:
- Check for playbook structure
references/best-practices.md - Check for nginx-related modules
references/module-patterns.md - Use as base
assets/templates/playbook/basic_playbook.yml
- Check
-
✅ Generate playbook:
- Use FQCN for all modules
- Include OS-specific conditionals
- Add SSL configuration tasks
- Include validation and health checks
- Add proper tags and handlers
-
✅ Validate:
- Invoke skill
devops-skills:ansible-validator - Fix any reported issues
- Re-validate if needed
- Invoke
-
✅ Present to user:
- Show validated playbook
- Explain key sections
- Provide usage instructions
- Mention successful validation
用户请求: "创建一个部署带SSL的nginx的剧本"
流程:
-
✅ 理解需求:
- 部署nginx web服务器
- 配置SSL/TLS
- 确保服务运行
- 目标:Linux服务器(Ubuntu/RHEL)
-
✅ 参考资源:
- 查看获取剧本结构
references/best-practices.md - 查看获取nginx相关模块
references/module-patterns.md - 以为基础
assets/templates/playbook/basic_playbook.yml
- 查看
-
✅ 生成剧本:
- 所有模块使用FQCN
- 包含操作系统特定条件
- 添加SSL配置任务
- 包含验证和健康检查
- 添加合适的标签和处理器
-
✅ 验证:
- 调用工具
devops-skills:ansible-validator - 修复任何报告的问题
- 必要时重新验证
- 调用
-
✅ 交付给用户:
- 展示已验证的剧本
- 解释关键部分
- 提供使用说明
- 提及验证成功
Common Patterns
常见模式
Multi-OS Support
多操作系统支持
yaml
- name: Install nginx (Debian/Ubuntu)
ansible.builtin.apt:
name: nginx
state: present
when: ansible_os_family == "Debian"yaml
- name: Install nginx (Debian/Ubuntu)
ansible.builtin.apt:
name: nginx
state: present
when: ansible_os_family == "Debian"NOTE: For RHEL 8+, use ansible.builtin.dnf instead of yum
注意:对于RHEL 8+,使用ansible.builtin.dnf而非yum
ansible.builtin.yum is deprecated in favor of dnf for modern RHEL/CentOS
对于现代RHEL/CentOS,ansible.builtin.yum已被dnf取代
- name: Install nginx (RHEL 8+/CentOS 8+) ansible.builtin.dnf: name: nginx state: present when: ansible_os_family == "RedHat"
undefined- name: Install nginx (RHEL 8+/CentOS 8+) ansible.builtin.dnf: name: nginx state: present when: ansible_os_family == "RedHat"
undefinedTemplate Deployment with Validation
带验证的模板部署
yaml
- name: Deploy configuration
ansible.builtin.template:
src: app_config.j2
dest: /etc/app/config.yml
mode: '0644'
backup: true
validate: '/usr/bin/app validate %s'
notify: Restart applicationyaml
- name: Deploy configuration
ansible.builtin.template:
src: app_config.j2
dest: /etc/app/config.yml
mode: '0644'
backup: true
validate: '/usr/bin/app validate %s'
notify: Restart applicationAsync Long-Running Tasks
异步长时间运行任务
yaml
- name: Run database migration
ansible.builtin.command: /opt/app/migrate.sh
async: 3600
poll: 0
register: migration
- name: Check migration status
ansible.builtin.async_status:
jid: "{{ migration.ansible_job_id }}"
register: job_result
until: job_result.finished
retries: 360
delay: 10yaml
- name: Run database migration
ansible.builtin.command: /opt/app/migrate.sh
async: 3600
poll: 0
register: migration
- name: Check migration status
ansible.builtin.async_status:
jid: "{{ migration.ansible_job_id }}"
register: job_result
until: job_result.finished
retries: 360
delay: 10Conditional Execution
条件执行
yaml
- name: Configure production settings
ansible.builtin.template:
src: production.j2
dest: /etc/app/config.yml
when:
- env == "production"
- ansible_distribution == "Ubuntu"yaml
- name: Configure production settings
ansible.builtin.template:
src: production.j2
dest: /etc/app/config.yml
when:
- env == "production"
- ansible_distribution == "Ubuntu"Error Messages and Troubleshooting
错误信息与故障排除
If devops-skills:ansible-validator reports errors:
如果devops-skills:ansible-validator报告错误:
- Syntax errors: Fix YAML formatting, indentation, or structure
- Lint warnings: Address best practice violations (FQCN, naming, etc.)
- Undefined variables: Add variable definitions or defaults
- Module not found: Check FQCN or add collection requirements
- Task failures in check mode: Add for tasks that must run
check_mode: no
- 语法错误: 修复YAML格式、缩进或结构
- Lint警告: 解决最佳实践违规问题(FQCN、命名等)
- 未定义变量: 添加变量定义或默认值
- 模块未找到: 检查FQCN或添加集合要求
- 检查模式下任务失败: 为必须运行的任务添加
check_mode: no
If custom module/collection documentation is not found:
如果未找到自定义模块/集合的文档:
- Try alternative search queries with different versions
- Check official Ansible Galaxy for collection
- Look for module in ansible-collections GitHub org
- Consider using alternative builtin modules
- Ask user if they have specific version requirements
- 尝试使用不同版本的替代搜索查询
- 检查官方Ansible Galaxy获取集合信息
- 在ansible-collections GitHub组织中查找模块
- 考虑使用替代内置模块
- 询问用户是否有特定版本要求
Final Checklist (MANDATORY)
最终检查清单(强制要求)
Before presenting any generated Ansible resource to the user, verify all items:
- Reference files read - Consulted and
references/best-practices.mdreferences/module-patterns.md - FQCN used - All modules use fully qualified names (, not bare names)
ansible.builtin.* - Booleans correct - Use /
true(NOTfalse/yes) to pass ansible-lintno - RHEL 8+ - Use (NOT
ansible.builtin.dnf) for modern RHEL/CentOSansible.builtin.yum - Idempotent - All tasks safe to run multiple times
- Security - on sensitive tasks, proper file permissions
no_log: true - Validated - devops-skills:ansible-validator skill invoked and passed
- Formal presentation - Output formatted per template below
在向用户交付任何生成的Ansible资源前,验证所有项目:
- 已阅读参考文件 - 查阅了和
references/best-practices.mdreferences/module-patterns.md - 使用了FQCN - 所有模块使用完全限定名称(,而非简称)
ansible.builtin.* - 布尔值正确 - 使用/
true(而非false/yes)以通过ansible-lintno - RHEL 8+支持 - 对于现代RHEL/CentOS,使用(而非
ansible.builtin.dnf)ansible.builtin.yum - 幂等性 - 所有任务可安全多次执行
- 安全性 - 敏感任务使用,设置正确的文件权限
no_log: true - 已验证 - 已调用devops-skills:ansible-validator工具且验证通过
- 规范呈现 - 输出符合以下模板格式
Required Output Format
必需输出格式
After validation passes, ALWAYS present results in this exact format:
markdown
undefined验证通过后,始终以以下精确格式呈现结果:
markdown
undefinedGenerated [Resource Type]: [Name]
生成的[资源类型]:[名称]
Validation Status: ✅ All checks passed
- YAML syntax: Passed
- Ansible syntax: Passed
- Ansible lint: Passed
Summary:
- [Brief description of what was generated]
- [Key features/sections included]
- [Any notable implementation decisions]
Usage:
bash
[Exact command to run the playbook/role]Prerequisites:
- [Any required collections or dependencies]
- [Target system requirements]
---验证状态: ✅ 所有检查通过
- YAML语法:通过
- Ansible语法:通过
- Ansible lint:通过
摘要:
- [生成内容的简要描述]
- [包含的关键功能/部分]
- [任何值得注意的实现决策]
使用方法:
bash
[运行剧本/角色的确切命令]前置条件:
- [任何必需的集合或依赖]
- [目标系统要求]
---Summary
总结
Always follow this sequence when generating Ansible resources:
- Understand - Clarify user requirements
- Reference - Check best-practices.md and module-patterns.md
- Generate - Use templates and follow standards (FQCN, idempotency, naming)
- Search - For custom modules/collections, use WebSearch to get current docs
- Validate - ALWAYS use devops-skills:ansible-validator skill
- Fix - Resolve any validation errors
- Present - Deliver validated, production-ready Ansible code
Generate Ansible resources that are:
- ✅ Idempotent and safe to run multiple times
- ✅ Following current best practices and naming conventions
- ✅ Using FQCN for all modules
- ✅ Properly documented with usage instructions
- ✅ Validated and lint-clean
- ✅ Production-ready and maintainable
生成Ansible资源时请始终遵循以下流程:
- 理解 - 明确用户需求
- 参考 - 查阅best-practices.md和module-patterns.md
- 生成 - 使用模板并遵循标准(FQCN、幂等性、命名)
- 搜索 - 对于自定义模块/集合,使用WebSearch获取最新文档
- 验证 - 始终使用devops-skills:ansible-validator工具
- 修复 - 解决所有验证错误
- 交付 - 交付已验证、可用于生产环境的Ansible代码
生成的Ansible资源应具备以下特性:
- ✅ 幂等性,可安全多次执行
- ✅ 遵循当前最佳实践和命名规范
- ✅ 所有模块使用FQCN
- ✅ 包含完善的使用说明文档
- ✅ 已验证且符合代码规范
- ✅ 可用于生产环境且易于维护