第 11 章 案例:部署Web服务器
使用Playbook批量部署多台LAMP环境(示例,不可用于生产环境)
0、添加主机清单及密钥认证
定义组名:
[root@xuegod63 ~]# vim /etc/ansible/hosts #还使用之前定义好的,这里不用修改
[web-servers]
192.168.1.63
192.168.1.64
然后,将公钥信息复制到被控制节点,ansible和两个节点间通过ssh进行连接。下面3个命令之前已经做过,不用执行了。
[root@xuegod63 ~]# ssh-keygen
[root@xuegod63 ~]# ssh-copy-id [email protected]
[root@xuegod63 ~]# ssh-copy-id [email protected]
1、创建文件结构目录:
mkdir -pv /etc/ansible/lamp/roles/{prepare,httpd,mysql,php}/{tasks,files,templates,vars,meta,default,handlers}
创建后文件夹结构如下:
/etc/ansible/lamp └── roles ├── httpd │ ├── default │ ├── files │ ├── handlers │ ├── meta │ ├── tasks │ ├── templates │ └── vars ├── mysql │ ├── default │ ├── files │ ├── handlers │ ├── meta │ ├── tasks │ ├── templates │ └── vars ├── php │ ├── default │ ├── files │ ├── handlers │ ├── meta │ ├── tasks │ ├── templates │ └── vars └── prepare ├── default ├── files ├── handlers ├── meta ├── tasks ├── templates └── vars
2.拷贝配置文件
(也可以创建对应模板jia)
将上面搭建成功的LAMP环境的httpd和MySQL的配置文件拷贝到对应目录下:
cd /etc/ansible/
Apache配置文件:cp /etc/httpd/conf/httpd.conf lamp/roles/httpd/files/
mariadb配置文件:cp /etc/my.cnf lamp/roles/mysql/files/
3、写prepare(前期准备)角色的playbooks
vim lamp/roles/prepare/tasks/main.yml ##复制以下红色内容到文件中,配置好yum源
- name: delete yum config
shell: rm -rf /etc/yum.repos.d/* #删除原有的yum配置文件
- name: provide yumrepo file
shell: wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo #下载新的yum配置文件
- name: clean the yum repo
shell: yum clean all #清除原有的yum缓存信息
- name: clean the iptables
shell: iptables -F #清除原有防火墙规则,不然后可能上不了网
4、构建httpd的任务
[root@CentOS7 roles]# cat httpd/tasks/main.yml
- name: yum install apache
yum: name=httpd state=present
- name: provide tset page
copy: src=index.php dest=/var/www/html
- name: delete httpd.conf
shell: rm -rf /etc/httpd/conf/httpd.conf
- name: provide configuration file
copy: src=httpd.conf dest=/etc/httpd/conf/httpd.conf
notify: restart httpd
5、构建httpd的handlers
[root@CentOS7 roles]# cat httpd/handlers/main.yml
- name: restart httpd
service: name=httpd enabled=yes state=restarted
6、部署mariadb数据库
[root@CentOS7 roles]# cat mysql/tasks/main.yml
- name: install mariadb
yum: name=mariadb-server state=present
- name: delete my.cnf
shell: rm -rf /etc/my.cnf
- name: provide my.cnf
copy: src=my.cnf dest=/etc/my.cnf
- name: start mariadb
service: name=mariadb enabled=yes state=started
5、安装PHP的任务
[root@CentOS7 roles]# cat php/tasks/main.yml
- name: install php
yum: name=php state=present
- name: install php-mysql
yum: name=php-mysql state=present
6、定义整个的任务
[root@CentOS7 roles]# pwd
/etc/ansible/lamp/roles
[root@CentOS7 roles]# cat site.yml
- name: LAMP build
remote_user: root
hosts: lamp
roles:
- prepare
- mysql
- php
- httpd
7、开始部署:
ansible-playbook -i /etc/ansible/hosts /etc/ansible/lamp/roles/site.yml
8、其他问题
去掉秘钥远程连接时,第一次连接会提示主机指纹验证提示:
修改 /etc/ansible/ansible.cfg
第70行左右,有一个取消主机指纹检查设置开启就行
host_key_checking = False