ansible playbook批量部署nginx软件
规划
软件安装包:nginx-1.16.1.tar.gz
源文件安装存放目录:/install/nginx-1.16.1.tar.gz
nginx安装目录:/usr/local/nginx
nginx解压缩目录:/usr/local/src
解压之后的源文件目录为/usr/local/src/nginx-1.16.1
部署环境:
操作中系统 | ip | 主机名 | 软件安装目录 |
---|---|---|---|
Linux7.5 | 192.168.174.129 | srvb | /usr/local/nginx |
Linux7.5 | 192.168.174.130 | srvc | /usr/local/nginx |
Linux7.5 | 192.168.174.131 | srvd | /usr/local/nginx |
程序部署思路说明:
1、通过将存放在ansible管理端的/install/nginx-1.16.1.tar.gz,复制并解压到受管端/usr/local/src/nginx-1.16.1目录
2、进入受管端/usr/local/src/nginx-1.16.1,进行nginx源码安装
3、安装完成之后,进行添加到系统命令行,也就是可执行文件link到/usr/sbin中
4、启动nginx
nginx.yaml配置文件
---
- hosts: srv
vars:
- srcdir: nginx-1.16.1
- insdir: /usr/local/nginx
remote_user: root
tasks:
- name: cp and untar
unarchive: src=/install/nginx-1.16.1.tar.gz dest=/usr/local/src
- name: compile and install nginx
shell : cd /usr/local/src/{{ srcdir }}; ./configure --prefix={{ insdir }} --with-http_stub_status_module --with-http_gzip_static_module --with-http_ssl_module && make && make install
- name: link the command
file : src={{ insdir }}/sbin/nginx dest=/usr/sbin/nginx state=link
- name: start nginx
shell : nginx
执行安装:
ansible-playbook nginx.yaml
**部署记录:**
[root@srva yaml]# ansible-playbook nginx.yaml
[WARNING]: Found both group and host with same name: srva
PLAY [srv] ************************************************************************************************************
TASK [Gathering Facts] ************************************************************************************************
ok: [srvc]
ok: [srvd]
ok: [srvb]
TASK [cp and untar] ***************************************************************************************************
changed: [srvb]
changed: [srvc]
changed: [srvd]
TASK [compile and install nginx] **************************************************************************************
changed: [srvd]
changed: [srvb]
changed: [srvc]
TASK [link the command] ***********************************************************************************************
changed: [srvc]
changed: [srvb]
changed: [srvd]
TASK [start nginx] ****************************************************************************************************
changed: [srvc]
changed: [srvb]
changed: [srvd]
PLAY RECAP ************************************************************************************************************
srvb : ok=5 changed=4 unreachable=0 failed=0
srvc : ok=5 changed=4 unreachable=0 failed=0
srvd : ok=5 changed=4 unreachable=0 failed=0
[root@srva yaml]#
补充说明
批量创建安装目录:
ansible srv -m shell -a ‘mkdir -p /usr/local/nginx’ 注:也可以使用file模块来处理
批量关闭nginx:
ansible srv -m shell -a ‘nginx -s stop’
查看nginx进程:
ansible srv -m shell -a 'ps -ef|grep nginx|grep -v grep ’
错误记录:
在配置yaml文件时,我们使用shell模块,又使用chdir来改变目录。这个是不正确的。
chdir是在command模块带的切换目录参数。而shell模块没有这个。
shell和raw模块要切换目录,可以使用 -a ‘cd /usr/local/nginx/sbin; ./nginx -s start’ 的模式来实现。