ansible-playbook-案例分析

Playbook 将会使 Ansible 的功能更为完善、Playbook 可以固化所有操作,减少人为失误, 满足工程量较大的工具所具备具备的复杂度、可扩展度等要求,使得 Ansible 成为超一流的管理工具。安装apache案例:

shell 脚本安装apache

1
2
3
4
5
6
7
8
9
# !/bin/bash
# 安装 Apache
yum install --quiet -y httpd httpd- devel
# 复制 配置文件
cp /path/to/config/httpd.conf /etc/httpd/conf/httpd.conf
cp /path/to/httpd-vhosts.conf /etc/httpd/conf/httpd-vhosts.conf
#启动 Apache,并设置开机启动
systemctl start httpd
systemctl enable httpd

chmod +x install_apache.sh
./install_apache.sh

Playbook command 模块 安装apache

1
2
3
4
5
6
7
8
9
10
11
---
- hosts: all
tasks:
- name: "安装 Apache"
command: yum install --quiet -y httpd httpd-devel
- name: "复制 配置文件"
command: cp /tmp/httpd.conf /etc/httpd/conf/httpd.conf
command: cp /tmp/httpd-vhosts.conf /etc/httpd/conf/httpd-vhosts.conf
- name: "启动 Apache, 并设置开机启动"
command: systemctl start httpd
command: systenctl enable httpd

ansible-playbook install_apache.yml

Playbook yum 模块 安装apache

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
---
- hosts: all
sudo: yes
tasks:
- name: 安装apache
yum: name={{ item }} state=present
with_items:
- httpd
- httpd-devel
- name: 复制配置文件
copy:
src: '{{ item.src }}'
dest: '{{ item.dest }}'
owner: root
group: root
mode: 0644
with_items:
- {
src: '/tmp/httpd.conf',
dest: '/etc/httpd/conf/httpd.conf'
}
- {
src: '/tmp/httpd-vhosts.conf',
dest: '/etc/httpd/conf/httpd-vhosts.conf'
}
- name: 检查Apache运行状态,并设置开机启动
service: name=httpd state=started enabled=yes

使用了yum、copy、service对apache服务进行安装、配置和运行状态维护等一系列操作。