码迷,mamicode.com
首页 > 其他好文 > 详细

使用SaltStack部署Nginx

时间:2015-04-24 01:19:50      阅读:274      评论:0      收藏:0      [点我收藏+]

标签:salt automation config_manage


规划:

    1、编译安装nginx

    2、实现配置文件、服务、用户、日志切割、虚拟主机的自动部署

    3、针对不同客户端资源配置的不同,利用grains实现可变配置

    4、利用pillar实现客户端功能区别配置


环境:

master: 192.168.111.129(Hostname: Server2)
client: 192.168.111.128(Hostname: Server1)


(这里是ID标识,为了实现配置不同的需要)


配置仓库根目录:

[root@Server2 ~]# vim /etc/salt/master
file_roots:
  base:
    - /srv/salt

创建入口文件:

[root@Server2 ~]# cat /srv/salt/top.sls 
base:
  ‘*‘:
    - nginx.init

先贴目录:

[root@Server2 nginx]# tree 
.
├── conf.sls
├── files
│   ├── nginx
│   ├── nginx-1.4.5.tar.gz
│   ├── nginx.conf
│   ├── nginx_log_cut.sh
│   └── vhost.conf
├── gcc.sls
├── init.sls
├── install.sls
└── vhost.sls

下面逐个文件分析:

init.sls

[root@Server2 nginx]# cat init.sls 
include:
  - nginx.gcc
  - nginx.install
  - nginx.conf
  - nginx.vhost

  

引用的时候只需指定nginx目录即可,这里面包含有nginx目录下面的4个sls文件


install.sls  nginx安装

[root@Server2 nginx]# cat install.sls 
#nginx.tar.gz
nginx_source:
  file.managed:
    - name: /tmp/nginx-1.4.5.tar.gz
    - unless: test -e /tmp/nginx-1.4.5.tar.gz
    - source: salt://nginx/files/nginx-1.4.5.tar.gz
#extract
extract_nginx:
  cmd.run:
    - cwd: /tmp
    - names:
      - tar zxvf nginx-1.4.5.tar.gz
    - unless: test -d /tmp/nginx-1.4.5
    - require:
      - file: nginx_source
#user
nginx_user:
  user.present:
    - name: nginx
    - uid: 1501
    - createhome: False
    - gid_from_name: True
    - shell: /sbin/nologin
#nginx_pkgs
nginx_pkg:
  pkg.installed:
    - pkgs:
      - gcc
      - openssl-devel
      - pcre-devel
      - zlib-devel
#nginx_compile
nginx_compile:
  cmd.run:
    - cwd: /tmp/nginx-1.4.5
    - names:
      - ./configure --prefix=/usr/local/nginx  --user=nginx  --group=nginx  --with-http_ssl_module  --with-http_gzip_static_module --http-client-body-temp-path=/usr/local/nginx/client/ --http-proxy-temp-path=/usr/local/nginx/proxy/   --http-fastcgi-temp-path=/usr/local/nginx/fcgi/   --with-poll_module  --with-file-aio  --with-http_realip_module  --with-http_addition_module --with-http_random_index_module   --with-pcre   --with-http_stub_status_module
      - make
      - make install
    - require:
      - cmd: extract_nginx
      - pkg:  nginx_pkg
    - unless: test -d /usr/local/nginx
#cache_dir
cache_dir:
  cmd.run:
    - names:
      - mkdir -p /usr/local/nginx/{client,proxy,fcgi} && chown -R nginx.nginx /usr/local/nginx/
    - unless: test -d /usr/local/nginx/client/
    - require:
      - cmd: nginx_compile

 

nginx编译安装,涉及文件管理、包管理、用户管理及cmd运用,其中注意的是如果使用cmd,它每次同步客户端时都会执行,为了防止这一现象,使用unless可解决


安装好以后,下面看配置文件的管理conf.sls

[root@Server2 nginx]# cat conf.sls 
include:
  - nginx.install     
{% set nginx_user = ‘nginx‘ + ‘ ‘ + ‘nginx‘ %}  
nginx_conf:
  file.managed:   
    - name: /usr/local/nginx/conf/nginx.conf
    - source: salt://nginx/files/nginx.conf
    - template: jinja
    - defaults:
      nginx_user: {{ nginx_user }}      
      num_cpus: {{grains[‘num_cpus‘]}}  
nginx_service:  
  file.managed:
    - name: /etc/init.d/nginx
    - user: root
    - mode: 755
    - source: salt://nginx/files/nginx
  cmd.run:    
    - names:
      - /sbin/chkconfig --add nginx
      - /sbin/chkconfig  nginx on
    - unless: /sbin/chkconfig --list nginx
  service.running:     
    - name: nginx
    - enable: True
    - reload: True
    - watch:
      - file: /usr/local/nginx/conf/*.conf
nginx_log_cut:                 
  file.managed:
    - name: /usr/local/nginx/sbin/nginx_log_cut.sh
    - source: salt://nginx/files/nginx_log_cut.sh
  cron.present:             
    - name: sh /usr/local/nginx/sbin/nginx_log_cut.sh
    - user: root
    - minute: 10
    - hour: 0
    - require:
      - file: nginx_log_cut

 

这里使用到了nginx.conf,nginx_log_cut.sh,nginx三个文件,这三个文件都存放在nginx/files目录下;我们来看下


nginx启动脚本

[root@Server2 files]# cat nginx
#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15 
# description:  Nginx is an HTTP(S) server, HTTP(S) reverse #               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /usr/local/nginx/conf/nginx.conf
# pidfile:     /usr/local/nginx/logs/nginx.pid
 
# Source function library.
. /etc/rc.d/init.d/functions
 
# Source networking configuration.
. /etc/sysconfig/network
 
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
 
nginx="/usr/local/nginx/sbin/nginx"
prog=$(basename $nginx)
 
NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"
 
 
lockfile=/var/lock/subsys/nginx
 
make_dirs() {
   # make required directories
   user=`$nginx -V 2>&1 | grep "configure arguments:" | sed ‘s/[^*]*--user=\([^ ]*\).*/\1/g‘ -`
   if [ -z "`grep $user /etc/passwd`" ]; then
       useradd -M -s /bin/nologin $user
   fi
   options=`$nginx -V 2>&1 | grep ‘configure arguments:‘`
   for opt in $options; do
       if [ `echo $opt | grep ‘.*-temp-path‘` ]; then
           value=`echo $opt | cut -d "=" -f 2`
           if [ ! -d "$value" ]; then
               # echo "creating" $value
               mkdir -p $value && chown -R $user $value
           fi
       fi
   done
}
 
start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}
 
stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}
 
restart() {
    configtest || return $?
    stop
    sleep 1
    start
}
 
reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}
 
force_reload() {
    restart
}
 
configtest() {
  $nginx -t -c $NGINX_CONF_FILE
}
 
rh_status() {
    status $prog
}
 
rh_status_q() {
    rh_status >/dev/null 2>&1
}
 
case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac

nginx主配置文件

[root@Server2 files]# cat nginx.conf 
#
user  {{ nginx_user }};
worker_processes {{grains[‘num_cpus‘]}};
error_log  logs/nginx_error.log  notice;
pid        /usr/local/nginx/sbin/nginx.pid;
worker_rlimit_nofile 65535;
events
     {
              use epoll;
              worker_connections 65535;
      }
http
     {
              include       mime.types;
              default_type  application/octet-stream;
              charset  utf-8;
              server_names_hash_bucket_size 128;
              client_header_buffer_size 32k;
              large_client_header_buffers 4 32k;
              client_max_body_size 128m;
              sendfile on;
              tcp_nopush     on;
              keepalive_timeout 60;
              tcp_nodelay on;
              server_tokens off;
              client_body_buffer_size  512k;
              gzip on;
              gzip_min_length  1k;
              gzip_buffers     4 16k;
              gzip_http_version 1.1;
              gzip_comp_level 2;
              gzip_types      text/plain application/x-javascript text/css application/xml;
              gzip_vary on;
      log_format  main  ‘$remote_addr - $remote_user [$time_local] "$request" ‘
                            ‘$status $body_bytes_sent "$http_referer" ‘
                                ‘"$http_user_agent" "$http_x_forwarded_for" "$host"‘ ;
              include vhost*.conf;
       }

日志切割脚本

[root@Server2 files]# cat nginx_log_cut.sh 
#!/bin/bash
logs_path=/usr/local/nginx/logs
yesterday=`date -d "yesterday" +%F`
mkdir -p $logs_path/$yesterday
cd $logs_path
for nginx_logs in `ls *log` ;
do
mv $nginx_logs ${yesterday}/${yesterday}-${nginx_logs}
kill -USR1  `cat /usr/local/nginx/sbin/nginx.pid`
done

虚拟主机的配置使用到了pillar,根据pillar配置不同的client使用不同的配置文件,先来看pillar的配置


pillar目录

[root@Server2 pillar]# pwd
/srv/pillar
[root@Server2 pillar]# ls
top.sls  vhost.sls

pillar的配置

[root@Server2 pillar]# cat top.sls 
base:
  ‘*‘:
    - vhost
[root@Server2 pillar]# cat vhost.sls 
vhost:
  {% if ‘Server‘ in grains[‘id‘] %}
  - name: www 
    target: /usr/local/nginx/conf/vhost_www.conf
  {% else %}
  - name: bbs
    target: /usr/local/nginx/conf/vhost_bbs.conf
  {% endif %}

下面是虚拟主机的配置文件管理vhost.sls

[root@Server2 nginx]# pwd
/srv/salt/nginx
[root@Server2 nginx]# cat vhost.sls 
include:
  - nginx.install
{% for vhostname in pillar[‘vhost‘] %}
{{vhostname[‘name‘]}}:
  file.managed:
    - name: {{vhostname[‘target‘]}}
    - source: salt://nginx/files/vhost.conf
    - target: {{vhostname[‘target‘]}}
    - template: jinja
    - defaults:
      server_name: {{grains[‘fqdn_ip4‘][0]}} 
      log_name: {{vhostname[‘name‘]}}
    - watch_in:
      service: nginx
{% endfor %}

这里使用到了vhost.conf文件,我们来看下

[root@Server2 files]# pwd
/srv/salt/nginx/files
[root@Server2 files]# cat vhost.conf 
server
        {
                listen       80;
                server_name {{ server_name }};
                index index.html index.htm ;
                root  html;
                #location ~ .*\.(php|php5)?$
                #        {
                #                try_files $uri =404;
                #                fastcgi_pass  unix:/tmp/php-cgi.sock;
                #                fastcgi_index index.php;
                #                include fcgi.conf;
                #        }
                location /status {
                       stub_status on;
                }
                location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
                        {
                                expires      30d;
                        }
                location ~ .*\.(js|css)?$
                        {
                                expires      1d;
                        }
                access_log  logs/{{ log_name }}-access.log  main;
        }

好了,以上是所有的配置,下面我们来看下执行结果。

salt ‘Server1‘ state.highstate
Summary
-------------
Succeeded: 17
Failed:     0
-------------
Total:     17

执行成功,来看下配置文件

[root@Server1 conf]# ls -lt *.conf
-rw-r--r--. 1 nginx nginx  963 Apr  4 20:06 vhost_www.conf
-rw-r--r--. 1 nginx nginx 1339 Apr  4 20:06 nginx.conf
............
[root@Server1 conf]# cat vhost_www.conf 
server
        {
                listen       80;
                server_name 192.168.111.128;
                index index.html index.htm ;
                root  html;
                #location ~ .*\.(php|php5)?$
                #        {
                #                try_files $uri =404;
                #                fastcgi_pass  unix:/tmp/php-cgi.sock;
                #                fastcgi_index index.php;
                #                include fcgi.conf;
                #        }
                location /status {
                       stub_status on;
                }
                location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
                        {
                                expires      30d;
                        }
                location ~ .*\.(js|css)?$
                        {
                                expires      1d;
                        }
                access_log  logs/www-access.log  main;
        }


与我上面的pillar配置相符合,grains[‘id‘]中含有‘Server‘,配置文件是vhost_www.conf


来查看下192.168.111.128的执行结果

[root@Server1 conf]# ls -lt *.conf
-rw-r--r--. 1 nginx nginx  963 Apr  4 21:15 vhost_www.conf
............

本文出自 “往事随风” 博客,谢绝转载!

使用SaltStack部署Nginx

标签:salt automation config_manage

原文地址:http://sdwang.blog.51cto.com/8432181/1637691

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!