Ansible 是一款开源的自动化运维工具,由 Red Hat 公司维护,主要用于配置管理、应用部署、任务自动化等场景。
# Ubuntu/Debian
sudo apt update
sudo apt install -y ansible
# CentOS/RHEL
sudo yum install -y epel-release
sudo yum install -y ansible
# macOS
brew install ansible
主配置文件通常位于 /etc/ansible/ansible.cfg
,可以创建 ~/.ansible.cfg
进行个性化配置:
[defaults]
inventory = ./hosts
remote_user = root
private_key_file = ~/.ssh/id_rsa
host_key_checking = False
创建 hosts
文件:
[web]
web1.example.com ansible_host=192.168.1.101
web2.example.com ansible_host=192.168.1.102
[db]
db1.example.com ansible_host=192.168.1.201
[all:vars]
ansible_user=admin
ansible_ssh_private_key_file=~/.ssh/admin_key
# 测试所有主机的连通性
ansible all -m ping
# 查看所有主机的磁盘空间
ansible all -a "df -h"
# 在 web 组主机上安装 nginx
ansible web -b -m apt -a "name=nginx state=present"
创建 webserver.yml
:
---
- name: Configure web server
hosts: web
become: yes
vars:
nginx_port: 8080
tasks:
- name: Install nginx
apt:
name: nginx
state: latest
update_cache: yes
- name: Configure nginx
template:
src: templates/nginx.conf.j2
dest: /etc/nginx/sites-available/default
notify:
- restart nginx
- name: Ensure nginx is running
service:
name: nginx
state: started
enabled: yes
handlers:
- name: restart nginx
service:
name: nginx
state: restarted
创建角色结构:
ansible-galaxy init roles/webserver
目录结构:
roles/webserver/
├── defaults
│ └── main.yml
├── files
├── handlers
│ └── main.yml
├── meta
│ └── main.yml
├── tasks
│ └── main.yml
├── templates
└── vars
└── main.yml
变量使用:
vars:
app_version: "1.2.3"
db_config:
host: "db.example.com"
port: 3306
条件执行:
tasks:
- name: Install package on Debian
apt:
name: "{{ package_name }}"
state: present
when: ansible_os_family == "Debian"
循环:
tasks:
- name: Add multiple users
user:
name: "{{ item }}"
state: present
groups: "wheel"
loop:
- alice
- bob
- charlie
--check
和 --diff
选项进行测试# 测试主机连接
ansible all -m ping
# 执行临时命令
ansible web -a "uptime"
# 运行 Playbook
ansible-playbook site.yml
# 列出所有主机
ansible all --list-hosts
# 检查 Playbook 语法
ansible-playbook --syntax-check playbook.yml
# 测试运行(不实际执行)
ansible-playbook --check playbook.yml
Ansible 提供了一种简单而强大的方式来自动化 IT 基础设施管理。通过 Playbook 和 Roles,可以实现复杂运维任务的标准化和自动化,显著提高运维效率和可靠性。