Salt-api有两种方式:
- 第一种是函数的形式,有人家定义好的函数,我们可以直接调用,直接写python代码调用函数或者类就可以了
- 第二种形式是salt-api有封装好的http协议的,我们需要启动一个服务端
安装:yum install –y salt-api
1、函数形式的api
①、加载master的配置文件
>>> import salt.config
>>> master_opts = salt.config.client_config('/etc/salt/master')
>>> print(‘master_opts’)
②、加载minion的配置文件
>>> import salt.config
>>> Minion_opts = salt.config.minion_config('/etc/salt/minion')
③、在master上执行各种模块
>>> import salt.client
>>> local = salt.client.LocalClient('/etc/salt/master')#不加也可以,加上最好
>>> local.cmd('*', "test.ping")
{'192.168.48.129': True}
>>> local.cmd('*', "cmd.run", "w")
{'192.168.48.129': ' 12:17:38 up 5:58, 1 user, load average: 0.00, 0.01, 0.05 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT root pts/0 192.168.48.1 11:14 2:50 0.89s 0.89s python'}>>> local.cmd('*',"cmd.run",['ifconfig'])
{'slave01': 'eth1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.137.10 netmask 255.255.255.0 broadcast 192.168.137.255 ether 42:e0:82:d4:16:9d txqueuelen 1000 (Ethernet) RX packets 20000 bytes 20483244 (19.5 MiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 13856 bytes 1104104 (1.0 MiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 loop txqueuelen 0 (Local Loopback) RX packets 0 bytes 0 (0.0 B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0.0 B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0'
如果一次要执行多个模块
>>> local.cmd('*', ['test.ping', 'cmd.run'], [[], ['whoami']])
{'192.168.48.129': {'test.ping': True, 'cmd.run': 'root'}}
自定义的模块
>>> local.cmd('*', "jd.meminfo", "")
{'192.168.48.129': {'meminfo': '0.31'}}
④、如果对于执行时间过长,没法直接返回的,我们就可以通过异步执行的形式进行返回
放到后台执行:cmd_async
>>> local.cmd_async('*',['test.ping','cmd.run'],[[],['whoami']])
>>> '20180706215438744640'
获取执行完的结果:get_cache_returns(jid)
>>> local.get_cache_returns(20180706215438744640)
>>> {'slave01': {'ret': {'cmd.run': 'root', 'test.ping': True}}}取的只有一个结果
以下代码只能只能在master上执行,而且是只能在master上才可以使用
__opts__ = salt.config.minion_config('/etc/salt/minion')
conf_file = __opts__['conf_file']
client = salt.client.LocalClient(conf_file)
jid = client.cmd_async(minion, function, params)
wait_time = 0
sleep_interval = 1
while wait_time < timeout:
print('wait {0} seconds'.format(sleep_interval))
time.sleep(sleep_interval)
returns = client.get_cache_returns(jid)
if returns:
return returns
wait_time += sleep_interval
⑤、客户端执行salt命令
>>> import salt.config
>>> import salt.client
>>> caller = salt.client.Caller(‘/etc/salt/minion’)
>>> caller.cmd("test.ping")
True
类似shell命令的salt-call,可以在minion端执行salt的命令,测试连通性什么的
⑥、Master端执行salt-run
>>> import salt.config
>>> import salt.runner
>>> __opts__ = salt.config.client_config('/etc/salt/master')
>>> runerMaster = salt.runner.RunnerClient(__opts__)
>>> runerMaster.cmd('jobs.list_jobs', [])
查看所有的:
>>> runerMaster.cmd('manage.status')
down:
up:
- 192.168.48.129
{'down': [], 'up': ['192.168.48.129']}
⑦、Grains
>>> import salt.config
>>> import salt.loader
>>> __opts__ = salt.config.minion_config("/etc/salt/minion")
>>> __grains__ = salt.loader.grains(__opts__)
>>> __grains__['id']
'192.168.48.129‘
⑧、其他的一些变量
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
__grains__ = salt.loader.grains(__opts__)
__opts__['grains'] = __grains__
__utils__ = salt.loader.utils(__opts__)
__salt__ = salt.loader.minion_mods(__opts__, utils=__utils__)
__salt__['test.ping']()
⑨、Salt的内置环境变量
在python的交互环境中,这些变量是不生效的,只有在自定义的模块,活着salt执行时才生效
__opts__ #配置文件,类型
__salt__ #执行modules
- __salt__['cmd.run']('fdisk -l')
- __salt__['network.ip_addrs']()
__pillar__ #pillar
__grains__ #grains
__context__
if not 'cp.fileclient' in __context__:
__context__['cp.fileclient'] = salt.fileclient.get_file_client(__opts__)
2、Saltstack的httpapi
安装
①、在官网更新yum源信息
②、yum安装
yum install -y gcc make python-devel libffi-devel salt-api openssl
pip install cherrypy
生成证书:
# cd /etc/salt
# mkdir keycrt
# cd keycrt
# openssl genrsa -out key.pem 4096
# openssl req -new -x509 -key key.pem -out cert.pem -days 1826
③、配置用户以及权限:
a)、首先需要在master上检查配置文件:
default_include: master.d/*.conf
interface: 192.168.137.130
conf_file: /etc/salt/master
pki_dir: /etc/salt/pki/master
auto_accept: True
file_roots:
base:
- /srv/salt/
log_file:/var/log/salt/master
log_level_logfile: debug
b)、配置salt-api的配置文件:
[root@localhost master.d]# cd /etc/salt/master.d/
[root@localhost master.d]# ls
api.conf eauth.conf
[root@localhost master.d]# cat api.conf
rest_cherrypy:
port: 8000
ssl_crt: /etc/salt/keycrt/cert.pem
ssl_key: /etc/salt/keycrt/key.pem[root@localhost master.d]# cat eauth.conf
external_auth:
pam:
saltapi:
- .*
- '@wheel'
- '@runner'
c)、创建用户
useradd -M -s /sbin/nologin/ saltapi
echo “saltapi” |passwd saltapi --stdin
注意这个应用名和上面的saltapi要对应一致
启动salt-api
systemctl restart salt-api
netstat –anp | grep 8000
对于ubuntu系统,我们可能使用https也是没法使用,我们可以使用http协议,具体的配置如下:
root@ling-virtual-machine:/etc/salt/master.d# cat api.conf
rest_cherrypy:
port: 8000
disable_ssl: True
#ssl_crt: /etc/salt/keycrt/cert.pem
#ssl_key: /etc/salt/keycrt/key.pem
注意以上的: disable_ssl: True
然后把ssl秘钥和公钥注释掉,eauth.conf 不发生变化
获取token:http协议
[root@localhost master.d]# curl -X POST -k http://192.168.137.130:8000/login -d username='saltapi' -d password='saltapi' -d eauth='pam' |python -mjson.tool
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 240 100 197 100 43 45 9 0:00:04 0:00:04 --:--:-- 45
{
"return": [
{
"eauth": "pam",
"expire": 1517235285.554001,
"perms": [
".*",
"@wheel",
"@runner"
],
"start": 1517192085.554001,
"token": "105ee1f28109d67855ce7898e75e173a678f5174",
"user": "saltapi"
}
]
}
获取token:https协议(centos7)
[root@localhost master.d]# curl -X POST -k https://192.168.137.130:8000/login -d username='saltapi' -d password='saltapi' -d eauth='pam' |python -mjson.tool
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 240 100 197 100 43 908 198 --:--:-- --:--:-- --:--:-- 912
{
"return": [
{
"eauth": "pam",
"expire": 1517235312.537542,
"perms": [
".*",
"@wheel",
"@runner"
],
"start": 1517192112.537541,
"token": "bd5922438e9ae10db039816728c2b86f9462a0bb",
"user": "saltapi"
}
]
}
通过postman来获取token
Headers里面是用来存放headers的信息的
Body里面来存放数据的,常用的data数据就是x-www-form-urlencoded
form-data 是用来存放页面form表单数据的
只要salt-api不重启,token就不会过期,salt-api重启以后,token就会过期
通过postman来获取执行module:
Headers部分要填写的:
body部分要填写的:
body部分加参数:
body部分加多个参数:
通过curl来获取执行module:
root@ling-virtual-machine:/etc/salt/master.d# curl -k http://192.168.48.134:8000 -H "Accept: application/x-yaml" -H "X-Auth-Token: ec623ed62de7dd62cfdadb94ad0044b7f46c9549" -d
client='local' -d tgt='*' -d fun='test.ping'
return:
192.168.48.129: true
运行runner
root@ling-virtual-machine:/etc/salt/master.d# curl -k http://192.168.48.134:8000 -H "Accept: application/x-yaml" -H "X-Auth-Token: ec623ed62de7dd62cfdadb94ad0044b7f46c9549" -d
client='runner' -d fun='manage.status'
return:
- down: []
up:
- 192.168.48.129
任务
1.自定义一些module
2. 线上使用runner的实例
3. 通过python脚本取访问salt的httpapi