1. 什么是 Ansible?
ansible 命令行、inventory 主机清单、playbook 剧本文件2.安装
# 安装 Ansible(CentOS/Ubuntu)
yum install ansible # CentOS
apt-get install ansible # Ubuntu
# 查看版本
ansible --version3. 定义要操作的主机(inventory)
在 ~/ansible/inventory 或其他路径 中定义主机分组:
# 示例 inventory 文件
[web_servers]
192.168.1.10 ansible_ssh_user=test
192.168.1.11
[db_servers]
192.168.1.20
[all_servers:children] # 合并组
web_servers
db_serversAd-Hoc 模式用于快速执行一次性任务,格式:
ansible [主机组] -m [模块] -a "[参数]"
# 对单个主机执行 ping
ansible web01 -i inventory -m ping
# 对 web_servers 组执行 ping
ansible web_servers -i inventory -m ping
# 对所有主机执行 ping(-a 参数传递额外参数)
ansible all -i inventory -m ping -a "data=hello"
# 指定绝对路径
ansible web_servers -i /path/to/my_inventory -m ping
# 查看所有服务器的系统时间
ansible all -m shell -a "date"
# 检查磁盘空间
ansible web_servers -m shell -a "df -h | grep /dev/sda1"
# 重启服务
ansible db_servers -m shell -a "systemctl restart mysql"输出示例:
192.168.1.10 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"}, "ping": "pong"}# 复制本地文件到远程主机
ansible web_servers -i inventory -m copy -a "src=/local/file.txt dest=/remote/path/"
# 写入内容到远程文件(支持模板变量)
ansible db_servers -i inventory -m copy -a "content='hello ansible' dest=/tmp/message.txt"
# 复制时设置权限
ansible all_servers -i inventory -m copy -a "src=/local/script.sh dest=/usr/bin/ mode=0755"# 在 web_servers 组中执行 ls 命令
ansible web_servers -i inventory -a "ls -la /etc"
# 在 db_servers 组中查看磁盘空间
ansible db_servers -i inventory -a "df -h"
# 对所有服务器执行 date 命令(-f 参数指定并发数,默认 5)
ansible all -i inventory -a "date" -f 10Playbook 是 Ansible 的核心,使用 YAML 格式定义任务流程。
以下是针对安装特定版本 Playwright (v1.51.0) 的 Ansible Playbook
创建 install_playwright.yml:
- name:安装与更新Playwright测试库
hosts:web_servers
become:true
vars:
target_playwright_version:"1.51.0"
tasks:
# 1. 检查当前安装版本
-name:获取已安装的Playwright版本
ansible.builtin.command:"pip3 show playwright | grep Version"
register:playwright_version
changed_when:false
ignore_errors:yes
# 2. 安装/更新指定版本 Playwright
-name:安装指定版本Playwright
ansible.builtin.pip:
name:playwright
version:"{{ target_playwright_version }}"
executable:pip3
register:install_result
when:
-"'Version: {{ target_playwright_version }}' not in playwright_version.stdout"
notify:安装浏览器依赖
handlers:
# 3. 安装浏览器(仅在库版本变更时执行)
-name:安装浏览器依赖
ansible.builtin.command:"playwright install --with-deps"
args:
chdir:"/home/test"
environment:
PATH: "/usr/local/bin:/usr/bin:/bin"执行逻辑:
# 执行 playbook(-v 显示详细日志)
ansible-playbook install_playwright.yml -i inventory -v1.
# 生成 SSH 密钥对
ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_ansible
# 分发公钥到远程主机
ansible all -i inventory -a "mkdir -p ~/.ssh"
ansible all -i inventory -a "chmod 700 ~/.ssh"
ansible all -i inventory -m copy -a "src=~/.ssh/id_ansible.pub dest=~/.ssh/authorized_keys mode=0600"当 Playwright 在百台服务器上绽放 —这些用命令行织就的自动化诗篇,终将成为测试人最浪漫的运维魔法。