1. 程式人生 > >saltstack常用模塊及組件備忘

saltstack常用模塊及組件備忘

1.4 .sh 代碼檢查 ast srv require 判斷 roles .com

Saltstack分為主控端和被控端。主控端的salt服務啟動:systemctl start salt-master,被控端的服務啟動:systemctl start salt-minion
1、Saltstack的防火墻配置
主控端防火墻允許TCP4505和4506端口,被控端不需要配置。原理是被控端直接與主控端的zeromq建立長鏈接,接受廣播到的任務信息並執行。

iptables -I INPUT -m state --state new -m tcp -p tcp --dport 4506 -j ACCEPT
iptables -I INPUT -m state --state new -m tcp -p tcp --dport 4505 -j ACCEPT

主控端的配置

vim /etc/salt/master
#綁定Master通信IP
interface: 192.168.40.10
#自動認證,如果是False就要進行手動認證
auto_accept: True
#指定saltstack的文件根目錄所在
file_roots:
  base:
        - /srv/salt

重啟服務讓配置生效:systemctl restart salt-master

被控端配置

vim /etc/salt/minion
#指定master主機的IP地址
master: 192.168.40.10
#修改被控端主機識別id
id: centos02

重啟服務讓配置生效:systemctl restart salt-minion

2、測試安裝saltstack的結果

[root@centos01 ~]# salt ‘centos02‘  test.ping
centos02:
    True

如果把centos02那麽就是測試所有的被控端

[root@centos01 ~]# salt ‘*‘ test.ping
centos02:
    True
centos03:
    True

3、利用saltstack遠程執行命令
命令行格式:salt ‘<操作目標>’ <方法> [參數]

[root@centos01 ~]# salt ‘centos02‘ cmd.run ‘free -m‘
centos02:
                  total        used        free      shared  buff/cache   available
    Mem:            472         119          76           3         275         308
    Swap:          1023           7        1016

-E,--pcre,通過正則表達式匹配,salt -E ‘.*02‘ cmd.run ‘free -m‘

-L,--list,以主機id名列表的形式進行過濾,即是主機名可以寫多個。salt -L ‘centos02,centos03‘ <方法>[參數]。

-S,--ipcidr,根據被控主機的IP地址或IP子網進行匹配, salt -S 192.168.40.11 test.ping; salt -S 192.168.40.12 test.ping。

4、常用的模塊和API
saltstack提供了非常豐富的功能模塊,涉及操作系統的基礎功能、常用工具支持等。

如果使用python腳本的方法來實現test.ping

>>> import salt.client
>>> client = salt.client.LocalClient()
>>> ret = client.cmd(‘centos02‘, ‘test.ping‘)
>>> print ret
{‘centos02‘: True}   ##以集合的形式

4.1、archive模塊,實現系統層面的壓縮包調用,支持gunzip、gzip、rar、tar、unrar、unzip等。

salt ‘centos02‘ archive.tar xf /tmp/access.tar.gz  ##解壓在/root目錄下
salt ‘centos02‘ archive.tar  /tmp/test.txt  ##壓縮在/tmp目錄下

api調用
client.cmd(‘centos02‘, ‘archive.tar‘, [‘xf‘, ‘/tmp/access.tar.gz‘])
4.2、cmd模塊,實現遠程命令行調用執行(使用的是root權限,所以風險高。)

salt ‘centos02‘ cmd.run ‘free -m‘

api調用
client.cmd(‘cnetos02‘, ‘cmd.run‘,[‘free -m‘])
4.3、cp模塊,實現遠程文件、目錄的復制,以及下載URL文件的操作。

##將指定被控主機的/etc/hosts文件復制到被控主機的salt的cache目錄下(cache目錄在/var/cache/salt/minion/localfiles/)
salt ‘centos02‘ cp.cache_local_file /etc/hosts
##將主服務器的file_roots指定位置下的目錄復制到被控主機
salt ‘centos02‘ cp.get_dir salt://apache/ /minion/  ##將file_roots指定的目錄,也就是/srv/salt目錄下的apache目錄復制到遠端的/minion/目錄下,如果沒有會自動創建該目錄。
##將主服務器file_roots指定位置下的文件復制到被控主機
salt ‘centos02‘ cp.get_file salt://apache/init.sls  /minion/dest.sls
##下載URL網頁內容到被控主機指定位置
salt ‘centos02‘ cp.get_url http://www.baidu.com /tmp/test.html

api調用
client.cmd(‘centos02‘, ‘cp.get_file‘, ( ‘salt://apache/init.sls ‘, ‘/minion/dest.sls‘)
4.4、cron模塊,實現被控主機上的crontab操作

##查看被控主機的root用戶的crontab清單
salt ‘centos02‘ cron.raw_cron root
##指定被控主機root用戶添加任務
salt ‘centos02‘ cron.set_job root ‘*‘ ‘*‘ ‘*‘ ‘*‘ ‘*‘ /bin/bash test.sh
##刪除指定被控主機的root用戶的任務
salt ‘centos02‘ cron.rm_job root /bin/bash test.sh

api調用
client.cmd(‘centos02‘, ‘cron.set_job‘,[‘root‘,‘‘,‘‘,‘‘,‘‘,‘*‘,‘/usr/local/weekly‘])
4.5、dnsutil模塊,實現被控制主機本地域名文件操作

#添加
salt ‘centos02‘ dnsutil.hosts_append /etc/hosts 127.0.0.1 www.test.com
##刪除
salt ‘centos02‘ dnsutil.hosts_remove /etc/hosts www.test.com

api調用
client.cmd(‘*‘, ‘dnsutil.hosts_append‘,[‘/etc/hosts‘,‘127.0.0.1‘,‘www.test.com‘])
4.6、file模塊,實現被控主機常見文件操作

##修改被控主機的/etc/passwd文件的擁有者和所有組,相當於在被控主機實現chown root:root /etc/passwd
salt ‘centos02‘ file.chown /etc/passwd root root
##復制指定被控主機本地/data/test.txt文件到本地的/tmp/dest.txt文件
salt ‘centos02‘ file.copy /data/test.txt /tmp/dest.txt
##檢查指定被控主機的/etc/目錄下是否存在文件,存在則返回True
salt ‘centos02‘ file.directory_exists /etc/
##獲取指定被控主機的/etc/passwd文件的stats信息
salt ‘centos02‘ file.stats /etc/passwd
##獲取指定被控主機/etc/passwd的權限mode,如700
salt ‘centos02‘ file.get_mode /etc/passwd
##修改指定被控主機的文件權限mode,如0644
salt ‘centos02‘ file.set_mode /etc/passwd 0644
##在指定被控主機創建/data/test目錄
salt ‘centos02‘ file.mkdir /data/test
##將指定被控主機的/data/test.txt文件裏的hello改為hhhh
salt ‘centos02‘ file.sed /data/test.txt ‘hello‘ ‘hhhh‘
##在指定被控主機的/data/test.txt文件內容追加test
salt ‘centos02‘ file.append /data/test.txt ‘test‘
##刪除指定被控主機的/data/test.txt文件
salt ‘centos02‘ file.remove /data/test.txt

api調用
client.cmd(‘*‘, ‘file.remove‘,[‘/data/test.txt‘])
4.7、network模塊,返回被控主機的網絡信息

##在指定被控主機獲取ping,traceroute目錄域名信息
salt ‘centos02‘ network.ping www.baidu.com
salt ‘centos02‘ network.traceroute www.baidu.com
##獲取指定被控主機的網卡的MAC地址
salt ‘centos02‘ network.hwaddr ens33
##獲取指定被控主機的IP地址配置信息
salt ‘centos02‘ network.ip_addrs
##獲取指定被控制主機的IP地址段
salt ‘centos02‘ network.subnets

api調用
client.cmd(‘centos02‘,‘network.ip_addrs‘)
4.8、pkg模塊,被控主機程序包管理,如yum、apt-get等

##為所有被控主機安裝ftp安裝包,根據不同操作系統安裝,如redhat就是相當於yum install -y ftp
salt ‘*‘ pkg.install ftp
##卸載所有被控主機的ftp安裝包
salt ‘*‘ pkg.remove ftp
##升級所有被控主機的軟件包
salt ‘*‘ pkg.upgrades

api調用
client.cmd(‘centos02‘, ‘pkg.remove‘,[‘ftp‘])

5、grains組件
grains是saltstack最重要的組件之一,它的作用就是收集被控制主機的基本信息,這些信息通常都是一些靜態的數據,如CPU,操作系統,虛擬化等。
5.1、grains常用的操作命令

##獲取所有os_family屬性為RedHat的被控主機的內存信息
salt -G ‘os_family:RedHat‘ cmd.run ‘free -m‘
##獲取所有被控主機的grains項信息
salt ‘*‘ grains.ls

5.2、定義grains的數據
定義grains數據有兩種方法,一種是在被控主機定制配置文件,另一種是通過主控端擴展模塊api實現,區別是模塊更加靈活。可以通過python編程動態定義,配置文件只適合相對固定的鍵與值。
一、在被控端定制grains數據
在被控端修改配置文件/etc/salt/minion,修改的內容是“default_include: minion.d/*.conf”‘然後在被控制端寫入配置文件:

[root@centos02 data]# cat /etc/salt/minion.d/hostinfo.conf 
grains:
  roles:
    - testhost
    - python02
  deployment: mytest
  cabinet: 13

為了讓配置生效,重啟被控端的salt-minion服務,systemctl restart salt-minion,然後主控端輸入命令查看定義的grains數據:

[root@centos01 ~]# salt ‘centos02‘ grains.item roles deployment cabinet
centos02:
    ----------
    cabinet:
        13
    deployment:
        mytest
    roles:
        - testhost
        - python02

二、主控端擴展模塊定制grains數據
首先在主控端編寫python代碼,包含了grains數據的代碼,然後將代碼同步到被控端,然後使用命令刷新生效就可以了。

##創建_grains目錄
install -d /srv/salt/_grains
##開始編寫代碼
[root@centos01 ~]# cat /srv/salt/_grains/grains_openfile.py 
import os,sys,commands
def grains_openfile():
    grains = {}   ##定義grains集合,變量名一定要用grains,方便saltstack識別。
    open_file = 65535  ##給變量一個初始值
    try:
         getulimit = commands.getstatusoutput(‘source /etc/profile;ulimit -n‘)
    except:
          pass
    if getulimit[0] == 0:
          open_file = int(getulimit[1])  ##將變量getulimit的第一個值ulimit -n給open_file
    grains[‘max_open_file‘] = open_file
    return grains
##由於grains是儲存鍵與相應的值的,所以grains是一個集合, grains[‘max_open_file‘] = open_file這句相當於給grains添加一對對象,鍵為max_open_file,值為open_file,而open_file是從ulimit -n獲取來的值。最後返回grains。
##將代碼同步到被控端
salt ‘centos02‘ saltutil.sync_all
##刷新
salt ‘centos02‘ sys.reload_modules  ##返回True
##測試結果
[root@centos01 ~]# salt ‘centos02‘ grains.item max_open_file
centos02:
    ----------
    max_open_file:
        1024

6、pillar組件
pillar是saltstack最重要的組件之一,其作用是定義與被控主機相關的任何數據,定義好的數據可以直接被其他組件使用,如被模板,state,api等使用。
6.1、主配置文件的定義
在主配置文件/etc/salt/master中通過pillar_opts:True來開啟該功能,配置後重啟服務生效能用“salt ‘centos02‘ pillar.data”來驗證。
6.2、sls文件的定義
pillar支持sls文件來定義數據,格式必須符合YAML規範

一、定義pillar的主目錄
##修改主配置文件/etc/salt/master的pillar_roots參數,
pillar_roots:
  base:
    - /srv/pillar
##同時創建pillar目錄
install -d /srv/pillar
二、定義入口文件top.sls
##入口文件一般是用來定義pillar覆蓋的主機範圍,‘*‘代表的是所有的主機
[root@centos01 ~]# cat /srv/pillar/top.sls 
base:
  ‘*‘:
    - data
##定義data.sls文件,寫入的是pillar的數據
[root@centos01 ~]# cat /srv/pillar/data.sls 
hostname: centos  
flow:
  maxconn: 65535
  maxmem: 1G
##其中hostname表示的是一級字典{‘hostname‘:‘centos‘},flow表示二級字典{‘flow‘:{‘maxconn‘:‘65535‘,‘maxmem‘:‘1G‘}}。
##測試
[root@centos01 ~]# salt ‘centos02‘ pillar.data hostname flow
centos02:
    ----------
    flow:
        ----------
        maxconn:
            65535
        maxmem:
            1G
    hostname:
        centos
##能看到data.sls的數據,因為入口文件top.sls使用的是‘*’,所有主機都能看到data數據。
三、pillar的使用
pillar定義好數據後,接下來就開始使用了,使用的格式是"{{ pillar[‘變量‘] }}"
{{ pillar [‘hostname‘] }} 一級字典
{{ pillar[‘flow‘][‘maxconn‘] }} 二級字典
api調用格式
pillar[‘flow‘][‘maxconn‘]
pillar.get(‘ flow:maxconn‘, { })
##通過 -I來匹配相應值的被控主機
[root@centos01 ~]# salt -I ‘hostname:centos‘ test.ping
centos02:
    True
centos03:
    True
##如果測試沒結果,重啟被控制主機的salt-minion:systemctl restart salt-minion
##結合grains處理數據差異性,通過grains的id來區分不同的maxcpu值,使用if...else...endif語句,該語句為jinja2的模板語法。
[root@centos01 pillar]# salt ‘centos02‘ pillar.data flow
centos02:
    ----------
    flow:
        ----------
        maxconn:
            65535
        maxcpu:
            4
        maxmem:
            1G
[root@centos01 pillar]# salt ‘centos03‘ pillar.data flow
centos03:
    ----------
    flow:
        ----------
        maxconn:
            65535
        maxcpu:
            1
        maxmem:
            1G
##註意的是上面定義的鍵,如maxconn不可以放到if語句裏面重新賦值,否則會出錯。

四、state的使用,state是saltstack的最核心功能,它通過預先定制好的sls(salt state file)文件對被控主機進行狀態管理,支持包括程序包、文件、網絡配置、系統服務、系統用戶等。

##state的定義是通過sls文件進行描述的,支持YAML語法,定義的規則如下
$ID:
  $state:
      - $state: states
##$ID是指state的名稱,通常采用與描述對象一樣的名稱,例如apache、nginx等;$state須管理對象的類型,如pkg(程序包)、file(文件)等;$state: states定制對象的狀態。
apache:              ##state的名稱
  pkg:                  ##表示state聲明開始,使用pkg狀態對象。pkg使用管理本地軟件包管理器yum或者apt管理將要安裝的軟件。
      - installed       ##要執行的方法,表示要求該軟件包應該處於已安裝的狀態。
    service:            ##同pkg,service是系統管理守護進程
      - running        ##同installed,表示要求改程序處於運行的狀態
      - require:        ##確保Apache服務只有處於已安裝的狀態下才能啟動。在運行此state之前,先運行依賴的state關系檢查。
      - pkg: apache
    上述代碼檢查Apache軟件包是否安裝,如果未安裝,通過yum或者apt安裝

##state的使用,入口文件為top.sls與pillar的一樣,但是state要求sls文件必須放在saltstack的base定義目錄下,/srv/salt,state描述的sls配置文件支持jinjia模板、grains以及pillar的調用。在state的定義完成後,使用 salt ‘*‘ state.highstate執行生效
##定義pillar
[root@centos01 ~]# cat /srv/pillar/top.sls 
base:
  ‘*‘:    ##定義該對象的覆蓋被控主機,這裏是任意主機
    - apache  ##定義對象的名稱
##在pillar配置目錄下創建Apache目錄
[root@centos01 ~]# mkdir /srv/pillar/apache
##編寫Apache的配置文件
[root@centos01 ~]# cat /srv/pillar/apache/init.sls 
pkgs:
{% if grains[‘os_family‘] == ‘Debian‘ %}   ##通過if語句調用grains判斷系統並返回相應的程序包名稱。
  apache: apache2
  {% elif grains[‘os_family‘] == ‘RedHat‘ %}
  apache: httpd
{% endif %}
##測試pillar配置的結果
[root@centos01 ~]# salt ‘*‘ pillar.data pkgs
centos02:
    ----------
    pkgs:
        ----------
        apache:
            httpd
centos03:
    ----------
    pkgs:
        ----------
        apache:
            httpd
##定義state,入口文件top.sls的格式和pillar的一樣
[root@centos01 ~]# cat /srv/salt/top.sls 
base:
  ‘*‘:
    - apache
[root@centos01 ~]# cat /srv/salt/apache/init.sls 
apache:
  pkg:
    - installed
    - name: {{ pillar[‘pkgs‘][‘apache‘] }}
  service.running:
    - name: {{ pillar[‘pkgs‘][‘apache‘] }}
    - require:
      - pkg: {{ pillar[‘pkgs‘][‘apache‘] }}
##在saltstack的定義目錄下創建state對象名稱為apache,pkg是指管理對象的類型是程序包。name使用的是pillar中定義的軟件包名稱。service.running檢查軟件是否處於運行的狀態,沒有運行就運行,require要求軟件必須處於已安裝狀態否則就會使用yum安裝軟件。
##測試結果
[root@centos01 ~]# salt ‘*‘ state.highstate
centos02:
----------
          ID: apache
    Function: pkg.installed
        Name: httpd
      Result: True
     Comment: Package httpd is already installed.
     Started: 15:56:57.900991
    Duration: 1095.767 ms
     Changes:   
----------
          ID: apache
    Function: service.running
        Name: httpd
      Result: True
     Comment: The service httpd is already running
     Started: 15:56:58.997731
    Duration: 150.081 ms
     Changes:   

Summary
------------
Succeeded: 2
Failed:    0
------------
Total states run:     2
centos03:
----------
          ID: apache
    Function: pkg.installed
        Name: httpd
      Result: True
     Comment: The following packages were installed/updated: httpd
     Started: 15:56:57.400161
    Duration: 35643.566 ms
     Changes:   
              ----------
              httpd:
                  ----------
                  new:
                      2.4.6-67.el7.centos.6
                  old:
              httpd-tools:
                  ----------
                  new:
                      2.4.6-67.el7.centos.6
                  old:
              mailcap:
                  ----------
                  new:
                      2.1.41-2.el7
                  old:
----------
          ID: apache
    Function: service.running
        Name: httpd
      Result: True
     Comment: Started Service httpd
     Started: 15:57:33.655895
    Duration: 1681.019 ms
     Changes:   
              ----------
              httpd:
                  True

Summary
------------
Succeeded: 2 (changed=2)
Failed:    0
------------
Total states run:     2
##能看到state執行後兩臺被控制主機安裝服務並啟動

saltstack常用模塊及組件備忘