SaltStack介绍-日常管理(五)

2020年7月27日12:59:56SaltStack介绍-日常管理(五)已关闭评论 494 views

第1章 Salt日常管理

1.1 使用include文件编写sls

参见:https://blog.leonshadow.com/763482/2148.html#112_sls

生产实践:使用include方式拆分sls文件,include的路径为当前base目录为根目录。

1.2 salt-run使用

  • 测试minion是否可以连接
1
2
3
4
5
[root@linux-node01 ~]# salt-run manage.status
down:
up:
    - linux-node01
    - linux-node02
  • 查看salt软件版本
1
2
3
4
5
6
7
8
9
[root@linux-node01 ~]# salt-run manage.versions
Master:
    2019.2.5
Up to date:
    ----------
    linux-node01:
        2019.2.5
    linux-node02:
        2019.2.5

1.3 编排预演test=True

1
2
# 标记将要做出的修改,但实际并不执行
[root@linux-node01 ~]# salt '*' state.highstate test=True

1.4 修改minion_id

1
2
3
4
5
6
7
[root@linux-node02 ~]# systemctl stop salt-minion
[root@linux-node02 ~]# salt-key -d linux-node02
[root@linux-node02 ~]# > /etc/salt/minion_id
[root@linux-node02 ~]# rm -f /etc/salt/pki/master/minions_pre/linux-node02
[root@linux-node02 ~]# vim /etc/salt/minion
112 #id:
[root@linux-node02 ~]# systemctl start salt-minion

第2章 SaltStack其他管理方式

2.1 master使用ssh远程管理(无minion)

备注:官方文档:https://docs.saltstack.com/en/latest/topics/ssh/index.html

2.1.1 安装salt-ssh服务

1
[root@linux-node01 ~]# yum install -y salt-ssh

备注:此时仅需要salt-ssh即可,不需要salt-master和salt-minion。

2.1.2 编辑配置文件

1
2
3
4
5
6
7
8
9
10
11
12
[root@linux-node01 ~]# vim /etc/salt/roster
linux-node01:
  host: 10.10.10.101
  user: root
  passwd: 123456
  port: 22

linux-node02:
  host: 10.10.10.102
  user: root
  passwd: 123456
  port: 22

2.1.3 运行批量管理命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
[root@linux-node01 ~]# salt-ssh '*' test.ping -i
linux-node02:
    True
linux-node01:
    True

[root@linux-node01 ~]# salt-ssh '*' -r 'w'
linux-node02:
    ----------
    retcode:
        0
    stderr:
    stdout:
        root@10.10.10.102's password:
         13:30:24 up  5:24,  1 user,  load average: 0.03, 0.04, 0.05
        USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
        root     pts/0    10.10.10.1       09:57    3:04   0.22s  0.22s -bash
linux-node01:
    ----------
    retcode:
        0
    stderr:
    stdout:
        root@10.10.10.101'
s password:
         13:30:29 up  5:24,  2 users,  load average: 0.07, 0.06, 0.06
        USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
        root     pts/0    10.10.10.1       09:57   13.00s  2.35s  0.08s /usr/bin/python /usr/bin/salt-ssh * -r w
        root     pts/1    10.10.10.1       10:12   14:37   0.11s  0.11s -bash

2.1.4 命令详解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
[root@linux-node01 ~]# salt-ssh --help
Usage: salt-ssh [options] '<target>' <function> [arguments]

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'.
  --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
  -r, --raw, --raw-shell
                        Don't execute a salt routine on the targets, execute a
                        raw shell command.
  --roster=ROSTER       Define which roster system to use, this defines if a
                        database backend, scanner, or custom roster system is
                        used. Default: '
flat'.

  --roster-file=ROSTER_FILE
                        Define an alternative location for the default roster
                        file location. The default roster file is called
                        roster and is found in the same directory as the
                        master config file.
  --refresh, --refresh-cache
                        Force a refresh of the master side data cache of the
                        target'
s data. This is needed if a target's grains
                        have been changed and the auto refresh timeframe has
                        not been reached.
  --max-procs=SSH_MAX_PROCS
                        Set the number of concurrent minions to communicate
                        with. This value defines how many processes are opened
                        up at a time to manage connections, the more running
                        processes the faster communication should be. Default:
                        25.
  --extra-filerefs=EXTRA_FILEREFS
                        Pass in extra files to include in the state tarball.
  --min-extra-modules=MIN_EXTRA_MODS
                        One or comma-separated list of extra Python modulesto
                        be included into Minimal Salt.
  --thin-extra-modules=THIN_EXTRA_MODS
                        One or comma-separated list of extra Python modulesto
                        be included into Thin Salt.
  -v, --verbose         Turn on command verbosity, display jid.
  -s, --static          Return the data from minions as a group after they all
                        return.
  -w, --wipe            Remove the deployment of the salt files when done
                        executing.
  -W, --rand-thin-dir   Select a random temp dir to deploy on the remote
                        system. The dir will be cleaned after the execution.
  -t, --regen-thin, --thin
                        Trigger a thin tarball regeneration. This is needed if
                        custom grains/modules/states have been added or
                        updated.
  --python2-bin=PYTHON2_BIN
                        Path to a python2 binary which has salt installed.
  --python3-bin=PYTHON3_BIN
                        Path to a python3 binary which has salt installed.
  --jid=JID             Pass a JID to be used instead of generating one.

  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=SSH_LOG_FILE
                        Log file path. Default: '
/var/log/salt/ssh'.
    --log-file-level=LOG_LEVEL_LOGFILE
                        Logfile logging log level. One of '
all', 'garbage',
                        '
trace', 'debug', 'profile', 'info', 'warning',
                        '
error', 'critical', 'quiet'. Default: 'warning'.

  Target Options:
    Target selection options.

    -H, --hosts         List all known hosts to currently visible or other
                        specified rosters
    -E, --pcre          Instead of using shell globs to evaluate the target
                        servers, use pcre regular expressions.
    -L, --list          Instead of using shell globs to evaluate the target
                        servers, take a comma or whitespace delimited list of
                        servers.
    -G, --grain         Instead of using shell globs to evaluate the target
                        use a grain value to identify targets, the syntax for
                        the target is the grain key followed by a
                        globexpression: "os:Arch*".
    -P, --grain-pcre    Instead of using shell globs to evaluate the target
                        use a grain value to identify targets, the syntax for
                        the target is the grain key followed by a pcre regular
                        expression: "os:Arch.*".
    -N, --nodegroup     Instead of using shell globs to evaluate the target
                        use one of the predefined nodegroups to identify a
                        list of targets.
    -R, --range         Instead of using shell globs to evaluate the target
                        use a range expression to identify targets. Range
                        expressions look like %cluster.

  Additional Target Options:
    Additional options for minion targeting.

    --delimiter=DELIMITER
                        Change the default delimiter for matching in multi-
                        level data structures. Default: '
:'.

  Output Options:
    Configure your preferred output format.

    --out=OUTPUT, --output=OUTPUT
                        Print the output from the '
salt-ssh' 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.

  SSH Options:
    Parameters for the SSH client.

    --remote-port-forwards=SSH_REMOTE_PORT_FORWARDS
                        Setup remote port forwarding using the same syntax as
                        with the -R parameter of ssh. A comma separated list
                        of port forwarding definitions will be translated into
                        multiple -R parameters.
    --ssh-option=SSH_OPTIONS
                        Equivalent to the -o ssh command option. Passes
                        options to the SSH client in the format used in the
                        client configuration file. Can be used multiple times.

  Authentication Options:
    Parameters affecting authentication.

    --priv=SSH_PRIV     Ssh private key file.
    --priv-passwd=SSH_PRIV_PASSWD
                        Passphrase for ssh private key file.
    -i, --ignore-host-keys
                        By default ssh host keys are honored and connections
                        will ask for approval. Use this option to disable
                        StrictHostKeyChecking.
    --no-host-keys      Removes all host key checking functionality from SSH
                        session.
    --user=SSH_USER     Set the default user to attempt to use when
                        authenticating.
    --passwd=SSH_PASSWD
                        Set the default password to attempt to use when
                        authenticating.
    --askpass           Interactively ask for the SSH password with no echo -
                        avoids password in process args and stored in history.
    --key-deploy        Set this flag to attempt to deploy the authorized ssh
                        key with all minions. This combined with --passwd can
                        make initial deployment of keys very fast and easy.
    --identities-only   Use the only authentication identity files configured
                        in the ssh_config files. See IdentitiesOnly flag in
                        man ssh_config.
    --sudo              Run command via sudo.
    --update-roster     If hostname is not found in the roster, store the
                        informationinto the default roster file (flat).

  Scan Roster Options:
    Parameters affecting scan roster.

    --scan-ports=SSH_SCAN_PORTS
                        Comma-separated list of ports to scan in the scan
                        roster.
    --scan-timeout=SSH_SCAN_TIMEOUT
                        Scanning socket timeout for the scan roster.

You can find additional help about salt-ssh issuing "man salt-ssh" or on
http://docs.saltstack.com

2.1.5 运行原理

  1. Master端将要执行的命令打包发送给要执行的客户端
  2. 客户端在本地解包执行命令
  3. 客户端将执行命令后的结果发送给Master

备注:salt-ssh执行命令并不是每次通过SSH连接到客户端执行命令的。

2.2 minion本地管理(无Master)

备注:此时仅需要salt-minion服务即可,不需要salt-master。

2.2.1 安装minion服务

1
[root@linux-node02 ~]# yum install -y salt-minion

2.2.2 修改配置文件

1
2
3
4
5
6
7
8
9
10
11
12
[root@linux-node02 ~]# vim /etc/salt/minion
574 file_client: local
# 添加以下内容
594 file_roots:
595   base:
596     - /srv/salt/base
597   dev:
598     - /srv/salt/dev
599   test:
600     - /srv/salt/test
601   prod:
602     - /srv/salt/prod

2.2.3 创建配置文件目录

1
[root@linux-node02 ~]# mkdir -p /srv/salt/{base,dev,test,prod}

2.2.4 关闭minion服务

1
[root@linux-node02 ~]# systemctl stop salt-minion

2.2.5 执行管理命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
[root@linux-node02 ~]# salt-call --local state.sls web.tomcat
local:
----------
          ID: jdk-install
    Function: pkg.installed
        Name: java-1.8.0-openjdk
      Result: True
     Comment: All specified packages are already installed
     Started: 10:19:08.534559
    Duration: 1233.081 ms
     Changes:  
----------
          ID: tomcat-group
    Function: group.present
        Name: java
      Result: True
     Comment: Group java is present and up to date
     Started: 10:19:09.768458
    Duration: 0.696 ms
     Changes:  
----------
          ID: tomcat-user
    Function: user.present
        Name: java
      Result: True
     Comment: User java is present and up to date
     Started: 10:19:09.770256
    Duration: 1.212 ms
     Changes:  
----------
          ID: tomcat-install
    Function: file.managed
        Name: /server/tools/apache-tomcat-8.5.43.tar.gz
      Result: True
     Comment: File /server/tools/apache-tomcat-8.5.43.tar.gz is in the correct state
     Started: 10:19:09.773772
    Duration: 693.251 ms
     Changes:  
----------
          ID: tomcat-install
    Function: cmd.run
        Name: cd /server/tools/ && tar xf apache-tomcat-8.5.43.tar.gz && mv apache-tomcat-8.5.43 /home/java/tomcat-8.5.43
      Result: True
     Comment: unless condition is true
     Started: 10:19:10.468042
    Duration: 47.842 ms
     Changes:  
----------
          ID: tomcat-security
    Function: file.directory
        Name: /home/java/tomcat-8.5.43
      Result: True
     Comment: The directory /home/java/tomcat-8.5.43 is in the correct state
     Started: 10:19:10.516747
    Duration: 108.957 ms
     Changes:  

Summary for local
------------
Succeeded: 6
Failed:    0
------------
Total states run:     6
Total run time:   2.085 s

2.3 API远程管理

备注:官方文档:https://docs.saltstack.com/en/latest/ref/netapi/all/salt.netapi.rest_cherrypy.html#a-rest-api-for-salt

API管理必须使用https协议,若无https需要先生成ssl证书并配置https。

2.3.1 安装salt-api服务

1
[root@linux-node01 ~]# yum install -y salt-api

2.3.2 生成自签名证书(可选)

1
2
3
4
5
[root@linux-node01 ~]# yum install -y salt-minion pyOpenSSL
# salt-call命令在salt-minion包中
[root@linux-node01 ~]# salt-call --local tls.create_self_signed_cert
local:
Created Private Key: "/etc/pki/tls/certs/localhost.key." Created Certificate: "/etc/pki/tls/certs/localhost.crt."

2.3.3 创建服务用户和密码

1
2
[root@linux-node01 ~]# useradd -M -s /sbin/nologin saltapi
[root@linux-node01 ~]# echo "123456" | passwd saltapi --stdin

2.3.4 编辑配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[root@linux-node01 ~]# vim /etc/salt/master
12 default_include: master.d/*.conf

[root@linux-node01 ~]# vim /etc/salt/master.d/api.conf
rest_cherrypy:
  host: 10.10.10.101
  port: 8000
  ssl_crt: /etc/pki/tls/certs/localhost.crt
  ssl_key: /etc/pki/tls/certs/localhost.key

[root@linux-node01 ~]# vim /etc/salt/master.d/auth.conf
external_auth:
  pam:
    saltapi:       # Authorized user
      - .*         # to allow access to all
      - '@wheel'   # to allow access to all wheel modules
      - '@runner'  # to allow access to all runner modules
      - '@jobs'    # to allow access to the jobs runner and/or wheel module

2.3.5 重启master服务

1
2
[root@linux-node01 ~]# systemctl restart salt-master
[root@linux-node01 ~]# systemctl restart salt-api

2.3.6 使用salt-api

2.3.6.1 获取用户token

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@linux-node02 ~]# curl -sSk https://10.10.10.101:8000/login \
     -H 'Accept: application/x-yaml' \
     -d username=saltapi \
     -d password=123456 \
     -d eauth=pam
return:
- eauth: pam
  expire: 1594924413.556822
  perms:
  - .*
  - '@wheel'
  - '@runner'
  - '@jobs'
  start: 1594881213.556821
  token: cb0f6e82428daf87c0cd0e21bc28abaddd5b0d95
  user: saltapi

2.3.6.2 执行模块

1
2
3
4
5
6
7
8
9
[root@linux-node01 ~]# curl -sSk https://10.10.10.101:8000 \
    -H 'Accept: application/x-yaml' \
    -H 'X-Auth-Token: cb0f6e82428daf87c0cd0e21bc28abaddd5b0d95 '\
    -d client=local \
    -d tgt='*' \
-d fun=test.ping
return:
- linux-node02: true
  linux-node01: true

2.3.6.3 执行模块加参数

1
2
3
4
5
6
7
8
9
[root@linux-node01 ~]# curl -sSk https://10.10.10.101:8000 \
    -H 'Accept: application/x-yaml' \
    -H 'X-Auth-Token: cb0f6e82428daf87c0cd0e21bc28abaddd5b0d95 '\
    -d client=local \
    -d tgt='*' \
-d fun=cmd.run -d arg='uptime'
return:
- linux-node02: ' 17:18:40 up 49 min,  1 user,  load average: 0.00, 0.01, 0.05'
  linux-node01: ' 17:18:40 up 50 min,  1 user,  load average: 0.40, 0.23, 0.13'

2.3.6.4 获取Grains

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[root@linux-node01 ~]# curl -sSk https://10.10.10.101:8000/minions/linux-node02 \
    -H 'Accept: application/x-yaml' \
-H 'X-Auth-Token: cb0f6e82428daf87c0cd0e21bc28abaddd5b0d95'
return:
- linux-node02:
    SSDs: []
    biosreleasedate: 07/29/2019
    biosversion: '6.00'
    cpu_flags:
    ……
    virtual: VMware
    zfs_feature_flags: false
    zfs_support: false
    zmqversion: 4.1.4
weinxin
我的微信
如果有技术上的问题可以扫一扫我的微信