一、使用ansible的playbook实现自动化安装httpd
环境:ansible主机:192.168.0.10
webserver1:192.168.0.11
webserver2:192.168.0.12
1)基于KEY认证
[root@localhost ~]#ssh-keygen
[root@localhost ~]#ssh-copy-id 192.168.0.10
[root@localhost ~]#rsync -av .ssh 192.168.0.11:/root/
[root@localhost ~]#rsync -av .ssh 192.168.0.12:/root/
2)安装ansible
[root@localhost ~]#yum install ansible -y
3)添加ansible管理的主机
[root@localhost ~]#vim /etc/ansible/host
[websrvs]
192.168.0.11
192.168.0.12
4)编写ansible脚本
[root@localhost ~]#vim install_httpd.yml
---
- hosts: websrvs
remote_user: root
tasks:
- name: "安装httpd"
yum: name=httpd
- name: "复制配置文件"
copy: src=/tmp/httpd.conf dest=/etc/httpd/conf/
- name: "启动httpd服务,并设置开机启动"
service: name=httpd state=started enabled=yes
5)复制修改httpd.conf的配置文件到/tmp下:
[root@localhost ~]# cp /etc/httpd/conf/httpd.conf /tmp/
[root@localhost ~]# vim /tmp/httpd.conf
Listen 8080
6)执行ansible脚本
[root@localhost ~]# ansible-playbook instll_httpd.yml
7)完成结果:
二、建立httpd服务器,要求提供两个基于名称的虚拟主机:
(1)www.X.com,页面文件目录为/web/vhosts/x;错误日志为/var/log/httpd/x.err,访问日志为/var/log/httpd/x.access
(2)www.Y.com,页面文件目录为/web/vhosts/y;错误日志为 /var/log/httpd/www2.err,访问日志为/var/log/httpd/y.access
(3)为两个虚拟主机建立各自的主页文件index.html,内容分别为其对应的主机名
1、创建主机的页面文件目录
[root@localhost ~]#mkdir -p /web/vhosts/{x,y}
2、生成两个主机各自的主页文件
[root@localhost ~]#echo www.x.com > /web/vhosts/x/index.html
[root@localhost ~]#echo www.y.com > /web/vhosts/y/index.html
3、创建虚拟主机配置文件
[root@localhost ~]# vim /etc/httpd/conf.d/web.conf
<VirtualHost *:80>
DocumentRoot /web/vhosts/x
servername www.x.com
ErrorLog /var/log/httpd/x.err
CustomLog /var/log/httpd/x.access combined
<Directory /web/vhosts/x>
require all granted
</Directory>
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /web/vhosts/y
servername www.y.com
ErrorLog /var/log/httpd/y.err
CustomLog /var/log/httpd/y.access combined
<Directory /web/vhosts/y>
require all granted
</Directory>
</VirtualHost>
4、访问测试
#添加hosts
[root@localhost ~]# vim /etc/hosts
192.168.0.10 www.x.com www.y.com
#访问2台主机:
[root@localhost ~]# curl www.x.com
www.x.com
[root@localhost ~]# curl www.y.com
www.y.com
5、查看日志
#查看日志文件
[root@localhost ~]# ll /var/log/httpd/
总用量 12
-rw-r--r-- 1 root root 0 3月 27 21:07 access_log
-rw-r--r-- 1 root root 671 3月 27 21:07 error_log
-rw-r--r-- 1 root root 264 3月 27 21:14 x.access
-rw-r--r-- 1 root root 0 3月 27 21:07 x.err
-rw-r--r-- 1 root root 176 3月 27 21:14 y.access
-rw-r--r-- 1 root root 0 3月 27 21:07 y.err
[root@localhost ~]# cat /var/log/httpd/x.access
192.168.0.10 - - [27/Mar/2021:21:08:41 +0800] "GET / HTTP/1.1" 200 10 "-" "curl/7.29.0"
192.168.0.10 - - [27/Mar/2021:21:08:52 +0800] "GET / HTTP/1.1" 200 10 "-" "curl/7.29.0"
192.168.0.10 - - [27/Mar/2021:21:14:35 +0800] "GET / HTTP/1.1" 200 10 "-" "curl/7.29.0"
[root@localhost ~]# cat /var/log/httpd/y.access
192.168.0.10 - - [27/Mar/2021:21:08:48 +0800] "GET / HTTP/1.1" 200 10 "-" "curl/7.29.0"
192.168.0.10 - - [27/Mar/2021:21:14:39 +0800] "GET / HTTP/1.1" 200 10 "-" "curl/7.29.0"