目录
脚本功能介绍
用户创建
使用user模块,利用loop进行循环,常见所需用户
下载nginx服务
使用yum模块,进行nginx服务的下载,可以使用yum_repository配置yum源,加快nginx的下载
配置nginx文件
使用template模块和j2模版文件进行节点nginx的配置
更还http服务端口,避免冲突
使用shell模块将http服务端口换为8080,防止与nginx服务冲突
检查nginx语法
使用shell模块和 nginx -t 命令检验语法
开启nginx,http服务
使用shell模块和systemctl命令来配置两个web服务
重启nginx服务
当主配置文件发生变化或者nginx语法错误,进行nginx的重启
脚本全览
- name: template playbook example
hosts: all
vars:
createuser:
- tomcat
- www
- mysql
become: yes
tasks:
- name: cretae user #创建用户
user:
name: "{{ item }}"
state: present
loop: "{{ createuser }}"
- name: yum nginx webserver #下载nginx服务
yum:
name: nginx
state: latest
- name: update nginx mate config #更新nginx主配置文件
template:
src: /root/j2/nginx.conf.j2
dest: /etc/nginx/nginx.conf
tags: updateconfig
notify: reload nginx server
- name: add virtualhost config #添加虚拟主机配置文件
copy:
src: /root/j2/www.qfedu.com.conf
dest: /etc/nginx/conf.d/
tags: updateconfig
notify: reload nginx server
- name: change httpd #更换http服务的端口号,避免发生冲突
shell: sed -ri 's/^Listen .*/Listen 8080/' /etc/httpd/conf/httpd.conf
register: httpd
- name: begin httpd #开启http服务
systemd:
name: httpd
state: restarted
when: httpd.rc == 0
- name: check naginx syntax #检查nginx语法
shell: /usr/sbin/nginx -t
register: nginxsyntax
tags: updateconfig
- name: check naginx running #检测nginx是否成功启动
stat: path=/var/run/nging.pid
register: nginxrunning
tags: updateconfig
- name: print nginx saytax #如果nginx语法错误,输出错误信息
debug:
var: nginxsyntax
- name: start nginx server #开启nginx服务
systemd:
name: nginx
state: started
enabled: yes
when:
- nginxsyntax.rc == 0
- nginxrunning.stat.exists == false
handlers: #当配置文件发生变化,重载nginx服务
- name: reload nginx server
systemd:
name: nginx
state: started
when:
- nginxsyntax.rc == 0
- nginxrunning.stat.exists == true