playbook实战-nginx安装1
实现思路:先在一台机器上编译安装好nginx、打包,也就是把这台机器作为模板机,然后再用ansible playbook去进行下发到远程机器上。
- 编译安装nginx
(1)nginx包下载地址:
http://mirrors.sohu.com/nginx/nginx-1.9.6.tar.gz
(2)解压下载的nginx包
[root@ansible-01 ~]# tar -zxf nginx-1.9.6.tar.gz
(3)编译
[root@ansible-01 ~]# ll
total 872
-rw-------. 1 root root 1079 Nov 19 2020 anaconda-ks.cfg
drwxr-xr-x. 8 1001 1001 4096 Oct 27 2015 nginx-1.9.6
-rw-r--r--. 1 root root 884733 May 25 11:43 nginx-1.9.6.tar.gz
[root@ansible-01 ~]# cd nginx-1.9.6
[root@ansible-01 nginx-1.9.6]# ./configure --prefix=/usr/local/nginx (报错是没有安装依赖:)
checking for OS
+ Linux 3.10.0-327.el7.x86_64 x86_64
checking for C compiler ... not found
./configure: error: C compiler cc is not found
注:两台都需要安装依赖
[root@ansible-01 nginx-1.9.6]# yum install -y gcc-c++ pcre-devel zlib-devel openssl-devel -y
(4)安装完再次进行编译:
[root@ansible-01 nginx-1.9.6]# ./configure --prefix=/usr/local/nginx
[root@ansible-01 nginx-1.9.6]# echo $? (无错误)
0
(5)编译安装:
[root@ansible-01 nginx-1.9.6]# make && make install
[root@ansible-01 nginx-1.9.6]# echo $? (无错误)
0
[root@ansible-01 nginx-1.9.6]# vi /etc/init.d/nginx
#!/bin/bash
# chkconfig: - 30 21
# description: http service.
# Source Function Library
. /etc/init.d/functions
# Nginx Settings
NGINX_SBIN="/usr/local/nginx/sbin/nginx"
NGINX_CONF="/usr/local/nginx/conf/nginx.conf"
NGINX_PID="/usx/local/nginx/logs/nginx.pid"
RETVAL=0
prog="Nginx"
start()
{
echo -n $"Starting $prog: "
mkdir -p /dev/shm/nginx_temp
daemon $NGINX_SBIN -c $NGINX_CONF
RETVAL=$?
echo
return $RETVAL
}
stop()
{
echo -n $"Stopping $prog: "
killproc -p $NGINX_PID $NGINX_SBIN -TERM
rm -rf /dev/shm/nginx_temp
RETVAL=$?
echo
return $RETVAL
}
reload()
{
echo -n $"Reloading $prog: "
killproc -p $NGINX_PID $NGINX_SBIN -HUP
RETVAL=$?
echo
return $RETVAL
}
restart()
{
stop
start
}
configtest()
{
$NGINX_SBIN -c $NGINX_CONF -t
return 0
}
case "$1" in
start)
start
;;
stop)
stop
;;
reload)
reload
;;
restart)
restart
;;
configtest)
configtest
;;
*)
echo $"Usage: $0 {start|stop|reload|restart|configtest}"
RETVAL=1
esac
exit $RETVAL
(7)进行编写(复制的时候去掉中文解析哦,不然有可能报错)
[root@ansible-01 nginx-1.9.6]# > /usr/local/nginx/conf/nginx.conf
[root@ansible-01 nginx-1.9.6]# vi /usr/local/nginx/conf/nginx.conf
user nobody nobody; //定义nginx运行的用户和用户组
worker_processes 2; //nginx进程数,一般为CPU总核心数
error_log /usr/local/nginx/logs/nginx_error.log crit; //全局错误日志定义类型
pid /usr/local/nginx/logs/nginx.pid; //进程文件
worker_rlimit_nofile 51200;
events //工作模式与连接数上限
{
use epoll;
worker_connections 6000;
}
http //http下的一些配置
{
include mime.types; //文件扩展名与文件类型映射表
default_type application/octet-stream; //默认文件类型
server_names_hash_bucket_size 3526;
server_names_hash_max_size 4096;
log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
'$host "$request_uri" $status'
'"$http_referer" "$http_user_agent"';
sendfile on; //开启高效文件传输模式
tcp_nopush on; //防止网络阻塞
keepalive_timeout 30; //长连接超时时间,单位为秒
client_header_timeout 3m;
client_body_timeout 3m;
send_timeout 3m;
connection_pool_size 256;
client_header_buffer_size 1k;
large_client_header_buffers 8 4k;
request_pool_size 4k;
output_buffers 4 32k;
postpone_output 1460;
client_max_body_size 10m;
client_body_buffer_size 256k;
client_body_temp_path /usr/local/nginx/client_body_temp;
proxy_temp_path /usr/local/nginx/proxy_temp;
fastcgi_temp_path /usr/local/nginx/fastcgi_temp;
fastcgi_intercept_errors on;
tcp_nodelay on; //防止网络阻塞
gzip on; //开启gzip压缩输出
gzip_min_length 1k;
gzip_buffers 4 8k;
gzip_comp_level 5;
gzip_http_version 1.1;
gzip_types text/plain application/x-javascript text/css text/htm
application/xml;
server //虚拟主机配置
{
listen 80;
server_name localhost;
index index.html index.htm index.php;
root /usr/local/nginx/html;
location ~ \.php$
{
include fastcgi_params;
fastcgi_pass unix:/tmp/php-fcgi.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/1ocal/nginx/html$fastcgi_script_name;
}
}
}
(8)编写完成后可以检查一下(成功)
[root@ansible-01 nginx-1.9.6]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
(9)开启nginx:
[root@ansible-01 nginx-1.9.6]# service nginx start
env: /etc/init.d/nginx: Permission denied //没有权限
(10)赋予权限:
[root@ansible-01 nginx-1.9.6]# chmod 777 /etc/init.d/nginx
(11)开启nginx,但会报错(解决方法:①查看状态②查看端口是否重复)
[root@ansible-01 nginx-1.9.6]# service nginx start
Reloading systemd: [ OK ]
Starting nginx (via systemctl): Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details.
[FAILED]
①查看nginx的状态
[root@ansible-01 nginx-1.9.6]# systemctl status nginx
● nginx.service - SYSV: http service.
Loaded: loaded (/etc/rc.d/init.d/nginx; bad; vendor preset: disabled)
Active: `failed` (Result: exit-code) since Tue 2021-05-25 12:05:49 CST; 35s ago
②查看端口是否重复
(1)命令不存在得需下载
[root@ansible-01 nginx-1.9.6]# yum install -y net-tools
(2)查看一下端口发下80端口被httpd站着,所以关闭就可以了
[root@ansible-01 nginx-1.9.6]# netstat -ntpl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1461/sshd
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1998/master
tcp6 0 0 :::80 :::* LISTEN 12534/httpd
tcp6 0 0 :::22 :::* LISTEN 1461/sshd
tcp6 0 0 ::1:25 :::* LISTEN 1998/master
(3)关闭httpd服务:
[root@ansible-01 nginx-1.9.6]# systemctl stop httpd
(4)开启nginx服务:
[root@ansible-01 nginx-1.9.6]# service nginx start
Starting nginx (via systemctl): [ OK ]
(5)查看端口:
[root@ansible-01 nginx-1.9.6]# netstat -ntpl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 27221/nginx: master
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1461/sshd
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1998/master
tcp6 0 0 :::22 :::* LISTEN 1461/sshd
tcp6 0 0 ::1:25 :::* LISTEN 1998/master
(6)查看nginx的状态:
[root@ansible-01 nginx-1.9.6]# systemctl status nginx
● nginx.service - SYSV: http service.
Loaded: loaded (/etc/rc.d/init.d/nginx; bad; vendor preset: disabled)
Active: active (`running`) since Tue 2021-05-25 12:07:41 CST; 14s ago
Docs: man:systemd-sysv-generator(8)
Process: 27217 ExecStart=/etc/rc.d/init.d/nginx start (code=exited, status=0/SUCCESS)
CGroup: /system.slice/nginx.service
├─27221 nginx: master process /usr/local/nginx/sbin/nginx -c /...
├─27222 nginx: worker process
└─27223 nginx: worker process
May 25 12:07:41 ansible-01 systemd[1]: Starting SYSV: http service....
May 25 12:07:41 ansible-01 nginx[27217]: Starting Nginx: [ OK ]
May 25 12:07:41 ansible-01 systemd[1]: Started SYSV: http service..
playbook实战-nginx安装2
- 进入ansible配置文件目录,并创建一个nginx_install的目录,方便管理:
[root@ansible-01 nginx-1.9.6]# cd /etc/ansible/
[root@ansible-01 ansible]# mkdir nginx_install
[root@ansible-01 ansible]# cd nginx_install/
[root@ansible-01 nginx_install]#
mkdir -p roles/{common,install}/{handlers,files,meta,tasks,templates,vars}
解释:roles目录下有两个角色,common为一些准备操作,install为安装nginx的操作。每个角色下面又有几个目录,handlers下面是当发生改变时要执行的操作,通常用在配置文件发生改变,重启服务。files为安装时用到的一些文件,meta为说明信息,说明角色依赖等信息,tasks里面是核心的配置文件,templates通常存一些配置文件,启动脚本等模板文件,vars下为定义的变量
- 把nginx目录打包,并放到files下面,以及把启动脚本、配置文件放到templates下面:
(1)将nginx目录打为tar包
[root@ansible-01 nginx_install]# cd /usr/local/
[root@ansible-01 local]# ls
bin etc games include lib lib64 libexec nginx sbin share src
[root@ansible-01 local]# tar -zcvf nginx.tar.gz nginx/
[root@ansible-01 local]# ls
bin games lib libexec nginx.tar.gz share
etc include lib64 nginx sbin src
(2)将nginx.tar.gz复制到/etc/ansible/nginx_install/roles/install/files下
[root@ansible-01 local]# mv nginx.tar.gz /etc/ansible/nginx_install/roles/install/files/
[root@ansible-01 local]# ls
bin etc games include lib lib64 libexec nginx sbin share src
[root@ansible-01 local]# cd nginx/
[root@ansible-01 nginx]# ls
client_body_temp fastcgi_temp logs sbin uwsgi_temp
conf html proxy_temp scgi_temp
(3)配置文件都要放到/etc/ansible/nginx_install/roles/install/templates下面
[root@ansible-01 nginx]# cp conf/nginx.conf /etc/ansible/nginx_install/roles/install/templates/
[root@ansible-01 nginx]# cp /etc/init.d/nginx /etc/ansible/nginx_install/roles/install/templates/
- 需要定义common的tasks,因为nginx是需要一些依赖包的:
[root@ansible-01 ~]# vim /etc/ansible/nginx_install/roles/common/tasks/main.yml
- name: Install initializtion require software
yum: name={{ item }} state=installed
with_items:
- zlib-devel
- pcre-devel
playbook实战-nginx安装3
- 定义变量
[root@ansible-01 ~]# vim /etc/ansible/nginx_install/roles/install/vars/main.yml
nginx_user: www
nginx_port: 80
nginx_basedir: /usr/local/nginx
- 要把所有用到的文档拷贝到目标机器:
[root@ansible-01 ~]# vim /etc/ansible/nginx_install/roles/install/tasks/copy.yml
- name: Copy Nginx Software
copy: src=nginx.tar.gz dest=/tmp/nginx.tar.gz owner=root group=root
- name: Uncompression Nginx Software
shell: tar zxf /tmp/nginx.tar.gz -C /usr/local/
- name: Copy Nginx Start Script
template: src=nginx dest=/etc/init.d/nginx owner=root group=root mode=0755
- name: Copy Nginx Config
template: src=nginx.conf dest={{ nginx_basedir }}/conf/ owner=root group=root mode=0644
注:这里src参数指定的是相对路径,这个相对路径相对的是模块,例如copy模块里的src参数的值为nginx.tar.gz,那么就会去files目录下找nginx.tar.gz,而template模块则是会去templates目录下找。
playbook实战-nginx安装4
会建立用户,启动服务,删除压缩包
[root@ansible-01 ~]# vim /etc/ansible/nginx_install/roles/install/tasks/install.yml
- name: Create Nginx User
user: name={{ nginx_user }} state=present createhome=no shell=/sbin/nologi
n
- name: Start Nginx Service
shell: /etc/init.d/nginx start
- name: Add Boot Start Nginx Service
shell: chkconfig --level 345 nginx on
- name: Delete Nginx compression files
shell: rm -rf /tmp/nginx.tar.gz
注:nginx_user变量是之前我们在vars目录下的main.yml文件中定义的,所以在这里可以直接引用。
playbook实战-nginx安装 5
- 再创建main.yml并且把copy和install调用
[root@ansible-01 ~]# vim /etc/ansible/nginx_install/roles/install/tasks/main.yml
- include: copy.yml
- include: install.yml
- 要定义一个入口配置文件
[root@ansible-01 ~]# vim /etc/ansible/nginx_install/install.yml
---
- hosts: 192.168.200.23
remote_user: root
gather_facts: True
roles:
- common
- install
- 执行
[root@ansible-01 ~]# ansible-playbook /etc/ansible/nginx_install/install.yml
PLAY [192.168.200.23] **********************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.200.23]
TASK [common : Install initializtion require software] *************************
[DEPRECATION WARNING]: Invoking "yum" only once while using a loop via
squash_actions is deprecated. Instead of using a loop to supply multiple items
and specifying `name: "{{ item }}"`, please use `name: ['zlib-devel', 'pcre-
devel']` and remove the loop. This feature will be removed in version 2.11.
Deprecation warnings can be disabled by setting deprecation_warnings=False in
ansible.cfg.
ok: [192.168.200.23] => (item=[u'zlib-devel', u'pcre-devel'])
TASK [install : Copy Nginx Software] *******************************************
changed: [192.168.200.23]
TASK [install : Uncompression Nginx Software] **********************************
[WARNING]: Consider using the unarchive module rather than running 'tar'. If
you need to use command because unarchive is insufficient you can add 'warn:
false' to this command task or set 'command_warnings=False' in ansible.cfg to
get rid of this message.
changed: [192.168.200.23]
TASK [install : Copy Nginx Start Script] ***************************************
changed: [192.168.200.23]
TASK [install : Copy Nginx Config] *********************************************
ok: [192.168.200.23]
TASK [install : Create Nginx User] *********************************************
changed: [192.168.200.23]
TASK [install : Start Nginx Service] *******************************************
changed: [192.168.200.23]
TASK [install : Add Boot Start Nginx Service] **********************************
changed: [192.168.200.23]
TASK [install : Delete Nginx compression files] ********************************
[WARNING]: Consider using the file module with state=absent rather than running
'rm'. If you need to use command because file is insufficient you can add
'warn: false' to this command task or set 'command_warnings=False' in
ansible.cfg to get rid of this message.
changed: [192.168.200.23]
PLAY RECAP *********************************************************************
192.168.200.23 : ok=10 changed=7 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
管理配置文件
- 管理nginx配置文件的playbook
[root@ansible-01 ~]# mkdir -p /etc/ansible/nginx_config/roles/{new,old}/{files,handlers,vars,tasks}
其中new为更新时用到的,old为回滚时用到的,files下面为nginx.conf和vhosts目录,handlers为重启nginx服务的命令
关于回滚,需要在执行playbook之前先备份一下旧的配置,所以对于老配置文件的管理一定要严格,千万不能随便去修改线上机器的配置,并且要保证new/files下面的配置和线上的配置一致
- files下面为nginx.conf和vhosts目录
[root@ansible-01 ~]# cd /usr/local/nginx/conf/
[root@ansible-01 conf]# ls (没有vhosts目录)
fastcgi.conf koi-win scgi_params
fastcgi.conf.default mime.types scgi_params.default
fastcgi_params mime.types.default uwsgi_params
fastcgi_params.default nginx.conf uwsgi_params.default
koi-utf nginx.conf.default win-utf
- 创建vhosts目录
[root@ansible-01 conf]# mkdir vhosts
[root@ansible-01 conf]# ls
fastcgi.conf mime.types uwsgi_params
fastcgi.conf.default mime.types.default uwsgi_params.default
fastcgi_params nginx.conf `vhosts`
fastcgi_params.default nginx.conf.default win-utf
koi-utf scgi_params
koi-win scgi_params.default
[root@ansible-01 conf]# cd vhosts/
[root@ansible-01 vhosts]# touch 1.conf (创建文件完后nginx无法读取)
[root@ansible-01 vhosts]# cd ..
- 两个端点都需要配:
①[root@ansible-01 conf]# vi nginx.conf
(所以在倒数第二行添加以下内容)
②[root@ansible-02 ~]# vi /usr/local/nginx/conf/nginx.conf
- 把nginx.conf和vhosts目录放到files目录下面
[root@ansible-01 conf]# cp -r nginx.conf vhosts /etc/an
anacrontab ansible/
[root@ansible-01 conf]# cp -r nginx.conf vhosts /etc/ansible/nginx_config/roles/new/files/
[root@ansible-01 conf]# ls /etc/ansible/nginx_config/roles/new/files/
nginx.conf vhosts
[root@ansible-01 conf]# cd /etc/ansible/nginx_config/
[root@ansible-01 nginx_config]# ls
roles
[root@ansible-01 nginx_config]# vim roles/new/vars/main.yml
nginx_basedir: /usr/local/nginx
[root@ansible-01 nginx_config]# vim roles/new/handlers/main.yml
- name: restart nginx
shell: /etc/init.d/nginx reload
[root@ansible-01 nginx_config]# vi roles/new/tasks/main.yml
- name: copy conf file
copy: src={{ item.src }} dest={{ nginx_basedir }}/{{ item.dest }} backup=yes owner=root group=root mode=0644
with_items:
- { src: nginx.conf, dest: conf/nginx.conf }
- { src: vhosts, dest: conf/ }
notify: restart nginx
[root@ansible-01 ~ ]# vim /etc/ansible/nginx_config/update.yml
---
- hosts: testhost
user: root
roles:
- new
执行:
[root@ansible-01 ~]# ansible-playbook /etc/ansible/nginx_config/update.yml
PLAY [testhost] ****************************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.200.23]
ok: [127.0.0.1]
TASK [new : copy conf file] ****************************************************
ok: [192.168.200.23] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
ok: [127.0.0.1] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
ok: [192.168.200.23] => (item={u'dest': u'conf/', u'src': u'vhosts'})
ok: [127.0.0.1] => (item={u'dest': u'conf/', u'src': u'vhosts'})
PLAY RECAP *********************************************************************
127.0.0.1 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
192.168.200.23 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
回滚操作就是把旧的配置覆盖,然后重新加载nginx服务, 每次改动nginx配置文件之前先备份到old里,对应目录为/etc/ansible/nginx_config/roles/old/files
[root@ansible-01 ~]# rsync -av /etc/ansible/nginx_config/roles/new/ /etc/ansible/nginx_config/roles/old/
sending incremental file list
files/
files/nginx.conf
files/vhosts/
files/vhosts/1.conf
handlers/
handlers/main.yml
tasks/
tasks/main.yml
vars/
vars/main.yml
sent 2,424 bytes received 131 bytes 5,110.00 bytes/sec
total size is 1,875 speedup is 0.73
-a:使用递归的形式传递文件,而且保留文件属性和权限
-v:传输中显示列表
定义总入口配置:
[root@ansible-01 ~]# vim /etc/ansible/nginx_config/rollback.yml
---
- hosts: testhost
user: root
roles:
- old
执行:
[root@ansible-01 ~]# ansible-playbook /etc/ansible/nginx_config/rollback.yml
PLAY [testhost] ****************************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.200.23]
ok: [127.0.0.1]
TASK [old : copy conf file] ****************************************************
ok: [127.0.0.1] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
ok: [192.168.200.23] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
ok: [127.0.0.1] => (item={u'dest': u'conf/', u'src': u'vhosts'})
ok: [192.168.200.23] => (item={u'dest': u'conf/', u'src': u'vhosts'})
PLAY RECAP *********************************************************************
127.0.0.1 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
192.168.200.23 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
但没发生改变,在实际操作中更新和回滚都是修改了配置文件之后才需要更新或者是回滚,但并没对配置文件进行修改,所以changed=0