SaltStack Runners模块CLI命令及RunnerClientAPI接口使用指南


SaltStack Runners模块的主要用途是执行一些只有在Salt Master上运行时才能有最好效果的工作任务或管理任务,它纯粹是一个在Salt Master侧才能运行的执行序列。,比如像处理一些网络自动发现、事件管理、本地文件服务器管理、从本地发起的HTTP访问、jobs管理、本地pillar数据的动态管理等等。

Salt runners模块 & salt-run命令 & RunnerClient API 三者的关系

  • Salt runners是用于在Salt master上执行便捷管理功能的一个简单的Salt功能模块。
  • salt-run是执行Salt Runners的前端命令。
  • RunnerClient API,是Salt Master上运行salt-run CLI工具时调用的salt底层接口

在Salt Master上运行的runner程序模块,都是通过调用底层的RunnerClient API完成的。
导入和使用RunnerClient有一个硬性的前提条件,即必须在与Salt Master相同的机器上完成,并且必须使用与运行Salt Master相同的用户执行。

SALT RUNNER 模块

下面是目前可用的SALT RUNNER MODULES的清单。
对于有复杂使用场景的企业,这些随Salt模块库分发的标准模块或模块功能并不能完全覆盖到大家的使用需求。所以已经有一个专门解决这类问题的开源Salt项目,为开发自定义模块或模块功能提供指导与支持,https://github.com/saltstack/salt-contrib
在这里插入图片描述
这里是一个完整Salt Runner Modules列表信息的链接:
https://docs.saltstack.com/en/latest/ref/runners/all/

命令行工具salt-run的使用

salt-run CLI命令的语法比较简单,使用的参数也不复杂,如下所示。
主要参数可以划分为这样的几部分:

  • 行为配置类参数
  • 认证类参数
  • 日志类参数
  • 输出信息类配置参数

大部分参数只有在遇到一些特别的功能定制需求时才有使用价值,总体来说这个salt-run命令的使用方法很简单。

$ salt-run -h
Usage: salt-run [options] <function> [arguments]
salt-run is the frontend command for executing Salt Runners. Salt Runners are
modules used to execute convenience functions on the Salt Master

Options:
  --version             show program's version number and exit
  -V, --versions-report
                        Show program's dependencies version number and exit.
  -h, --help            show this help message and exit
  --saltfile=SALTFILE   Specify the path to a Saltfile. If not passed, one
                        will be searched for in the current working directory.
  -c CONFIG_DIR, --config-dir=CONFIG_DIR
                        Pass in an alternative configuration directory.
                        Default: '/etc/salt'.
  -t TIMEOUT, --timeout=TIMEOUT
                        Change the timeout, if applicable, for the running
                        command (in seconds). Default: 1.
  --args-stdin          Read additional options and/or arguments from stdin.
                        Each entry is newline separated.
  --hard-crash          Raise any original exception rather than exiting
                        gracefully. Default: False.
  --no-parse=argname1,argname2,...
                        Comma-separated list of named CLI arguments (i.e.
                        argname=value) which should not be parsed as Python
                        data types
  -d, --doc, --documentation
                        Display documentation for runners, pass a runner or
                        runner.function to see documentation on only that
                        runner or function.
  --async               Start the runner operation and immediately return
                        control.

  Logging Options:
    Logging options which override any settings defined on the
    configuration files.

    -l LOG_LEVEL, --log-level=LOG_LEVEL
                        Console logging log level. One of 'all', 'garbage',
                        'trace', 'debug', 'profile', 'info', 'warning',
                        'error', 'critical', 'quiet'. Default: 'warning'.
    --log-file=LOG_FILE
                        Log file path. Default: '/var/log/salt/master'.
    --log-file-level=LOG_LEVEL_LOGFILE
                        Logfile logging log level. One of 'all', 'garbage',
                        'trace', 'debug', 'profile', 'info', 'warning',
                        'error', 'critical', 'quiet'. Default: 'warning'.

  External Authentication:
    -a EAUTH, --auth=EAUTH, --eauth=EAUTH, --external-auth=EAUTH
                        Specify an external authentication system to use.
    -T, --make-token    Generate and save an authentication token for re-use.
                        The token is generated and made available for the
                        period defined in the Salt Master.
    --username=USERNAME
                        Username for external authentication.
    --password=PASSWORD
                        Password for external authentication.

  Output Options:
    Configure your preferred output format.

    --out=OUTPUT, --output=OUTPUT
                        Print the output from the 'salt-run' command using the
                        specified outputter.
    --out-indent=OUTPUT_INDENT, --output-indent=OUTPUT_INDENT
                        Print the output indented by the provided value in
                        spaces. Negative values disables indentation. Only
                        applicable in outputters that support indentation.
    --out-file=OUTPUT_FILE, --output-file=OUTPUT_FILE
                        Write the output to the specified file.
    --out-file-append, --output-file-append
                        Append the output to the specified file.
    --no-color, --no-colour
                        Disable all colored output.
    --force-color, --force-colour
                        Force colored output.
    --state-output=STATE_OUTPUT, --state_output=STATE_OUTPUT
                        Override the configured state_output value for minion
                        output. One of 'full', 'terse', 'mixed', 'changes' or
                        'filter'. Default: 'none'.
    --state-verbose=STATE_VERBOSE, --state_verbose=STATE_VERBOSE
                        Override the configured state_verbose value for minion
                        output. Set to True or False. Default: none.

  Output Options:
    Configure your preferred output format.

    --quiet             Do not display the results of the run.

  Profiling support:
    --profiling-path=PROFILING_PATH
                        Folder that will hold all stats generations path.
                        Default: '/tmp/stats'.
    --enable-profiling  Enable generating profiling stats. See also:
                        --profiling-path.

举几个例子

使用salt-run调用http模块

在Salt Master上执行一个HTTP访问请求,获取一个web页面的数据

# salt-run http.query http://192.168.81.7:8080/
body:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    ......
    </body>
    </html>
  • 页面作为一个json数据返回,key为body,注意不要和html页面中的body标签混淆。

现在很多服务间调用都是通过接口完成的,可以像下面这样调用接口地址并附带上需要的参数:

salt-run http.query http://somelink.com/ method=POST params='key1=val1&key2=val2'

使用salt-run调用salt.cmd模块执行几个系统管理方面的命令

# salt-run salt.cmd test.ping
True
# salt-run salt.cmd cmd.run "hostname"
sleeper-VirtualBox
  • 以上系统命令的执行目标仅有Salt Master节点

在Salt Master上执行一个HTTP访问请求,获取指定URL返回响应的HTTP状态码

# salt-run salt.cmd cmd.run "curl -I -m 10 -o /dev/null -s -w %{http_code} http://192.168.81.7:8080/"
200

使用salt-run调用jobs模块完成各种jobs管理任务

查看当前正在运行中的jobs:

# salt-run jobs.active
20180918103622717011:
    ----------
    Arguments:
    Function:
        saltutil.running
    Returned:
......

执行一条管理命令用于演示jobs管理方法:

[root@jumpjump ~]# salt testserver test.ping
testserver:
    True

按执行的功能函数查询最后执行的一次job的信息:

# salt-run jobs.last_run function='test.ping'
20180918104254437160:
    ----------
    Arguments:
    Function:
        test.ping
    Minions:
        -testserver
    Result:
        ----------
       testserver:
            ----------
            return:
                True
    StartTime:
        2018, Sep 18 10:42:54.437160
    Target:
       testserver
    Target-type:
        glob
    User:
        root

或者可以按执行的功能函数查询jobs列表信息:

# salt-run jobs.list_jobs search_function='test.ping'
20180918104254437160:
    ----------
    Arguments:
    Function:
        test.ping
    StartTime:
        2018, Sep 18 10:42:54.437160
    Target:
       testserver
    Target-type:
        glob
    User:
        root

或者只查询指定目标target主机上指定功能函数的jobs列表信息:

# salt-run  jobs.list_jobs  search_target='["testserver"]'  search_function='test.ping'
20180918104254437160:
    ----------
    Arguments:
    Function:
        test.ping
    StartTime:
        2018, Sep 18 10:42:54.437160
    Target:
       testserver
    Target-type:
        glob
    User:
        root

如果需要指定一个查询的时间段,需要确认安装了python-dateutil依赖包:

pip install python-dateutil
# salt-run jobs.list_jobs search_target=testserver start_time='2018, Sep 18 10:00' end_time='2018, Sep 18 13:00'
20180918104254437160:
    ----------
    Arguments:
    Function:
        test.ping
    StartTime:
        2018, Sep 18 10:42:54.437160
    Target:
       testserver
    Target-type:
        glob
    User:
        root

当然了,上面的命令很简单,迅速就执行完毕了,但会有一些场景下的管理命令是不会这么快返回结果的,此时可以使用下面方法查询指定job是否已经执行完毕并成功得退出了:

# salt-run jobs.exit_success 20180918104254437160
testserver:
    True

如果还需要获取下job的返回数据:

# salt-run jobs.lookup_jid 20180918104254437160
testserver:
    True

查看指定job的完整任务信息:

# salt-run jobs.print_job 20180918104254437160
20180918104254437160:
    ----------
    Arguments:
    Function:
        test.ping
    Minions:
        -testserver
    Result:
        ----------
       testserver:
            ----------
            return:
                True
    StartTime:
        2018, Sep 18 10:42:54.437160
    Target:
       testserver
    Target-type:
        glob
    User:
        root

如有不明之处,请参见官网资料:
https://docs.saltstack.com/en/latest/ref/runners/all/salt.runners.jobs.html#module-salt.runners.jobs

RunnerClient API的使用方法

class salt.runner.RunnerClient(opts),Salt Master上salt-run CLI工具使用的底层接口。
它在Salt Master上执行支持的runner程序模块。
导入和使用RunnerClient必须在与Salt Master相同的机器上完成,并且必须使用与运行Salt Master相同的用户执行。
Salt的external_auth功能可用于对调用请求进行验证。 eauth用户必须被授权可执行runner模块(@runner)。
external_auth是Salt auth模块所提供的,需要在Salt Master配置文件中配置需要的使用授权。可参照下面的配置内容和链接。

external_auth:
  pam:
    fred:
      - test.*

RunnerClient API提供了三个函数方法

  • cmd(fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False),执行一个runner函数
  • cmd_async(low),异步执行一个runner函数
  • cmd_sync(low, timeout=None, full_return=False),同步方式执行一个runner函数

cmd_async(), cmd_sync()都需要有external_auth的授权支持,且在调用时需要参照下面方法提供认证信息。
** 执行异步函数前的认证:**

runner.eauth_async({
    'fun': 'jobs.list_jobs',
    'username': 'saltdev',
    'password': 'saltdev',
    'eauth': 'pam',})

执行同步函数前的认证:

runner.eauth_sync({
    'fun': 'jobs.list_jobs',
    'username': 'saltdev',
    'password': 'saltdev',
    'eauth': 'pam',})

RunnerClient API使用举例

# python
Python 2.7.5 (default, Aug  4 2017, 00:39:18)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import salt.config
>>> import salt.runner
>>> opts = salt.config.master_config('/etc/salt/master')
>>> runner = salt.runner.RunnerClient(opts)
>>> runner.cmd('salt.cmd', ['test.ping'])
True
True
>>> runner.cmd('salt.cmd', ['cmd.run', 'hostname'])
sleeper-VirtualBox
u'sleeper-VirtualBox'
>>> runner.cmd('salt.cmd', ['cmd.run', 'curl -I -m 10 -o /dev/null -s -w %{http_code} http://192.168.81.7:8080/'])
200
u'200'
>>>

我们可以看到上面几个接口方法调用的输出都是重复的两份,这个只需要带上print_event=False参数就可以减掉一个了:

>>> runner.cmd('salt.cmd', ['test.ping'], print_event=False)
True
>>>

通过API查询一个job的执行结果

>>> runner.cmd('jobs.lookup_jid',['20180918104254437160'])
testserver:
    True
{'testserver': True}
>>>

通过API查询指定目标节点上近期执行过的jobs列表

>>> runner.cmd('jobs.list_jobs', ['search_target=testserver'])
20180918104254437160:
    ----------
    Arguments:
    Function:
        test.ping
    StartTime:
        2018, Sep 18 10:42:54.437160
    Target:
       testserver
    Target-type:
        glob
    User:
        root

通过API查询指定节点上在指定时间段内执行过的jobs信息

>>> runner.cmd('jobs.list_jobs', ['search_target=testserver', "start_time='2018, Sep 18 10:00'", "end_time='2018, Sep 18 13:00'"])
20180918104254437160:
    ----------
    Arguments:
    Function:
        test.ping
    StartTime:
        2018, Sep 18 10:42:54.437160
    Target:
       testserver
    Target-type:
        glob
    User:
        root

更加详细的SALT.RUNNERS.JOBS使用方法请参见:
https://docs.saltstack.com/en/latest/ref/runners/all/salt.runners.jobs.html#module-salt.runners.jobs

猜你喜欢

转载自blog.csdn.net/watermelonbig/article/details/82757725
今日推荐