231321 发表于 2016-3-21 09:17:59

ansible playbook实战——下发部署nginx以及更新、回滚

下面这篇文章主要是通过 ansible 下发部署安装 nginx 以及后期发布更新配置,还有回滚机制来认识 ansible 的 playbook。



思路:先在一台机器上编译安装好 nginx、打包,然后再用 ansible 去下发。



一、安装nginx
首先我们需要在安装了 ansible 的机器上编译安装好nginx,详细步骤如下:
1、下载解压

# cd /usr/local/src/
# wget http://nginx.org/download/nginx-1.4.4.tar.gz
# tar -zxvf nginx-1.4.4.tar.gz

2、安装依赖包
# yum install -y gcc zlib-devel openssl openssl-devel pcre-devel

3、配置编译参数
# cd nginx-1.4.4

# ./configure \
--prefix=/usr/local/nginx \
--with-http_realip_module \
--with-http_sub_module \
--with-http_gzip_static_module \
--with-http_stub_status_module\
--with-pcre
3、编译安装nginx

# make
# make install
4、编写启动脚本

# vim /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="/usr/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
保存退出后修改启动脚本权限:

# chmod 755 /etc/init.d/nginx


5、更改配置文件
# > /usr/local/nginx/conf/nginx.conf                //清空原有配置
# vim /usr/local/nginx/conf/nginx.conf


user nobody nobody;
worker_processes 2;
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
{
    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_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;
    include vhosts/*.conf;

}
保存退出后检查配置文件是否有错:
# /usr/local/nginx/sbin/nginx -t

新建虚拟主机目录(后面用于测试):
# mkdir /usr/local/nginx/conf/vhosts
6、启动服务

# chkconfig --add nginx

# chkconfig nginx on
# service nginx start



二、下发nginx
1、新建所需目录
# cd /etc/ansible/
# mkdir -p nginx_install/roles
# cd nginx_install/roles/
# mkdir common install
# mkdir common/tasks
# mkdir install/{files,tasks,templates,vars}
说明:官方建议创建以下目录(我这里简单化了,不需要的就没有创建):
# mkdir -p nginx_install/roles/{common,delete,install}/{handlers,files,meta,tasks,templates,vars}
roles目录下有三个角色,common为一些准备操作,delete为删除nginx的操作,install为安装nginx的操作。每个角色下面又有几个目录,handlers下面是当发生改变时要执行的操作,通常用在配置文件发生改变,重启服务。files为安装时用到的一些文件,meta为说明信息,说明角色依赖等信息,tasks里面是核心的配置文件,templates通常存一些配置文件,启动脚本等模板文件,vars下为定义的变量。


2、打包nginx并拷贝文件
# cd /usr/local/

# tar czvf nginx.tar.gz nginx
# cp nginx.tar.gz /etc/ansible/nginx_install/roles/install/files/
# cp /etc/init.d/nginx /etc/ansible/nginx_install/roles/install/templates/
说明:把安装文件放于 install/files/ 目录下,把启动脚本放于install/templates/ 目录下。


3、定义common的tasks

# cd /etc/ansible/nginx_install/roles/
# vim common/tasks/main.yml            //定义nginx需要安装的一些依赖包

---- name: Install initializtion require softwareyum: name={{ item }} state=installedwith_items:    - gcc    - zlib-devel    - pcre-devel    - openssl-devel
4、定义install的vars
# vim install/vars/main.yml                           //定义变量


nginx_user: nobody
nginx_basedir: /usr/local/nginx

说明:这里的 nginx_user 要与 nginx.conf 配置文件中定义的用户一致。变量还可以定义一些其他的,如下:
nginx_port: 80

nginx_web_dir: /data/www
nginx_version: 1.4.4

5、定义install的tasks
# vim install/tasks/copy.yml



- name: Copy Nginx Softwarecopy: 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

说明:这里是拷贝文件到远程机器/tmp/目录下,然后解压。其中的 copy: src 相对于 install/files/ 目录下,template: src 相对于 install/templates/ 目录下。


# vim install/tasks/install.yml



- name: Create Nginx Useruser: name={{ nginx_user }} state=present createhome=no shell=/sbin/nologin
- name: Start Nginx Service
service: name=nginx state=started
- 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_web_dir目录,存放虚拟主机文件


# vim install/tasks/main.yml


- include: copy.yml
- include: install.yml

说明:这里创建的是调用 copy.yml 和 install.yml 的文件。


6、定义总入口文件


# cd /etc/ansible/nginx_install/
# vim install.yml

---
- hosts: testhost
remote_user: root
gather_facts: True
roles:
    - common
    - install



7、执行下发
先修改下 hosts 文件,因为之前实验把本机也添加到了 组里面去了,这里只保留一个远程机:
# vim /etc/ansible/hosts


192.168.0.114
# ansible-playbook install.yml



8、在远程机上测试结果

# rpm -qa |egrep 'gcc|zlib|pcre|openssl'
# ls /usr/local/nginx/
# ps aux |grep nginx

# chkconfig --list nginx

由上图可知下发已经成功。



三、更新nginx
生产环境中大多时候是需要管理配置文件的,安装软件包只是在初始化环境的时候用一下。下面我们来写个管理 nginx 配置文件的 playbook。
1、新建及拷贝文件

# cd /etc/ansible/
# mkdir -p nginx_config/roles
# cd nginx_config/roles/
# mkdir -p new/{vars,files,tasks,handlers}
# cp /usr/local/nginx/conf/nginx.conf new/files
# cp -r /usr/local/nginx/conf/vhosts new/files
说明:其中 new 为更新时用到的,后面会新建old 为回滚时用到的,new/files 下面为 nginx.conf文件 和 vhosts 目录,handlers 为重启 nginx 服务所需目录。
2、定义变量
# vim new/vars/main.yml


nginx_basedir: /usr/local/nginx
3、定义重新加载服务
# vim new/handlers/main.yml

- name: restart nginxshell: /etc/init.d/nginx reload

4、定义tasks核心任务
# vim 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

注意:这里的copy是相当于数组。notify定义了需要调用handlers/main.yml下的重启nginx。
5、定义总入口配置

# cd ..
# vim update.yml

---- hosts: testhost
user: root
roles:
- new

6、测试更新
1)新建一个虚拟主机配置文件
# vim roles/new/files/vhosts/1.conf

#msiyuetian.blog.iyunv.com
2)发布更新
# ansible-playbook update.yml       //右下可知更新成功

3)远程机器查看已经同步成功:



四、回滚nginx
关于回滚,需要在执行 playbook 之前先备份一下旧的配置,所以对于老配置文件的管理一定要严格,千万不能随便去修改线上机器的配置,并且要保证 new/files 目录下面的配置和线上的配置一致。

1、备份

# mkdir roles/old
# rsync -av roles/new/ roles/old/
注意:拷贝整个new/目录即实现备份,这里用rsync而不用cp,是因为rsync会直接覆盖相同的文件。若没有rsync命令,直接yum install -y rsync安装即可。
2、定义回滚入口
# vim backup.yml


---
- hosts: testhost
user: root
roles:
- old

3、更新

1)修改虚拟主机文件
# vim roles/new/files/vhosts/1.conf            //添加三行


#msiyuetian.blog.iyunv.com
#msiyuetian.blog.iyunv.com
#msiyuetian.blog.iyunv.com
#msiyuetian.blog.iyunv.com

2)下发更新
# ansible-playbook update.yml      //发布更新
3)远程机器查看是否更新

由上图可知已经更新成功
4、回滚
1)执行回滚
# ansible-playbook backup.yml

2)远程机器查看效果

由上图可知已经回滚成功。



样例库:https://github.com/dl528888/ansible-examples
我们可以下载整个样例库
# git clone git://https://github.com/dl528888/ansible-examples.git
页: [1]
查看完整版本: ansible playbook实战——下发部署nginx以及更新、回滚