生成、审查并优化 Ansible 自动化脚本;在用户提及 Ansible、playbook、角色、清单、任务、处理器等情况时使用本技能。
Ansible Skill.是一项面向实际任务的技能,主要用于A 生成生产级Ansble自动化的技巧:游戏本,角色,目录,.;Jinja2模板,可变文件,以及官后完整的项目结构.bes.。
从功能定位来看,该技能强调把分散的操作要求整理成清晰、可复用的处理流程,使用户能够围绕既定目标快速准备输入、选择执行方式并获得结构化结果。实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;
若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;涉及批量任务时,还应保存进度,避免中断后重复操作。
一项用于生成生产级 Ansible 自动化内容的技能:Playbook、Role、Inventory、Jinja2 模板、变量文件,以及遵循官方最佳实践的完整项目结构。
1. 明确意图 → 理解目标操作系统、任务类型、规模、幂等性需求 2. 选择输出类型 → Playbook / Role / Inventory / 模板 / 完整项目 3. 生成制品 → 生成嵌入最佳实践的 YAML 文件 4. 验证与注释 → 添加 lint 提示、--check 命令及幂等性说明 5. 输出结构 → 清晰展示文件路径与执行指令
生成前需收集以下信息(上下文明确时可自动推断):
| 参数 | 说明 | 示例 |
|---|---|---|
target_os |
被管主机的操作系统家族 | Ubuntu 22.04, RHEL 9 |
task_type |
需自动化的操作类型 | deploy app, manage users |
connection_type |
Ansible 的连接方式 | SSH(默认)、WinRM |
privilege |
是否需要 sudo/become 权限? | yes / no |
scale |
主机/主机组数量 | 3 webservers, 1 DB |
idempotency |
是否必须支持重复安全执行? | yes(始终推荐) |
var_source |
变量来源 | group_vars, vault, extra |
若上下文已足够清晰,可跳过交互式确认,直接生成。
适用场景:临时任务、简单自动化、一次性操作。
模板:
--- # playbooks/.yml - name: <描述性 Play 名称> hosts: become: true gather_facts: true vars: app_port: 8080 app_user: deploy pre_tasks: - name: Ensure required packages are present ansible.builtin.package: name: "{{ item }}" state: present loop: - curl - git roles: - role: when: ansible_os_family == "Debian" tasks: - name: Task description (use verb + object) ansible.builtin.module: param: value notify: Restart service tags: - setup - deploy handlers: - name: Restart service ansible.builtin.service: name: state: restarted
规则:
ansible.builtin.copy,而非 copystate: present/absent 保证幂等性tags,支持选择性执行notify + handler 实现(禁止在 task 中内联重启)loop 而非已弃用的 with_items适用场景:可复用、可共享、可测试的自动化单元。
目录结构:
roles// ├── defaults/ │ └── main.yml # 低优先级默认值(可被覆盖) ├── vars/ │ └── main.yml # 高优先级 Role 内部变量 ├── tasks/ │ ├── main.yml # 入口文件(按 OS/功能 import_tasks) │ ├── install.yml │ ├── configure.yml │ └── service.yml ├── handlers/ │ └── main.yml ├── templates/ │ └── .conf.j2 ├── files/ │ └── ├── meta/ │ └── main.yml # Galaxy 元数据与依赖声明 └── README.md
tasks/main.yml 模式:
---
- name: Include OS-specific variables
ansible.builtin.include_vars: "{{ ansible_os_family }}.yml"
failed_when: false
- ansible.builtin.import_tasks: install.yml
tags: [install]
- ansible.builtin.import_tasks: configure.yml
tags: [configure]
- ansible.builtin.import_tasks: service.yml
tags: [service]
defaults/main.yml 模式:
--- # Role:# All variables with safe defaults role_package_name: nginx role_service_name: nginx role_config_path: /etc/nginx/nginx.conf role_user: www-data role_port: 80 role_enabled: true
静态 Inventory(INI 格式):
# inventory/hosts [webservers] web01.example.com ansible_host=10.0.1.10 web02.example.com ansible_host=10.0.1.11 [databases] db01.example.com ansible_host=10.0.2.10 [loadbalancers] lb01.example.com [production:children] webservers databases loadbalancers [all:vars] ansible_user=deploy ansible_ssh_private_key_file=~/.ssh/id_rsa ansible_python_interpreter=/usr/bin/python3
静态 Inventory(YAML 格式 — 推荐):
# inventory/hosts.yml
all:
vars:
ansible_user: deploy
ansible_python_interpreter: /usr/bin/python3
children:
webservers:
hosts:
web01:
ansible_host: 10.0.1.10
http_port: 80
web02:
ansible_host: 10.0.1.11
http_port: 80
databases:
hosts:
db01:
ansible_host: 10.0.2.10
db_port: 5432
staging:
children:
webservers:
databases:
group_vars 目录结构:
inventory/
├── hosts.yml
├── group_vars/
│ ├── all.yml # 应用于所有主机
│ ├── all/
│ │ ├── vars.yml
│ │ └── vault.yml # ansible-vault 加密的敏感信息
│ ├── webservers.yml
│ └── databases.yml
└── host_vars/
└── web01.yml
配置文件模板模式:
{# templates/nginx.conf.j2 #}
{# Managed by Ansible - Do not edit manually #}
user {{ nginx_user | default('www-data') }};
worker_processes {{ nginx_worker_processes | default(ansible_processor_vcpus) }};
events {
worker_connections {{ nginx_worker_connections | default(1024) }};
}
http {
include mime.types;
default_type application/octet-stream;
{% if nginx_log_format is defined %}
log_format main '{{ nginx_log_format }}';
{% endif %}
{% for vhost in nginx_vhosts | default([]) %}
server {
listen {{ vhost.port | default(80) }};
server_name {{ vhost.name }};
root {{ vhost.root }};
{% if vhost.ssl | default(false) %}
listen 443 ssl;
ssl_certificate {{ vhost.ssl_cert }};
ssl_certificate_key {{ vhost.ssl_key }};
{% endif %}
}
{% endfor %}
}
Jinja2 关键模式:
{# 默认值过滤器 #}
{{ variable | default('fallback_value') }}
{# 条件块 #}
{% if ansible_os_family == "Debian" %}
apt_cache_valid_time: 3600
{% elif ansible_os_family == "RedHat" %}
yum_releasever: latest
{% endif %}
{# 遍历字典 #}
{% for key, value in config_dict.items() %}
{{ key }} = {{ value }}
{% endfor %}
{# 列表拼接 #}
{{ my_list | join(', ') }}
{# 大写 / 替换 #}
{{ service_name | upper | replace('-', '_') }}
变量优先级顺序(高 → 低):
extra vars (-e) # 最高优先级 task vars block vars role and include vars play vars host facts host_vars group_vars/all role defaults # 最低优先级
vault.yml 模式(存放敏感数据):
# group_vars/all/vault.yml # Encrypt with: ansible-vault encrypt vault.yml vault_db_password: "super_secret_password" vault_api_key: "abc123xyz" vault_ssl_cert_content: | -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----
vars.yml(引用 vault 中的变量):
# group_vars/all/vars.yml
db_password: "{{ vault_db_password }}"
api_key: "{{ vault_api_key }}"
[defaults] inventory = ./inventory/hosts.yml roles_path = ./roles:~/.ansible/roles collections_paths = ./collections:~/.ansible/collections remote_user = deploy private_key_file = ~/.ssh/id_rsa host_key_checking = False retry_files_enabled = False stdout_callback = yaml callbacks_enabled = profile_tasks, timer interpreter_python = auto_silent # 性能调优 forks = 10 pipelining = True gathering = smart fact_caching = jsonfile fact_caching_connection = /tmp/ansible_facts fact_caching_timeout = 3600 [privilege_escalation] become = True become_method = sudo become_user = root become_ask_pass = False [ssh_connection] ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s control_path_dir = /tmp/.ansible/cp
对于完整项目,请生成如下布局:
/ ├── ansible.cfg ├── requirements.yml # Galaxy roles/collections 依赖声明 ├── site.yml # 主 Playbook ├── playbooks/ │ ├── deploy.yml │ ├── rollback.yml │ └── maintenance.yml ├── roles/ │ └── / # 见上方 Role 骨架定义 ├── inventory/ │ ├── production/ │ │ ├── hosts.yml │ │ ├── group_vars/ │ │ └── host_vars/ │ └── staging/ │ ├── hosts.yml │ └── group_vars/ ├── collections/ │ └── requirements.yml ├── filter_plugins/ # 自定义 Jinja2 过滤器 ├── library/ # 自定义模块 └── .github/ └── workflows/ └── ansible-lint.yml # CI 验证流程
requirements.yml:
---
collections:
- name: community.general
version: ">=7.0.0"
- name: ansible.posix
- name: community.docker
version: "3.4.0"
roles:
- name: geerlingguy.nodejs
version: "6.1.0"
- src: https://github.com/org/role.git
scm: git
version: main
name: custom_role
所有生成内容末尾均须附加以下说明:
语法检查:
ansible-playbook playbooks/deploy.yml --syntax-check
模拟运行(不实际变更):
ansible-playbook playbooks/deploy.yml --check --diff
代码规范检查(需安装 ansible-lint):
pip install ansible-lint ansible-lint playbooks/deploy.yml
使用 Vault 执行:
ansible-playbook playbooks/deploy.yml --ask-vault-pass # 或指定 vault 密码文件: ansible-playbook playbooks/deploy.yml --vault-password-file ~/.vault_pass
限制执行范围(特定主机/主机组):
ansible-playbook site.yml --limit webservers ansible-playbook site.yml --limit web01.example.com
执行特定标签的任务:
ansible-playbook site.yml --tags deploy,configure ansible-playbook site.yml --skip-tags debug
Ad-hoc 命令示例:
# Ping 所有主机 ansible all -m ping # 收集主机事实 ansible webservers -m ansible.builtin.setup # 执行 Shell 命令 ansible databases -m ansible.builtin.shell -a "df -h" # 复制文件 ansible all -m ansible.builtin.copy -a "src=file.conf dest=/etc/file.conf"
务必始终遵循以下原则:
ansible.builtin.copy,而非 copystate:shell/commandshell/command 类任务必须设置when 表达式,而非 shell 条件语句# Managed by Ansible| 任务 | 模块 |
|---|---|
| 安装软件包 | ansible.builtin.package |
| 复制文件 | ansible.builtin.copy |
| 渲染模板文件 | ansible.builtin.template |
| 管理服务 | ansible.builtin.service |
| 管理用户 | ansible.builtin.user |
| 执行命令 | ansible.builtin.command |
| 执行 Shell 命令 | ansible.builtin.shell |
| 管理文件/目录 | ansible.builtin.file |
| 编辑文件中的某行 | ansible.builtin.lineinfile |
| 下载文件 | ansible.builtin.get_url |
| 解压归档包 | ansible.builtin.unarchive |
| 管理定时任务 | ansible.builtin.cron |
| 管理防火墙 | ansible.posix.firewalld |
| Docker 容器管理 | community.docker.docker_container |
| Git 克隆 | ansible.builtin.git |
| 等待条件满足 | ansible.builtin.wait_for |
| 设置自定义 Fact | ansible.builtin.set_fact |
| 断言条件成立 | ansible.builtin.assert |
| 导入变量文件 | ansible.builtin.include_vars |
| 调试输出 | ansible.builtin.debug |
交付 Ansible 制品时请遵守:
# comment相关专题
热门下载
相关下载
精品课程
共6课时 | 54.7万人学习
共89课时 | 134.3万人学习
共49课时 | 82.7万人学习
最新文章