1、使用ansible的playbook实现自动化安装httpd
准备工作:
1. 主机规划
192.168.37.7作为ansible的主控制端,192.168.37.6作为一台centos6的被控端,192.168.37.17作为一台centos7的被控端;
主机 | 用途 |
---|---|
192.168.37.7 | ansible主控制端 |
192.168.37.6 | centos6被控端 |
192.168.37.17 | centos7被控端 |
2. 控制端ansible的安装配置
A.192.168.37.7安装ansible
#注意:ansible主控制端需要python2.6以上
[root@37-7-test1 ~]# python --version
Python 2.7.5
#ansible基于epel源,配置epel源为阿里云
[root@37-7-test1 ~]# cat /etc/yum.repos.d/epel.repo
[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
baseurl=http://mirrors.aliyun.com/epel/7/$basearch
failovermethod=priority
enabled=1
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
[epel-debuginfo]
name=Extra Packages for Enterprise Linux 7 - $basearch - Debug
baseurl=http://mirrors.aliyun.com/epel/7/$basearch/debug
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=0
[epel-source]
name=Extra Packages for Enterprise Linux 7 - $basearch - Source
baseurl=http://mirrors.aliyun.com/epel/7/SRPMS
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=0
#演示 直接以yum方式安装,生产中也可以编译安装
[root@37-7-test1 ~]# yum install ansible -y
Loaded plugins: fastestmirror, langpacks
base | 3.6 kB 00:00:00
epel | 4.7 kB 00:00:00
extras | 2.9 kB 00:00:00
updates | 2.9 kB 00:00:00
(1/3): epel/x86_64/updateinfo | 1.0 MB 00:00:00
(2/3): epel/x86_64/primary_db | 6.9 MB 00:00:00
(3/3): updates/7/x86_64/primary_db | 3.7 MB 00:00:00
。。。。。
Dependency Updated:
openssl.x86_64 1:1.0.2k-19.el7 openssl-libs.x86_64 1:1.0.2k-19.el7
Complete!
#自动解决依赖关系,编译安装请先安装依赖包
#yum -y install python-jinja2 PyYAML python-paramiko python-babel
B. 主机清单的配置
vim /etc/ansible/hosts
[websrvs]
192.168.37.17
192.168.37.6
[appsrvs]
192.168.37.17
"/etc/ansible/hosts" 48L, 1073C written
C. 基于SSH-key验证
#在192.168.37.7上生成私钥,和公钥
[root@37-7-test1 ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
b7:cf:e6:01:12:77:75:77:d9:0b:3e:4f:b5:c1:2e:a6 root@37-7-test1
The key's randomart image is:
+--[ RSA 2048]----+
| o *|
| o ==|
| . . o o =|
| o . = = |
| S o o = |
| o E . |
| . . |
| o.. |
| o+ |
+-----------------+
[root@master-mariadb bakup]# ssh-copy-id 192.168.37.17
#分发公钥至目标主机192.168.37.17和192.168.37.6,实现以ssh-key方式验证,无须输入用户名密码
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.37.17's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '192.168.37.17'"
and check to make sure that only the key(s) you wanted were added.
[root@37-7-test1 ~]# ssh-copy-id 192.168.37.6
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.37.6's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '192.168.37.6'"
and check to make sure that only the key(s) you wanted were added.
#ansible配置修改/etc/ansible/ansible.cfg
#第一次验证不检查key
host_key_checking = False
#测试被控主机列表,被测试ansible是否可用
[root@37-7-test1 ~]# ansible all --list-hosts
#查看所有主机列表
hosts (2):
192.168.37.17
192.168.37.6
[root@37-7-test1 ~]# ansible websrvs --list-hosts
#查看websrvs主机列表
hosts (2):
192.168.37.17
192.168.37.6
[root@37-7-test1 ~]# ansible appsrvs --list-hosts
hosts (1):
192.168.37.17
#测试可用性
[root@37-7-test1 ~]# ansible all -m ping
192.168.37.17 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.37.6 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
3. 准备httpd.conf配置文件
#可以安装一个httpd服务,并把配置文件拷贝过来即可
[root@37-7-test1 ~]# mkdir /data/ansible/playbook -p
[root@37-7-test1 ~]# cd /data/ansible/playbook/
#准备一个目录用于ansible剧本拷贝调用copy模块复制配置文件
[root@37-7-test1 playbook]# cp /etc/httpd/conf/httpd.conf /data/ansible/playbook/
[root@37-7-test1 playbook]# ls /data/ansible/playbook/
httpd.conf
[root@37-7-test1 playbook]# vim /data/ansible/httpd.conf
#配置文件修改一下端口,方便后面测试是不是我们ansible安装的httpd
Listen 8080
4.编制剧本实现自动化安装httpd
#此剧本适合yum安装httpd的部署
-------------------------------------------------------
#注意yum格式语法
#开头顶格写---
---
- hosts: appsrvs
#注意顶格写-,定义主机列表
remote_user: root
#远程用户
tasks:
#tasks要与上面的remote——user对齐
- name: install httpd
#错格tasks2个空格符
yum: name=httpd
- name: config
copy: src=/data/ansible/playbook/httpd.conf dest=/etc/httpd/conf/httpd.conf
notify: restart httpd
- name: service
service: name=httpd state=started enabled=yes
handlers:
#要与tasks对齐 修改配置文件触发重启httpd服务
- name: restart httpd
service: name=httpd state=restart
-------------------------------------------------------
[root@37-7-test1 playbook]# vim install_httpd.yml
---
- hosts: appsrvs
remote_user: root
tasks:
- name: install
yum: name=httpd
- name: config
copy: src=/data/ansible/playbook/httpd.conf dest=/etc/httpd/conf/
notify: restart httpd
- name: service
service: name=httpd state=started enabled=yes
handlers:
- name: restart httpd
service: name=httpd state=restarted
"install_httpd.yml" 15L, 364C written
[root@37-7-test1 playbook]# ansible-playbook --syntax-check install_httpd.yml
#语法检查是否有错误
playbook: install_httpd.yml
#先检查192.168.37.17和37.6是否安装httpd
[root@37-17-test2 ~]# rpm -qi httpd
package httpd is not installed
[root@37-6-test1 ~]# rpm -qi httpd
package httpd is not installed
#运行剧本
[root@37-7-test1 playbook]# ansible-playbook install_httpd.yml
PLAY [appsrvs] ***********************************************************************************************
TASK [Gathering Facts] ***************************************************************************************
ok: [192.168.37.17]
TASK [install] ***********************************************************************************************
ok: [192.168.37.17]
TASK [config] ************************************************************************************************
ok: [192.168.37.17]
TASK [service] ***********************************************************************************************
changed: [192.168.37.17]
PLAY RECAP ***************************************************************************************************
192.168.37.17 : ok=4 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
[root@37-7-test1 playbook]# ansible appsrvs --list-hosts
hosts (1):
192.168.37.17
#将- hosts: appsrvs 改为all或者websrvs测试
[root@37-17-test2 ~]# ss -tnl|grep 8080
LISTEN 0 128 :::8080 :::*
我们发现上述只能实现centos7的安装,并不能实现centos6,和centos7一起部署的场景。可以借助ansible的when,以及变量,template来实现具体如下:
1.分别准备centos6,centos7的httpd.conf配置文件
[root@37-7-test1 playbook]# mkdir templates
#在playbook的同级目录下建立templates模板目录里面存放模板文件
#建立templates模板
[root@37-7-test1 playbook]# tree
.
├── install_httpd2.yml
├── install_httpd.yml
└── templates
├── httpd.conf.c6.j2
└── httpd.conf.c7.j2
1 directory, 4 files
[root@37-7-test1 playbook]# less httpd.conf.c6.j2
#这里直接在centos6安装yum安装一个httpd将配置文件拷贝过来即可,并修改端口为60待会测试用
#
# This is the main Apache server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# The configuration directives are grouped into three basic sections:
# 1. Directives that control the operation of the Apache server process as a
# whole (the 'global environment').
# 2. Directives that define the parameters of the 'main' or 'default' server,
# which responds to requests that aren't handled by a virtual host.
# These directives also provide default values for the settings
# of all virtual hosts.
# 3. Settings for virtual hosts, which allow Web requests to be sent to
# different IP addresses or hostnames and have them handled by the
# same Apache server process.
[root@37-7-test1 playbook]# less httpd.conf.c7.j2
#已经准备好的httpd.conf改个名就好
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
# with ServerRoot set to '/www' will be interpreted by the
# server as '/www/log/access_log', where as '/log/access_log' will be
# interpreted as '/log/access_log'.
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
2.playbook剧本的实现
[root@37-7-test1 playbook]# vim install_httpd2.yml
---
- hosts: websrvs
remote_user: root
tasks:
- name: install
yum: name=httpd
- name: config6
template: src=httpd.conf.c6.j2 dest=/etc/httpd/conf/httpd.conf
notify: restart httpd
when: ansible_distribution_major_version=="6"
- name: config7
template: src=httpd.conf.c7.j2 dest=/etc/httpd/conf/httpd.conf
notify: restart httpd
when: ansible_distribution_major_version=="7"
- name: service
service: name=httpd state=started enabled==yes
handlers:
- name: restart httpd
service: name=httpd state=restarted
~
~
~
~
~
~
~
~
~
~
~
"install_httpd2.yml" 21L, 589C written
[root@37-7-test1 playbook]# ansible-playbook --syntax-check install_httpd2.yml
playbook: install_httpd2.yml
3.测试执行并验证
[root@37-7-test1 playbook]# ansible-playbook --syntax-check install_httpd2.yml
playbook: install_httpd2.yml
[root@37-7-test1 playbook]# ansible-playbook install_httpd2.yml
PLAY [websrvs] ******************************************************************************************************************************************************************
TASK [Gathering Facts] **********************************************************************************************************************************************************
ok: [192.168.37.17]
ok: [192.168.37.6]
TASK [install] ******************************************************************************************************************************************************************
ok: [192.168.37.6]
ok: [192.168.37.17]
TASK [config6] ******************************************************************************************************************************************************************
skipping: [192.168.37.17]
ok: [192.168.37.6]
TASK [config7] ******************************************************************************************************************************************************************
skipping: [192.168.37.6]
ok: [192.168.37.17]
TASK [service] ******************************************************************************************************************************************************************
ok: [192.168.37.17]
changed: [192.168.37.6]
PLAY RECAP **********************************************************************************************************************************************************************
192.168.37.17 : ok=4 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
192.168.37.6 : ok=4 changed=1 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
#验证c6是否安装并启动60端口
[root@37-6-test1 conf]# ss -tnlp|grep httpd
LISTEN 0 128 :::60 :::* users:(("httpd",7870,5),("httpd",7872,5),("httpd",7873,5),("httpd",7874,5),("httpd",7875,5),("httpd",7876,5),("httpd",7877,5),("httpd",7878,5),("httpd",7879,5))
#验证c7是否安装并启动8080端口
[root@37-17-test2 ~]# ss -tnlp|grep httpd
LISTEN 0 128 :::8080 :::* users:(("httpd",36259,4),("httpd",36258,4),("httpd",36257,4),("httpd",36255,4),("httpd",36254,4),("httpd",36253,4))
2、建立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. 安装httpd服务器
#以yum安装为例
[root@37-7-test1 ~]# yum install httpd -y
Loaded plugins: fastestmirror, langpacks
Determining fastest mirrors
* base: mirrors.aliyun.com
* extras: mirrors.aliyun.com
* updates: mirrors.aliyun.com
Resolving Dependencies
--> Running transaction check
---> Package httpd.x86_64 0:2.4.6-93.el7.centos will be installed
--> Finished Dependency Resolution
Dependencies Resolved
============================================================================================================
Package Arch Version Repository Size
============================================================================================================
Installing:
httpd x86_64 2.4.6-93.el7.centos base 2.7 M
Transaction Summary
============================================================================================================
Install 1 Package
Total download size: 2.7 M
Installed size: 9.4 M
Downloading packages:
httpd-2.4.6-93.el7.centos.x86_64.rpm | 2.7 MB 00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : httpd-2.4.6-93.el7.centos.x86_64 1/1
Verifying : httpd-2.4.6-93.el7.centos.x86_64 1/1
Installed:
httpd.x86_64 0:2.4.6-93.el7.centos
Complete!
2.配置HTTP的服务
A. 创建网站所需目录
[root@master-mariadb ~]# mkdir -p /web/vhosts/{x,y}
#创建二个虚拟主机的目录
#分别给虚拟主机目录添加主页文件,方便测试用
[root@master-mariadb ~]# vim /web/vhosts/x/index.html
<h1>这是站点X</h1>
[root@master-mariadb ~]# vim /web/vhosts/y/index.html
<h1>这是站点Y</h2>
#检查其目录结构
[root@master-mariadb ~]# tree /web/vhosts/
/web/vhosts/
├── x
│ └── index.html
└── y
└── index.html
2 directories, 2 files
B. 虚拟主机的配置
#此处不用修改配置文件/etc/httpd/conf/httpd.conf,在/etc/httpd/conf.d/test.conf直接配置
------------------------------------------------------------
#定义站点主目录
#并授权/web/vhosts,也可在虚拟主机中分别授权所需目录,这里直接授权/web/vhosts即可
DocumentRoot "/web/vhosts"
<Directory "/web/vhosts">
require all granted
</Directory>
#定义虚拟主机www.x.com
<VirtualHost *:80>
#表示虚拟主机监听在所有网卡的80端口上,工作可绑定某ip
ServerName www.x.com
#依靠主机头多虚拟主机的关键配置项定义不同FQDN来区分不同http服务
DocumentRoot "/web/vhosts/x"
#此虚拟主机的站点目录
ErrorLog "/var/log/httpd/x.err"
#错误日志存放位置和格式
CustomLog "/var/log/httpd/x.access" combined
#访问日志的定义
#只为演示分别授权的例子,centos7以后需要显示授权其目录才能访问
<Directory "/web/vhosts/x">
require all granted
</Directory>
</VirtualHost>
#定义虚拟主机www.y.com
<VirtualHost *.80>
ServerName www.y.com
DocumentRoot "/web/vhosts/y"
ErrorLog "/var/log/httpd/www2.err"
CustomLog "/var/log/httpd/y.access" combined
</VirtualHost>
---------------------------------------------------------------------
[root@master-mariadb ~]# vim /etc/httpd/conf.d/test.conf
DocumentRoot "/web/vhosts"
<Directory "/web/vhosts">
require all granted
</Directory>
<VirtualHost 192.168.37.7:80>
ServerName www.x.com
DocumentRoot "/web/vhosts/x"
ErrorLog "/var/log/httpd/x.err"
CustomLog "/var/log/httpd/x.access" combined
</VirtualHost>
<VirtualHost 192.168.37.7:80>
ServerName www.y.com
DocumentRoot "/web/vhosts/y"
ErrorLog "/var/log/httpd/y.err"
CustomLog "/var/log/httpd/y.access" combined
</VirtualHost>
C.测试
#192.168.37.7本机测试
[root@master-mariadb ~]# vim /etc/hosts
#先修改hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdoma
in4
::1 localhost localhost.localdomain localhost6 localhost6.localdoma
in6
192.168.37.7 www.x.com
192.168.37.7 www.y.com
~
"/etc/hosts" 4L, 204C written
#然后测试成功
[root@master-mariadb ~]# curl www.x.com
<h1>这是站点X</h1>
[root@master-mariadb ~]# curl www.y.com
<h1>这是站点Y</h2>
#分别查看日志文件
[root@master-mariadb ~]# tail -f /var/log/httpd/x.access
192.168.37.7 - - [13/Aug/2020:14:50:56 +0800] "GET / HTTP/1.1" 200 23
192.168.37.1 - - [13/Aug/2020:15:07:49 +0800] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
192.168.37.1 - - [13/Aug/2020:15:07:57 +0800] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
windows客户端浏览器测试
1. 设置hosts
图片.png
站点测试结果
图片.png
图片.png