saltstack中的salt-api接口

文章目录

  • salt-api接口简介
  • API
    • salt-api的配置及其应用
  • Python OMT
    • 需求一:打印该master节点下的所有获得key的minion实现
    • 需求二:开启server3的httpd服务

学习指南: https://docs.saltstack.com/en/latest/ref/netapi/all/salt.netapi.rest_cherrypy.html

salt-api接口简介

salt-api时saltstack官方提供的一个REST API格式的项目,使salt与第三方系统集成变的尤为简单,可以通过配置salt-api,使用salt-api获取想要的信息。

API

salt-api的配置及其应用

(1)开启salt服务

[root@server1 ~]# systemctl start salt-master
[root@server2 ~]# systemctl start salt-minion
[root@server3 ~]# systemctl start salt-minion

(2)下载salt-api

[root@server1 ~]# yum install -y salt-api

saltstack中的salt-api接口_第1张图片(3)为调用cherrypy模块做准备,在/etc/pki/tls/certs目录下生成证书,因为在这个目录下面有makefile文件,该文件里面有生成证书的相应方式

[root@server1 ~]# cd /etc/pki/tls/private/
[root@server1 private]# ls
[root@server1 private]# openssl genrsa 2048 > localhost.key   ##生成密钥
Generating RSA private key, 2048 bit long modulus
........................+++
....................+++
e is 65537 (0x10001)
[root@server1 private]# ls
localhost.key
[root@server1 private]# file localhost.key
localhost.key: PEM RSA private key

saltstack中的salt-api接口_第2张图片(4)使用钥匙生成自签名证书

[root@server1 certs]# pwd
/etc/pki/tls/certs
[root@server1 certs]# make testcert

saltstack中的salt-api接口_第3张图片
(5)在server1上/etc/salt下查看master文件里面有相应的api模块文件的目录及其文件命名格式,api模版文件要在master.d目录下且以.conf结尾
saltstack中的salt-api接口_第4张图片(6)调用cherrypy模块
按照官网的格式,在/etc/salt/master.d目录下编辑api的配置文件添加证书及其钥匙
saltstack中的salt-api接口_第5张图片

[root@server1 certs]# cd /etc/salt/master.d/
[root@server1 master.d]# pwd
/etc/salt/master.d
[root@server1 master.d]# vim api.conf

rest_cherrypy:
  port: 8000
  ssl_crt: /etc/pki/tls/certs/localhost.crt
  ssl_key: /etc/pki/tls/private/localhost.key

saltstack中的salt-api接口_第6张图片(4)同样,在/etc/salt/master.d目录下新建扩展认证文件,按照官网的格式写

[root@server1 master.d]# pwd
/etc/salt/master.d
[root@server1 master.d]# ls
api.conf
[root@server1 master.d]# vim auth.conf

external_auth:
  pam:
    devops:   ##用户名
      - '*'   
      - '@wheel'    ##允许所有的wheel块
      - '@runner' 
      - '@jobs'

[root@server1 master.d]# ls
api.conf  auth.conf

(5)建立认证用户devops,并修改其密码为devops

[root@server1 master.d]# useradd devops
[root@server1 master.d]# echo devops | passwd devops --stdin
Changing password for user devops.
passwd: all authentication tokens updated successfully.

启动服务
[root@server1 ~]# systemctl restart salt-master
[root@server1 ~]# systemctl start salt-api

在这里插入图片描述
(6)登陆,获取token

[root@server1 ~]# curl -sSk https://localhost:8000/login \
> -H 'Accept: application/x-yaml' \
> -d username=devops -d password=devops -d eauth=pam

saltstack中的salt-api接口_第7张图片(7)利用刚才的token,执行test.ping命令,检测所有的minion端

[root@server1 ~]# curl -sSk https://localhost:8000 \
> -H 'Accept: application/x-yaml' \
> -H 'X-Auth-Token:29e79ef45bd2d8d91bd9f56fa513ee63a1f9d12a ' \
> -d client=local \
> -d tgt='*' \
> -d fun=test.ping

saltstack中的salt-api接口_第8张图片

Python OMT

需求一:打印该master节点下的所有获得key的minion实现

需求步骤:

(1)编写一个实现需求的python脚本模板

[root@server1 ~]# vim saltapi 

# -*- coding: utf-8 -*-

import urllib2,urllib
import time

try:
    import json
except ImportError:
    import simplejson as json

class SaltAPI(object):
    __token_id = ''
    def __init__(self,url,username,password):
        self.__url = url.rstrip('/')
        self.__user = username
        self.__password = password

    def token_id(self):
        ''' user login and get token id '''
        params = {'eauth': 'pam', 'username': self.__user, 'password': self.__password}
        encode = urllib.urlencode(params)
        obj = urllib.unquote(encode)
        content = self.postRequest(obj,prefix='/login')
	try:
            self.__token_id = content['return'][0]['token']
        except KeyError:
            raise KeyError

    def postRequest(self,obj,prefix='/'):
        url = self.__url + prefix
        headers = {'X-Auth-Token'   : self.__token_id}
        req = urllib2.Request(url, obj, headers)
        opener = urllib2.urlopen(req)
        content = json.loads(opener.read())
        return content

    def list_all_key(self):
        params = {'client': 'wheel', 'fun': 'key.list_all'}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        minions = content['return'][0]['data']['return']['minions']
        minions_pre = content['return'][0]['data']['return']['minions_pre']
        return minions,minions_pre

    def delete_key(self,node_name):
        params = {'client': 'wheel', 'fun': 'key.delete', 'match': node_name}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        ret = content['return'][0]['data']['success']
        return ret

    def accept_key(self,node_name):
        params = {'client': 'wheel', 'fun': 'key.accept', 'match': node_name}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        ret = content['return'][0]['data']['success']
        return ret

    def remote_noarg_execution(self,tgt,fun):
        ''' Execute commands without parameters '''
        params = {'client': 'local', 'tgt': tgt, 'fun': fun}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        ret = content['return'][0][tgt]
        return ret

    def remote_execution(self,tgt,fun,arg):
        ''' Command execution with parameters '''        
        params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        ret = content['return'][0][tgt]
        return ret

    def target_remote_execution(self,tgt,fun,arg):
        ''' Use targeting for remote execution '''
        params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg, 'expr_form': 'nodegroup'}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        jid = content['return'][0]['jid']
        return jid

    def deploy(self,tgt,arg):
        ''' Module deployment '''
        params = {'client': 'local', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        return content

    def async_deploy(self,tgt,arg):
        ''' Asynchronously send a command to connected minions '''
        params = {'client': 'local_async', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        jid = content['return'][0]['jid']
        return jid

    def target_deploy(self,tgt,arg):
        ''' Based on the node group forms deployment '''
        params = {'client': 'local_async', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg, 'expr_form': 'nodegroup'}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        jid = content['return'][0]['jid']
        return jid

def main():
    sapi = SaltAPI(url=,username=,password=)
    #sapi.token_id()
    #print sapi.list_all_key()
    #sapi.delete_key('test-01')
    #sapi.accept_key('test-01')
    #sapi.deploy('test-01','nginx')
    #print sapi.remote_noarg_execution('test-01','grains.items')

if __name__ == '__main__':
    main()

(2)根据需求,修改模板中的def_main( ):
saltstack中的salt-api接口_第9张图片(3)执行脚本,实现需求,打印出salt-minion端的主机名

[root@server1 ~]# python saltapi
([u'server2', u'server3'], [])

需求二:开启server3的httpd服务

实现需求步骤:

(1)修改sapi.deploy

注意:必须确保在base目录下(/srv/salt)有相应的sls安装及其启动服务install.sls或service.sls的文件
saltstack中的salt-api接口_第10张图片(2)执行脚本前先查看server3httpd服务是否是开启的
saltstack中的salt-api接口_第11张图片(3)执行脚本,实现需求

[root@server1 ~]# python saltapi

开启server3httpd服务
在这里插入图片描述saltstack中的salt-api接口_第12张图片

你可能感兴趣的:(自动化运维saltstack)