一、内置模块与自定义模块
saltstack内置了很多模块,这些模块使我们简单的执行一条命令就可以返回我们所需的结果。具体可以查看---<a href="http://docs.saltstack.com/en/latest/ref/modules/all/index.html#all-salt-modules" target="_blank" rel="noopener"> SaltStack内置模块列表</a> 。不过也有很多时候,这些内置模块不能满足我们的正常需要,或者返回的结果不理想,这就需要通过自定义模块实现我们想要的结果。自定义SaltStack模块是需要存放在由/etc/salt/master配置文件中file_roots指定的路径下的_modules目录下。(需要创建),默认位置为/srv/salt/_modules。
二、编写自定义模块
1、创建自定义模块存放目录
Master上创建存放模块的目录:
<br />
mkdir -pv /srv/salt/_modules
cd /srv/salt/_modules
2、编写自定义模块
这里我想要让返回的格式是txt格式,我在这里模块里定义了两个函数:
<br />
# cat ndisk.py
#coding:utf-8
import commands,random
__outputter__ = {
'test': 'txt',
'usage': 'txt'
}
def test():
return random.randint(1,100)%2==0
def usage(per=35):
ret = []
(status, output) = commands.getstatusoutput('df -P')
out = output.splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
if len(comps) >= 2:
perct = (comps[-2]).replace('%', '')
if int(perct) > per:
data = (comps[-1],perct)
ret.append(data)
return ret
3、同步文件到minion端
同步自定义模块到客户端的方法有三种,这里一般以第二种属于较正统的同步模块方法,第1,3方法同步的时候也会同步其他信息到客户端:
<br />
state.highstate
saltutil.sync_modules
saltutil.sync_all
同步完成后,默认会将自定义模块同步到/var/cache/salt/minion/extmods/modules目录下:
<img src="https://www.361way.com/wp-content/uploads/2014/04/sync-modules.png" alt="" width="595" height="72" />
4、自定义模块的调用
同步完成后,自定义模块的调用结果如下:
<img src="https://www.361way.com/wp-content/uploads/2014/04/salt-ext-module.png" title="salt-ext-module" alt="salt-ext-module" width="796" height="169" />
这里返回的格式会发现有双方括号,返回的并不美观,一般建议返回字典值,我们还可以修改上面的函数为如下:
<br />
def usage(per=35):
ret = {}
(status, output) = commands.getstatusoutput('df -P')
out = output.splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
#print comps
if len(comps) >= 2:
#print line
perct = (comps[-2]).replace('%', '')
#print perct
if int(perct) > per:
key = comps[-1]
ret[key] = perct
return ret
<br />
其执行后,结果如下:
<img src="https://www.361way.com/wp-content/uploads/2014/04/saltutil-ext-mod.png" alt="" width="792" height="88" />
这个结果是不是美观多了?
写模块时,也可以参考salt内置模块,其默认通过rpm安装的位置为:/usr/lib/python2.7/site-packages/salt/modules 。
注:<span style="color:#E53333;">默认salt也带有一个disk模块,不过其执行时的输出结果不满足我们进行巡检的需求,可以通过编写一大批自定义的模块,满足平时巡检的需求</span>。
三、自定义模块中的特殊调用
自定义模块中也可以调用salt内部的一些变量或其他模块,同时还可以给模块指定一个虚拟名称。示例如下:
<br />
[root@ZJHZ-CMREAD-TEST93 _modules]# cat test.py
#!/usr/bin/python
#coding:utf-8
import time
__virtualname__ = 'hoho'
def __virtual__():
return __virtualname__
def date():
return time.time()
def get_osfinger():
return __grains__['osfinger']
def get_cachedir():
return __pillar__['productname']
def foo():
return __salt__['cmd.run']('df')
执行结果如下:
<img src="https://www.361way.com/wp-content/uploads/2014/04/salt-virtual.png" title="salt-virtual" alt="salt-virtual" width="785" height="283" />
<br />