1. 操作系统系列 (ansible_os_family)
ansible web -m setup -a 'filter=ansible_os_family'
2. 操作系统家族为 RedHat 时执行任务
--- - hosts: websrvsremote_user: roottasks:- name: Install package on RedHat systemsyum:name: httpdstate: presentwhen: ansible_os_family == "RedHat"
- 这个任务会在操作系统家族为
RedHat
的系统上安装httpd
包。
3. 操作系统家族为 Debian 时执行任务
--- - hosts: websrvsremote_user: roottasks:- name: Install package on Debian systemsapt:name: apache2state: presentwhen: ansible_os_family == "Debian"
- 这个任务会在操作系统家族为
Debian
的系统上安装apache2
包。
4. 操作系统为 RedHat 或 Debian 时执行任务
--- - hosts: websrvsremote_user: roottasks:- name: Install common package on RedHat and Debian systemspackage:name: vimstate: presentwhen: ansible_os_family in ["RedHat", "Debian"]
- 这个任务会在操作系统家族为
RedHat
或Debian
的系统上安装vim
包。
5. 操作系统为 Ubuntu 时执行任务
--- - hosts: websrvsremote_user: roottasks:- name: Install package on Ubuntu systemsapt:name: nginxstate: presentwhen: ansible_distribution == "Ubuntu"
- 这个任务会在操作系统为
Ubuntu
的系统上安装nginx
包。
6. 特定版本的操作系统执行任务
--- - hosts: websrvsremote_user: roottasks:- name: Install package on CentOS 8yum:name: httpdstate: presentwhen: ansible_distribution == "CentOS" and ansible_distribution_version == "8"
- 这个任务会在
CentOS 8
系统上安装httpd
包。
7. 操作系统家族为 Suse 时执行任务
--- - hosts: websrvsremote_user: roottasks:- name: Install package on Suse systemszypper:name: apache2state: presentwhen: ansible_os_family == "Suse"
- 这个任务会在操作系统家族为
Suse
的系统上安装apache2
包。
8. 检测操作系统是否为 Windows 系统
--- - hosts: windows_machinesremote_user: Administratortasks:- name: Install IIS on Windowswin_chocolatey:name: iisstate: presentwhen: ansible_os_family == "Windows"
- 这个任务会在操作系统家族为
Windows
的系统上安装 IIS。
9. 操作系统家族不为 RedHat 时执行任务
---
- hosts: websrvs
remote_user: root
tasks:
- name: Install package on non-RedHat systems
apt:
name: nginx
state: present
when: ansible_os_family != "RedHat"
- 这个任务会在操作系统家族不为
RedHat
的系统上安装nginx
包。
10. 根据操作系统家族执行不同的配置
---
- hosts: websrvs
remote_user: root
tasks:
- name: Configure firewall on RedHat systems
firewalld:
service: http
permanent: yes
state: enabled
when: ansible_os_family == "RedHat"- name: Configure firewall on Debian systems
ufw:
rule: allow
name: 'Apache'
when: ansible_os_family == "Debian"
- 这个任务根据操作系统家族来执行不同的防火墙配置:
RedHat
使用firewalld
,Debian
使用ufw
。