引言

Ansible是简单强大的自动化运维工具。本文介绍Ansible的使用和实战。

一、Ansible安装

1
2
3
4
5
6
7
8
9
10
11
# CentOS
yum install ansible

# Ubuntu
apt install ansible

# pip安装
pip install ansible

# 验证
ansible --version

二、Inventory配置

1
2
3
4
5
6
7
8
9
10
11
# /etc/ansible/hosts
[web]
web1 ansible_host=192.168.1.10
web2 ansible_host=192.168.1.11

[db]
db1 ansible_host=192.168.1.20

[all:vars]
ansible_user=root
ansible_ssh_private_key_file=/root/.ssh/id_rsa

三、Ad-Hoc命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# ping测试
ansible all -m ping

# 执行命令
ansible web -m shell -a "uptime"

# 复制文件
ansible web -m copy -a "src=/tmp/file.txt dest=/tmp/"

# 安装软件
ansible web -m yum -a "name=nginx state=present"

# 启动服务
ansible web -m service -a "name=nginx state=started enabled=yes"

四、Playbook编写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# nginx.yml
---
- name: Install and configure Nginx
hosts: web
become: yes

vars:
nginx_port: 80
nginx_root: /var/www/html

tasks:
- name: Install Nginx
yum:
name: nginx
state: present

- name: Copy config file
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: Restart Nginx

- name: Start Nginx
service:
name: nginx
state: started
enabled: yes

handlers:
- name: Restart Nginx
service:
name: nginx
state: restarted
1
2
3
4
5
6
7
8
# 执行Playbook
ansible-playbook nginx.yml

# 检查语法
ansible-playbook nginx.yml --syntax-check

# 模拟执行
ansible-playbook nginx.yml --check

五、角色(Roles)

1
2
3
4
5
6
7
8
9
10
11
12
# 创建角色
ansible-galaxy init nginx

# 目录结构
nginx/
├── defaults/ # 默认变量
├── files/ # 文件
├── handlers/ # 处理器
├── meta/ # 元数据
├── tasks/ # 任务
├── templates/ # 模板
└── vars/ # 变量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# tasks/main.yml
---
- name: Install Nginx
yum:
name: nginx
state: present

- name: Configure Nginx
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: Restart Nginx

- name: Start Nginx
service:
name: nginx
state: started
enabled: yes
1
2
3
4
5
6
# 使用角色
---
- hosts: web
roles:
- nginx
- mysql

六、实战案例:部署Java应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
---
- name: Deploy Java Application
hosts: app
become: yes

vars:
app_name: myapp
app_port: 8080
app_jar: myapp.jar

tasks:
- name: Install Java
yum:
name: java-11-openjdk
state: present

- name: Create app directory
file:
path: /opt/{{ app_name }}
state: directory

- name: Copy jar file
copy:
src: target/{{ app_jar }}
dest: /opt/{{ app_name }}/{{ app_jar }}

- name: Create systemd service
template:
src: app.service.j2
dest: /etc/systemd/system/{{ app_name }}.service

- name: Start application
systemd:
name: "{{ app_name }}"
state: restarted
enabled: yes
daemon_reload: yes

总结

Ansible核心:

  1. 无Agent:SSH连接,无需安装客户端
  2. Playbook:YAML格式,易读易写
  3. 幂等性:多次执行结果一致
  4. 角色:模块化组织

参考资料