Playbook: 操作
2025-02-17
条件语句
when 语句用于控制任务的执行条件。支持使用 Ansible facts、注册变量和自定义变量进行判断。
单一条件
使用单个条件判断:
tasks:
- name: 安装 Apache
yum: name=httpd state=present
when: ansible_os_family == "RedHat"多重条件
支持使用多个条件组合:
tasks:
# 使用 and 条件(隐式)
- name: 配置 CentOS 7 服务
template: src=service.conf.j2 dest=/etc/service.conf
when:
- ansible_distribution == "CentOS"
- ansible_distribution_major_version == "7"
# 使用 or 条件
- name: 安装 RHEL 系包
yum: name=httpd state=present
when: >
ansible_distribution == "CentOS" or
ansible_distribution == "RedHat"
# 使用 not 条件
- name: 非 Debian 系统跳过
debug: msg="不是 Debian"
when: not ansible_os_family == "Debian"注册变量条件
tasks:
- name: 检查服务状态
command: systemctl status httpd
register: service_status
- name: 重启服务
service: name=httpd state=restarted
when:
- service_status.rc != 0变量存在性检查
# 设置变量
vars:
db_password: "your_secure_password"
tasks:
- name: 配置数据库 # 任务描述
template: # 使用模板模块
src: db.conf.j2 # 源模板文件
dest: /etc/db.conf # 目标配置文件
when: db_password is defined # 执行条件:db_password变量已定义循环语句
基本循环
with_items 用于遍历列表项,常用于:
- 批量安装软件包
- 创建多个用户/目录
- 复制多个文件
tasks:
- name: 安装多个包
yum: name={{ item }} state=present
with_items:
- httpd
- php
- mysql-server字典循环
with_dict 用于遍历字典数据,可以:
- 访问键值对
- 处理嵌套数据
- 配置复杂选项
tasks:
- name: 创建用户
user:
name: "{{ item.key }}"
groups: "{{ item.value.groups }}"
shell: "{{ item.value.shell }}"
with_dict:
admin:
groups: wheel
shell: /bin/bash
dev:
groups: developers
shell: /bin/zsh文件匹配循环
with_fileglob 用于文件操作:
- 匹配文件模式
- 批量处理文件
- 支持通配符
tasks:
- name: 复制配置文件
copy:
src: "{{ item }}"
dest: /etc/app/
with_fileglob:
- "files/*.conf"
- "templates/*.j2"序列循环
with_sequence 生成数字序列:
- 指定起始值
- 设置结束值
- 定义步长
tasks:
- name: 创建多个目录
file:
path: "/data/dir{{ item }}"
state: directory
with_sequence: start=1 end=5 stride=1错误处理
忽略错误
tasks:
- name: 尝试操作
command: /bin/false
ignore_errors: yes条件判断
tasks:
- name: 检查服务状态
command: systemctl status httpd
register: result
failed_when: "'active' not in result.stdout"块错误处理
tasks:
- block:
- name: 安装应用
yum: name=app state=present
- name: 启动服务
service: name=app state=started
rescue:
- name: 清理安装
yum: name=app state=absent
always:
- name: 通知管理员
mail:
to: admin@example.com
subject: 部署状态任务控制
标签(Tags)
tasks:
- name: 安装包
yum: name=httpd state=present
tags: install
- name: 配置服务
template: src=httpd.conf.j2 dest=/etc/httpd.conf
tags:
- config
- httpd任务委派
tasks:
- name: 添加到负载均衡
shell: /usr/local/bin/add_to_lb.sh {{ inventory_hostname }}
delegate_to: localhost任务超时
tasks:
- name: 长时间运行的任务
command: /usr/bin/long_running_operation
async: 3600 # 1小时超时
poll: 0 # 立即返回最佳实践
任务设计
- 保持任务幂等性
- 合理使用条件判断
- 适当处理错误
代码组织
- 使用有意义的标签
- 合理分组任务
- 注意执行顺序
错误处理
- 使用 block/rescue
- 设置合理超时
- 记录错误信息
注意:
- 避免过度复杂的条件
- 谨慎使用 ignore_errors
- 合理使用任务委派
参考资料: