salt源碼裝nginx

   其實早就知道saltstack的強大,其中的state,grain,pillar,是個很好的自動化配置工具!!由於在上一個公司像這樣的腳本都已經寫好,其實沒有太大的動力去學salt的更強大的功能。在這家公司就是深入研究一下salt。在之前做了好多的準備。。。今天下午才做成功實驗!!!!廢話不多說。上乾貨!!

思路:

    1.使用grains收集cpu信息、以及打開文件最大等信息結合jinja配置nginx.conf.

    2.使用salt推送文件。

一、做準備工作


(1)環境介紹


master: 192.168.100.127   web1

minion: 192.168.100.129   web2     192.168.100.90 db1   192.168.100.134  db2


(2)安裝saltmaster

   我們需要安裝其他的yum源,這樣才能順利的安裝master和minion。


master

       yum  -y install epel-release

       yum install salt-master

編輯配置文件vim /etc/salt/master

file_roots:
    base:
      - /srv/salt/
 pillar_roots:
   base:
     - /srv/pillar
 pillar_opts: True
 order_masters: True

重啓服務:service salt-master restart

主要配置是如上所示。。


(3)安裝salt-minion

minion

       yum -y install epel-release

       yum  install salt-minion

編輯minion的配置文件vim /etc/salt/minion


#master爲你所指定的master的ip或者機器名

master: web1

#id爲你配置的機器minion的ip或者機器名

id: db2


重啓服務: service salt-minion restart


其他的minion同上!!!!

(4)連通

master端:

salt-key  -L 會顯示所有minion向master發送的公鑰。但是沒有被master接受!!

salt-key  -A  可以接受那些minion發送的公鑰也就是master同意了作爲他們的“頭”了


可以驗證一下: salt ‘*’ test.ping


[root@master files]# salt '*' test.ping

db2:

    True

web1:

    True

web2:

    True

db1:

    True

[root@master files]# 

此時說明master和minion之間可以互相通信了。。。。



二、目錄樹

(1)下面的圖是這次實驗的目錄樹


srv

├── pillar

│   ├── dbserver.sls

│   ├── top.sls

│   └── webserver.sls

└── salt

    ├── _grains

    │   └── nginx_config.py

    ├── nginx

    │   ├── conf.sls

    │   ├── files

    │   │   ├── nginx

    │   │   ├── nginx-1.8.0.tar.gz

    │   │   └── nginx.conf

    │   ├── init.sls

    │   ├── install.sls

    │   └── server.sls

    └── top.sls

(2)介紹

所有的state文件的執行都要個top.sls 該文件是入口文件。

例如salt下top.sls 要想執行 conf.sls,install.sls server.sls 必須有個top.sls

規範爲主:在在某個項目都要有個獨立的文件夾,其中有個init.sls 文件裏面包括了這次要執行的state文件。廢話不多說!!上乾貨!!

三、編寫grain與pillar

(1)vim nginx_config.py

#該文件是用來獲取打開文件最大數的方便了nginx.conf的參數的確定

  #  1 #!/usr/bin/python
  2 import os
  3 import sys
  4 import commands
  5 def NginxGrains():
  6     grains={}
  7     max_open_file=65535
  8     try:
  9         getulimit=commands.getstatusoutput('source /etc/profile;ulimit -n')
 10     except Exception,e:
 11         pass
 12     if getulimit[0]==0:
 13         max_open_file=int(getulimit[1])
 14         grains['max_open_file']=max_open_file
 15         return grains
  
  
  (2)測試數據
 刷新grain模塊:salt ‘*’ saltutil.sync_all
 檢驗數據加載情況:salt ‘*’ grains.item max_open_file
     [root@master _grains]# salt '*' grains.item max_open_file
web1:
    ----------
    max_open_file:
        1024
web2:
    ----------
    max_open_file:
        1024
db2:
    ----------
    max_open_file:
        1024
db1:
    ----------
    max_open_file:
        1024
 數據測試成功!
 
 (3)編寫pillar
 vim top.sls
 base:
   'web*':
     - webserver
   'db*':
     - dbserver
 
 以上是正則匹配 ‘web*’‘db*’
 在此類文件中執行state文件可以省略後綴名.sls
 vim webserver.sls
 nginx:
   root: /data
  
  vim dbserver.sls
  nginx:
    root: /WWW
 
 
 pillar在此的作用是根據webserver和dbserver做區分,webserver的根目錄爲/data,而dbserver爲/WWW
 .簡單的實現這些,其他的可以根據需求來定義。

  刷新pillar:salt ‘*’saltutil.refresh_pillar
  
  檢驗數據的成效:salt '*' pillar.data nginx 如下所示:
  
  [root@master pillar]# salt '*' pillar.data nginx
  該命令的含義是:獲取pillar的數據 名稱是nginx的數據,pillar的格式用一個詞是有相當強的歸屬感!意思就是root這個參數是歸屬在nginx名稱下的。同樣root下也可以繼續有參數。。
web1:
    ----------
    nginx:
        ----------
        root:
            /data
web2:
    ----------
    nginx:
        ----------
        root:
            /data
db1:
    ----------
    nginx:
        ----------
        root:
            /www
db2:
    ----------
    nginx:
        ----------
        root:
            /www
四、編寫salt文件下的nginx項目

vim  top.sls

   1 base:
  2   '*':
  3     - nginx                                                                          此處的nginx表明要執行文件夾裏的sls文件。
  
  
  cd nginx
  
  vim init.sls
                                                                                             include:
  2   - nginx.install
  3   - nginx.conf
  4   - nginx.server                          

   nginx.install 表示 要執行nginx目錄下的install.sls文件
此處的點代表路徑。省略後綴名於是就是nginx.install。其他一樣。順序不能變原因就在下面。。。

vim install.sls 

#該文件是安裝過程的文件


  1 #nginx.tar.gz

  2 nginx_source:

  3   file.managed:

  4     - name: /tmp/nginx-1.8.0.tar.gz

  5     - unless: test -e /tmp/nginx-1.8.0.tar.gz

  6     - source: salt://nginx/files/nginx-1.8.0.tar.gz

  7 #extract

  8 extract_nginx:

  9   cmd.run:

 10     - cwd: /tmp

 11     - names:

 12       - tar -zxvf nginx-1.8.0.tar.gz

 13     - unless: test -d /tmp/nginx-1.8.0

 14     - reuqire:

 15       - file: nginx_source

 16 #user

 17 nginx_user:

 18   user.present:

 19     - name: nginx

 20     - uid: 610

 21     - createhome: False

 22     - shell: /sbin/nologin

 23 #nginx_pkgs

 24 nginx_pkgs:

 25   pkg.installed:

 26     - pkgs:

 27       - gcc

 28       - openssl

 29       - openssl-devel

 30       - pcre-devel

 31       - zlib-devel

 32 #nginx_compile

 33 nginx_compile:

 34   cmd.run:

 35     - cwd: /tmp/nginx-1.8.0

 36     - names:

 37       - ./configure --prefix=/nginx/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_sta    tus_module

 38       - pwd

 39       - make

 40       - make install

 41     - require:

 42       - cmd: extract_nginx

 43       - pkg: nginx_pkgs

 44     - unless: test -d /nginx/nginx

 45 #cache_dir

 46 cache_dir:

 47   cmd.run:

 48     - names:

 49       - mkdir -p /nginx/nginx{client,proxy,fcgi} && chown -R nginx.nginx /nginx/nginx/

 50       - mkdir -p /nginx/nginx/conf/vhost && chown -R nginx.nginx /nginx/nginx/conf/vhost

 51     - unless: test -d /nginx/nginx/client

 52     - require:

 53       - cmd: nginx_compile



vim  conf.sls

#該文件是從master傳送conf文件。啓動過程依賴conf文件。


  1 include:

  2   - nginx.install

  3 nginx_service:

  4   file.managed:

  5     - name: /nginx/nginx/conf/nginx.conf

  6     - user: nginx

  7     - mode: 644

  8     - source: salt://nginx/files/nginx.conf

  9     - template: jinja

 10   service.running:

 11     - name: nginx

 12     - enable: True

 13     - reload: True

 14     - watch:

 15       - file: /nginx/nginx/conf/nginx.conf

vim    server.sls

#該文件是傳送啓動腳本,服務啓動依賴該腳本

 

  1 include:

  2   - nginx.install

  3 server:

  4   file.managed:

  5     - name: /etc/init.d/nginx

  6     - user: root

  7     - mode: 755

  8     - source: salt://nginx/files/nginx

  9   service.running:

 10     - name: nginx

 11     - enable: True

 12     - reload: True

 13     - watch:

 14       - file: /etc/init.d/nginx

 15 command:

 16   cmd.run:

 17     - names:

 18       - /sbin/chkconfig --add nginx

 19       - /sbin/chkconfig --nginx on

 20     - unless: /sbin/chkconfig --list nginx

 

 五、files文件夾

在目錄樹中有files這裏面是放了在安裝過程中需要的文件。例如配置文件、啓動腳本、安裝包、

vim nginx.conf

1 # For more information on configuration, see:  

  2 user              nginx;

  3 worker_processes  {{ grains['num_cpus'] }};

  4 {% if grains['num_cpus'] == 1 %}

  5 worker_cpu_affinity 1 ;

  6 {% elif grains['num_cpus'] == 2 %}

  7 worker_cpu_affinity 01 10;

  8 {% elif grains['num_cpus'] == 4 %}

  9 worker_cpu_affinity 1000 0100 0010 0001;

 10 {% elif grains['num_cpus'] >= 8 %}

 11 worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;

 12 {% else %}

 13 worker_cpu_affinity 1000 0100 0010 0001;

 14 {% endif %}

 15 worker_rlimit_nofile {{ grains['max_open_file'] }};

 16 

 17 error_log  /var/log/nginx/error.log;

 18 #error_log  /var/log/nginx/error.log  notice;  

 19 #error_log  /var/log/nginx/error.log  info;  

 20 

 21 pid        /var/run/nginx.pid;

 22 

 23 events {

 24         worker_connections  {{ grains['max_open_file'] }};

 25  }

 26 

 27 http

 28      {

 29               include       mime.types;

 30               default_type  application/octet-stream;

 31               charset  utf-8;

 32               server_names_hash_bucket_size 128;

 33               client_header_buffer_size 32k;

 34               large_client_header_buffers 4 32k;

 35               client_max_body_size 128m;

 36               sendfile on;

 37               tcp_nopush     on;

 38               keepalive_timeout 60;

 39               tcp_nodelay on;

 40               server_tokens off;

 41               client_body_buffer_size  512k;

 42               gzip on;

 43               gzip_min_length  1k;

 44               gzip_buffers     4 16k;

 45               gzip_http_version 1.1;

 46               gzip_comp_level 2;

 47               gzip_types      text/plain application/x-javascript text/css application/xml;

 48               gzip_vary on;

 49               log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '

 50                                 '$status $body_bytes_sent "$http_referer" '

 51                                 '"$http_user_agent" "$http_x_forwarded_for" "$host"' ;

 52 

 53 

 54         server {

 55                          listen            80;

 56                          root              {{ pillar['nginx']['root'] }};

 57                          index             index.html;

 58 

 59                 }

 60 

 61               include vhost/*.conf;

 62        }

關鍵注意加黑的字體的參數的數值。。。這就是pillar和grain的威力!!!!!

vim nginx

#啓動腳本沒什麼可說的

 1 #!/bin/sh

  2 #

  3 # nginx - this script starts and stops the nginx daemon

  4 #

  5 # chkconfig:   - 85 15 

  6 # description:  Nginx is an HTTP(S) server, HTTP(S) reverse \

  7 #               proxy and IMAP/POP3 proxy server

  8 # processname: nginx

  9 # config:      /nginx/nginx/conf/nginx.conf

 10 # pidfile:     /nginx/nginx/logs/nginx.pid

 11 

 12 # Source function library.

 13 . /etc/rc.d/init.d/functions

 14 

 15 # Source networking configuration.

 16 . /etc/sysconfig/network

 17 

 18 # Check that networking is up.

 19 [ "$NETWORKING" = "no" ] && exit 0

 20 

 21 nginx="/nginx/nginx/sbin/nginx"

 22 prog=$(basename $nginx)

 23 

 24 NGINX_CONF_FILE="/nginx/nginx/conf/nginx.conf"

 25 

 26 

 27 lockfile=/var/lock/subsys/nginx

 28 

 29 make_dirs() {

 30    # make required directories

 31    user=`$nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`

 32    if [ -z "`grep $user /etc/passwd`" ]; then

 33        useradd -M -s /bin/nologin $user

 34    fi

 35    options=`$nginx -V 2>&1 | grep 'configure arguments:'`

 36    for opt in $options; do

 37        if [ `echo $opt | grep '.*-temp-path'` ]; then

 38            value=`echo $opt | cut -d "=" -f 2`

 39            if [ ! -d "$value" ]; then

 40                # echo "creating" $value

 41                mkdir -p $value && chown -R $user $value

 42            fi

 43        fi

 44    done

 

45 }

 46 

 47 start() {

 48     [ -x $nginx ] || exit 5

 49     [ -f $NGINX_CONF_FILE ] || exit 6

 50     make_dirs

 51     echo -n $"Starting $prog: "

 52     daemon $nginx -c $NGINX_CONF_FILE

 53     retval=$?

 54     echo

 55     [ $retval -eq 0 ] && touch $lockfile

 56     return $retval

 57 }

 58 

 59 stop() {

 60     echo -n $"Stopping $prog: "

 61     killproc $prog -QUIT

 62     retval=$?

 63     echo

 64     [ $retval -eq 0 ] && rm -f $lockfile

 65     return $retval

 66 }

 67 

 68 restart() {

 69     configtest || return $?

 70     stop

 71     sleep 1

 72     start

 73 }

 74 

 75 reload() {

 76     configtest || return $?

 77     echo -n $"Reloading $prog: "

 78     killproc $nginx -HUP

 79     RETVAL=$?

 80     echo

 81 }

 82 

 83 force_reload() {

 84     restart

 85 }

 86 

 87 configtest() {

 88   $nginx -t -c $NGINX_CONF_FILE

 89 }

 90 

 91 rh_status() {

 92     status $prog

 93 }

 94 

 95 rh_status_q() {

 96     rh_status >/dev/null 2>&1

 97 }

 98 

 99 case "$1" in

100     start)

101         rh_status_q && exit 0

102         $1

103         ;;

104     stop)

105         rh_status_q || exit 0

106         $1

107         ;;

108     restart|configtest)

109         $1

110         ;;

111     reload)

112         rh_status_q || exit 7

113         $1

114         ;;

115     force-reload)

116         force_reload

117         ;;

118     status)

119         rh_status

120         ;;

121     condrestart|try-restart)

122         rh_status_q || exit 0

123             ;;

124     *)

125         echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"

126         exit 2

127 esac

                                              

  到此主要步驟結束。

 

六、安裝

master端:salt ‘*’ state.highstate

如果你運氣好的話,一遍就成功了。這基本上是不可能的!!!!!

假設是成功的:

會有如下:

nginx就能用了唄。。

跟手動編譯的一模一樣!!!

 最重要的是pillar和grain起的作用!!

                              


七、問題總結

(1)、就是在編譯安裝時,./configure 通過了,可是在make,make install 相繼報錯make: *** No targets specified and no makefile found.  Stop

這意思就是該文件夾下沒有Makefile。

解決辦法:我認爲是不是路徑變了。於是在make和make install  前加了條pwd 看看是不是該路徑。沒想到加上這條命令這個問題就解決了。

(2)就是在推送啓動腳本和nginx配置文件時,明明存在就是不能解釋,報類似的錯誤:

[root@web2 init.d]# service nginx start

env: /etc/init.d/nginx: No such file or directory


突然想起來原來我是在windows上編寫的。於是用dos2unix 這個命令解決了


(3)就是在安裝過程中,saltstack有個不好的地方就是明明上一次還行,下一次同樣的系統就是不可以了。這樣的解決辦法就是多推送幾次。前提是之前的問題都解決了。還出現同樣的問題。



好了,就到這吧。學得所有關於saltstack的知識都是爲了能按照需求×××應用!!



                                              


               


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章