saltstack SLS

SLS文件定义

SLS(代表SaLt State文件)是Salt State系统的核心。SLS描述了系统的目标状态,由格式简单的数据构成。这经常被称作配置管理

top.sls 是配置管理的入口文件,一切都是从这里开始,在master 主机上,默认存放在/srv/salt/目录. 

top.sls 默认从 base 标签开始解析执行,下一级是操作的目标(被控主机),可以通过正则,grain模块,或分组名,来进行匹配,再下一级是要执行的state文件,不包换扩展名。

创建top.sls

(一)被控主机的匹配

#通过正则进行匹配的示例,
base:
  '*':
    - users    #为users.sls或users目录

#通过分组名进行匹配的示例,必须要有 - match: nodegroup
base:
  master1:
    - match: nodegroup    
    - users

#通过grain模块匹配的示例,必须要有- match: grain
base:
  'os:CentOS':
    - match: grain
    - users

(二)编写state文件

 首先说一下sls的命名空间

A)、SLS文件的扩展名 .sls 被省略。 (例如. webserver.sls 变成 webserver)
B)、子目录可以更好的组织,每个子目录都由一个点来表示.(例如 webserver/dev.sls 可以简称为 webserver.dev)
C)、如果子目录创建一个init.sls的文件,引用的时候仅指定该目录即可. (例如 webserver/init.sls 可以简称为 webserver)
D)、如果一个目录下同时存在webserver.sls 和 webserver/init.sls,那么 webserver/init.sls 将被忽略,SLS文件引用的webserver将只引用webserver.sls

 示例:

1)初始化配置

[root@k8s_master salt]# cat /etc/salt/master | grep -v '^#|^$'
cachedir: /var/cache/salt/master
auto_accept: True
file_recv: True
file_roots:
  base:
    - /srv/salt/
pillar_roots:
  base:
    - /srv/pillar
pillar_opts: True
nodegroups:
   master1: 'L@k8s_master'
   agents: 'L@k8s_node1,k8s_node2'

2)配置grains_module

创建目录并编写脚本

[root@k8s_master salt]#install -d /srv/salt/_grains

[root@k8s_master salt]# cat /srv/salt/_grains/test_grains.py 
#!/usr/bin/env python
#-*-coding:utf-8-*-

import os,sys,commands

def get_custom_grains():
    grains = {}
    _open_file=65535
    try:
        getulimit = commands.getstatusoutput('source /etc/profile;ulimit -n')
    except Exception,e:
        print e
    print getulimit,type(getulimit)
    if getulimit[0] == 0:
        _open_file=int(getulimit[1])
    grains['max_open_files'] = _open_file
    return grains

刷新并重载模块

#同步grains模块,运行
[root@k8s_master pillar]#salt '*' saltutil.sync_all

#刷新模块(让minion编译模块)
[root@k8s_master pillar]#salt '*' sys.reload_modules

验证

[root@k8s_master pillar]# salt '*' grains.item max_open_files
k8s_node1:
    ----------
    max_open_files:
        1024
k8s_node2:
    ----------
    max_open_files:
        1024
k8s_master:
    ----------
    max_open_files:
        1024

3)配置pillar

[root@k8s_master pillar]# cat top.sls 
base:
  'master1':
    - match: nodegroup
    - master1

  'agents':
    - match: nodegroup
    - agents
    
[root@k8s_master pillar]# cat master1.sls 
nginx:
    root: /www
[root@k8s_master pillar]# cat agents.sls 
nginx:
    root: /data

验证

[root@k8s_master pillar]# salt '*' pillar.data nginx
k8s_master:
    ----------
    nginx:
        ----------
        root:
            /www
k8s_node2:
    ----------
    nginx:
        ----------
        root:
            /data
k8s_node1:
    ----------
    nginx:
        ----------
        root:
            /data

4)配置state

[root@k8s_master salt]# cat top.sls 
base:
  '*':
    - nginx

[root@k8s_master salt]# cat nginx.sls 
nginx:              #state名称
  pkg:              #管理对象类型:pkg(进行软件安装 yum/apt)
   - installed         #pkg要执行的方法: install,如果未安装就进行安装
  file.managed:
   - source: salt://nginx/nginx.conf      #配置模板文件位置
   - name: /etc/nginx/nginx.conf
   - user: root
   - group: root
   - mode: 644
   - template: jinja
- backup:minion      #备份
- require: - pkg: nginx service.running: - enable: True        #检查服务是否在开机启动服务队列中 - reload: True        #表示服务支持reload操作,不加则默认执行restart操作 - watch:            #检测nginx.conf是否发生变化,如果发生变化会执行reload操作,pkg为确保nginx安装成功 - file: /etc/nginx/nginx.conf - pkg: nginx

nginx.conf配置文件

[root@k8s_master salt]# cat nginx/nginx.conf 
user nginx;
worker_processes  {{ grains['num_cpus'] }};  #采用grains获取本地的值,与设备cpu核数一致
{% if grains['num_cpus'] == 2 %}         
worker_cpu_affinity 01 10;            #分配cpu
{% elif grains['num_cpus'] == 1 %}
worker_cpu_affinity 0001;
{% elif grains['num_cpus'] == 4 %}
worker_cpu_affinity 1000 0100 0010 0001;
{% elif grains['num_cpus'] >= 8 %}
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;
{% else %}
worker_cpu_affinity 1000 0100 0010 0001;
{% endif %}


worker_rlimit_nofile {{ grains['max_open_files'] }};  #文件描述符
error_log  /var/log/nginx/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  {{ grains['max_open_files'] }} ; #与文件描述符数量一致
}


http {
    include       mime.types;
    default_type  application/octet-stream;


#    log_format  main  '$remote_addr - $remote_user [$time_local] $http_host $request_method  "$uri" "$query_string"'
 #                      '$status $body_bytes_sent "$http_referer" $upstream_status $upstream_addr $request_time $upstream_response_time'
 #                     '"$http_user_agent" "$http_x_forwarded_for"';
    
     log_format log_json '{"@timestamp": "$time_iso8601","remote_addr": "$remote_addr","remote_user": "$remote_user","request_method": "$request_method","uri": "$uri","query_string": "$query_string","status": "$status","body_bytes_sent": "$body_bytes_sent","http_referrer": "$http_referer","upstream_status": "$upstream_status","upstream_addr" : "$upstream_addr","request_time": "$request_time","upstream_response_time": "$upstream_response_time","request": "$request","http_user_agent": "$http_user_agent","http_x_forwarded_for": "$http_x_forwarded_for"}';
 
#   log_format json '{"@timestamp":"$time_iso8601",'
 #                 '"host":"$server_addr",'
  #                '"clientip":"$remote_addr",'
   #               '"remote_user":"$remote_user",'
    #              '"request_method":"$request_method",'
     #             '"request":"$request",'
#		  '"uri":"$uri",'
 #                 '"query_string":"$query_string",'
  #                '"http_user_agent":"$http_user_agent",'
   #               '"size":$body_bytes_sent,'
    #              '"responsetime":$request_time,'
     #             '"upstreamtime":"$upstream_response_time",'
      #            '"upstreamhost":"$upstream_addr",'
       #           '"url":"$uri",'
        #          '"domain":"$host",'
         #         '"client_realip":"$http_x_forwarded_for",'
          #        '"referer":"$http_referer",'
           #       '"status":"$status"}';

    access_log /var/log/nginx/access.log  log_json;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  {{ grains['ip4_interfaces']['ens33'][0] }};  #获取本地的ip(grains)
	root {{ pillar['nginx']['root'] }};               #获取web目录(pillar里定制)
	index index.php index.html index.htm;
        #charset koi8-r;


        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
	location /ngx_status 
    	{
        	stub_status on;
        	access_log off;
    	}

	location ~ ^/(status|ping)$
	{
		include fastcgi_params;
        	fastcgi_pass 127.0.0.1:9000;
        	fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
	}
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ .php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ .php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}
	location ~ .php$ {
            fastcgi_connect_timeout 300;
            fastcgi_read_timeout 300;
            fastcgi_send_timeout 300;
            fastcgi_buffer_size 128k;
            fastcgi_buffers 32 32k;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

 执行刷新state配置

[root@k8s_master salt]# pwd
/srv/salt
[root@k8s_master salt]#salt '*' state.highstate

效果图

原文地址:https://www.cnblogs.com/FRESHMANS/p/8295382.html