【自动化运维系列教程】Saltstack工具部署及常用模块

一、Saltstack的介绍

1.作用

基于python语言开发、实现对IT基础设施批量管控

2.特性

  • 开源的、跨平台
  • 基于证书的方式进行认证
  • saltstack角色
    • salt-master管理端
    • salt-minion被管理端
    • salt-syndic分布式
    • salt-api提供API接口
  • 支持分布式部署
  • 支持sls状态文件

二、部署Saltstack

1.环境准备

主机名 IP地址 安装的软件 系统版本
salt_master.linux.com 192.168.140.11 salt-master Centos7.9
salt_node1.linux.com 192.168.140.14 salt-minion Centos7.9
salt_node2.linux.com 192.168.140.15 salt-minion Centos7.9

2.三台服务器关闭防火墙和SElinux、配置时间同步

过程省略

3.三台服务器配置Yum源和Epel源还有Saltstack安装源

如果没有wget命令,请安装yum install -y wget

[root@salt_master ~]# wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
[root@salt_node1 ~]# wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
[root@salt_node2 ~]# wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
[root@salt_master ~]# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
[root@salt_node1 ~]# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
[root@salt_node2 ~]# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
[root@salt_master ~]# wget https://archive.repo.saltproject.io/yum/redhat/7/x86_64/2019.2.repo -O /etc/yum.repos.d/salt.repo
[root@salt_node1 ~]# wget https://archive.repo.saltproject.io/yum/redhat/7/x86_64/2019.2.repo -O /etc/yum.repos.d/salt.repo
[root@salt_node2 ~]# wget https://archive.repo.saltproject.io/yum/redhat/7/x86_64/2019.2.repo -O /etc/yum.repos.d/salt.repo
[root@salt_master ~]# yum clean all && yum makecache
[root@salt_node1 ~]# yum clean all && yum makecache
[root@salt_node2 ~]# yum clean all && yum makecache

4.在管理端安装Salt-master

A.安装Salt-master

[root@salt_master ~]# yum install -y salt-master

B.启动Salt-master服务

[root@salt_master ~]# systemctl enable --now salt-master

C.检查服务是否启动

因为Saltstack基于Python开发,所以需要搜索Python
如果没有netstat命令,请安装yum install -y net-tools

[root@salt_master ~]# netstat -tunlp | grep python
tcp        0      0 0.0.0.0:4505            0.0.0.0:*               LISTEN      1652/python         
tcp        0      0 0.0.0.0:4506            0.0.0.0:*               LISTEN      1659/python

4505端口用于Salt-master内部通信
4506端口用于Salt-masterSalt-minion之间的通信,用于推送任务发布任务

5.在被管理端安装Salt-minion

A.安装Salt-minion

[root@salt_node1 ~]# yum install -y salt-minion
[root@salt_node2 ~]# yum install -y salt-minion

B.修改被管理端上的配置文件

[root@salt_node1 ~]# vim /etc/salt/minion
#配置文件并不完整,仅展示修改的地方
master: 192.168.140.11	#修改为管理端IP,注意格式“:”后面要有空格
id: 192.168.140.14	#修改为本机IP,注意格式“:”后面要有空格
[root@salt_node2 ~]# vim /etc/salt/minion
#配置文件并不完整,仅展示修改的地方
master: 192.168.140.11	#修改为管理端IP,注意格式“:”后面要有空格
id: 192.168.140.15	#修改为本机IP,注意格式“:”后面要有空格

C.启动Salt-minion服务

[root@salt_node1 ~]# systemctl enable --now salt-minion
[root@salt_node2 ~]# systemctl enable --now salt-minion

6.回到管理端,签署证书

A.查看未签署证书的机器

[root@salt_master ~]# salt-key -L
Accepted Keys:	#已签署的证书
Denied Keys:	#拒绝的证书
Unaccepted Keys:	#未接受的证书
192.168.140.14
192.168.140.15
Rejected Keys:	#拒绝的证书

B.接受所有的请求证书

[root@salt_master ~]# salt-key -A -y
The following keys are going to be accepted:
Unaccepted Keys:
192.168.140.14
192.168.140.15
Key for minion 192.168.140.14 accepted.
Key for minion 192.168.140.15 accepted.

C.再次查看状态

[root@salt_master ~]# salt-key -L
Accepted Keys:	#2台机器已经签署证书了
192.168.140.14
192.168.140.15
Denied Keys:
Unaccepted Keys:
Rejected Keys:

D.salt-key命令参数说明

  • -A接受所有
  • -a 主机名/IP接受某一个
  • -D删除所有
  • -d 主机名/IP删除某一个
  • -R拒绝所有
  • -r 主机名/IP拒绝某一个
  • -L列出所有状态
  • -y所有条件都接受

E.测试

测试主机连通性
[root@salt_master ~]# salt "*" test.ping
192.168.140.14:
    True
192.168.140.15:
    True
[root@salt_master ~]# salt "*" cmd.run 'hostname' 
192.168.140.15:
    salt_node2.linux.com
192.168.140.14:
    salt_node1.linux.com

三、匹配minion的方法

-L支持以逗号隔开的方式匹配多个minion

[root@salt_master ~]# salt -L '192.168.140.14,192.168.140.15' test.ping
192.168.140.15:
    True
192.168.140.14:
    True

-S以网段的形式匹配minion

[root@salt_master ~]# salt -S '192.168.140.0/24' test.ping
192.168.140.15:
    True
192.168.140.14:
    True

-E以正则表达式的方式匹配minion

[root@salt_master ~]# salt -E '^192' test.ping
192.168.140.15:
    True
192.168.140.14:
    True
[root@salt_master ~]# salt -E '192.168.140.(14|15)' test.ping
192.168.140.15:
    True
192.168.140.14:
    True

-C以复合条件匹配minion

and/or
S@是特殊写法,和-S作用一致

[root@salt_master ~]# salt -C '192.168.140.15 and S@192.168.140.0/24' test.ping
192.168.140.15:
    True
[root@salt_master ~]# salt -C '192.168.140.15 or S@192.168.140.0/24' test.ping
192.168.140.14:
    True
192.168.140.15:
    True

-N以主机组的方式匹配

需要提前在配置文件中/etc/salt/master定义主机组
L@是特殊写法,和-L作用相同

[root@salt_master ~]# vim /etc/salt/master
#配置文件并不完整,仅展示修改的地方
nodegroups:
   webserver: 'L@192.168.140.14,192.168.140.15'
   
[root@salt_master ~]# systemctl restart salt-master
[root@salt_master ~]# salt -N 'webserver' test.ping
192.168.140.14:
    True
192.168.140.15:
    True

-Ggrains数据组件中的数据匹配minion

  • grains数据组件
    • 保存minion端的状态数据(IP、系统版本、内核版本、主机名等)
  • 查看grains组件中的数据
    • salt '*' grains.items

查看grains收集到的数据

[root@salt_master ~]# salt '192.168.140.14' grains.items
192.168.140.14:
    ----------
    SSDs:
    biosreleasedate:
        11/12/2020
    biosversion:
        6.00
    cpu_flags:
        - fpu
        - vme
        - de
        - pse
        - tsc
        - msr
        - pae
        - mce
        - cx8
        - apic
        - sep
        - mtrr
        - pge
        - mca
        - cmov
        - pat
        - pse36
        - clflush
        - mmx
        - fxsr
        - sse
        - sse2
        - ss
        - syscall
        - nx
        - pdpe1gb
        - rdtscp
        - lm
        - constant_tsc
        - arch_perfmon
        - nopl
        - xtopology
        - tsc_reliable
        - nonstop_tsc
        - eagerfpu
        - pni
        - pclmulqdq
        - ssse3
        - fma
        - cx16
        - pcid
        - sse4_1
        - sse4_2
        - x2apic
        - movbe
        - popcnt
        - tsc_deadline_timer
        - aes
        - xsave
        - avx
        - f16c
        - rdrand
        - hypervisor
        - lahf_lm
        - abm
        - 3dnowprefetch
        - invpcid_single
        - ssbd
        - ibrs
        - ibpb
        - stibp
        - ibrs_enhanced
        - fsgsbase
        - tsc_adjust
        - bmi1
        - avx2
        - smep
        - bmi2
        - invpcid
        - rdseed
        - adx
        - smap
        - clflushopt
        - xsaveopt
        - xsavec
        - xgetbv1
        - arat
        - pku
        - ospke
        - md_clear
        - spec_ctrl
        - intel_stibp
        - flush_l1d
        - arch_capabilities
    cpu_model:
        Intel(R) Core(TM) i7-10875H CPU @ 2.30GHz
    cpuarch:
        x86_64
    disks:
        - sda
        - sr0
        - dm-0
        - dm-1
    dns:
        ----------
        domain:
        ip4_nameservers:
            - 114.114.114.114
            - 8.8.8.8
        ip6_nameservers:
        nameservers:
            - 114.114.114.114
            - 8.8.8.8
        options:
        search:
            - linux.com
        sortlist:
    domain:
        linux.com
    fqdn:
        salt_node1.linux.com
    fqdn_ip4:
        - 192.168.140.14
    fqdn_ip6:
        - fe80::20c:29ff:fe9a:65ec
    fqdns:
    gid:
        0
    gpus:
        |_
          ----------
          model:
              SVGA II Adapter
          vendor:
              vmware
    groupname:
        root
    host:
        salt_node1
    hwaddr_interfaces:
        ----------
        ens33:
            00:0c:29:9a:65:ec
        lo:
            00:00:00:00:00:00
    id:
        192.168.140.14
    init:
        systemd
    ip4_gw:
        192.168.140.2
    ip4_interfaces:
        ----------
        ens33:
            - 192.168.140.14
        lo:
            - 127.0.0.1
    ip6_gw:
        False
    ip6_interfaces:
        ----------
        ens33:
            - fe80::20c:29ff:fe9a:65ec
        lo:
            - ::1
    ip_gw:
        True
    ip_interfaces:
        ----------
        ens33:
            - 192.168.140.14
            - fe80::20c:29ff:fe9a:65ec
        lo:
            - 127.0.0.1
            - ::1
    ipv4:
        - 127.0.0.1
        - 192.168.140.14
    ipv6:
        - ::1
        - fe80::20c:29ff:fe9a:65ec
    kernel:
        Linux
    kernelrelease:
        3.10.0-1160.el7.x86_64
    kernelversion:
        #1 SMP Mon Oct 19 16:18:59 UTC 2020
    locale_info:
        ----------
        defaultencoding:
            UTF-8
        defaultlanguage:
            zh_CN
        detectedencoding:
            UTF-8
        timezone:
            unknown
    localhost:
        salt_node1.linux.com
    lsb_distrib_codename:
        CentOS Linux 7 (Core)
    lsb_distrib_id:
        CentOS Linux
    machine_id:
        fccaaadc79334eeca70f71b88e47f377
    manufacturer:
        VMware, Inc.
    master:
        192.168.140.11
    mdadm:
    mem_total:
        1819
    nodename:
        salt_node1.linux.com
    num_cpus:
        1
    num_gpus:
        1
    os:
        CentOS
    os_family:
        RedHat
    osarch:
        x86_64
    oscodename:
        CentOS Linux 7 (Core)
    osfinger:
        CentOS Linux-7
    osfullname:
        CentOS Linux
    osmajorrelease:
        7
    osrelease:
        7.9.2009
    osrelease_info:
        - 7
        - 9
        - 2009
    path:
        /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
    pid:
        11846
    productname:
        VMware Virtual Platform
    ps:
        ps -efHww
    pythonexecutable:
        /usr/bin/python
    pythonpath:
        - /usr/bin
        - /usr/lib64/python27.zip
        - /usr/lib64/python2.7
        - /usr/lib64/python2.7/plat-linux2
        - /usr/lib64/python2.7/lib-tk
        - /usr/lib64/python2.7/lib-old
        - /usr/lib64/python2.7/lib-dynload
        - /usr/lib64/python2.7/site-packages
        - /usr/lib/python2.7/site-packages
    pythonversion:
        - 2
        - 7
        - 5
        - final
        - 0
    saltpath:
        /usr/lib/python2.7/site-packages/salt
    saltversion:
        2019.2.8
    saltversioninfo:
        - 2019
        - 2
        - 8
        - 0
    selinux:
        ----------
        enabled:
            False
        enforced:
            Disabled
    serialnumber:
        VMware-56 4d fb 59 5c 83 ad 5a-5d 09 15 06 b8 9a 65 ec
    server_id:
        925752345
    shell:
        /bin/sh
    swap_total:
        2047
    systemd:
        ----------
        features:
            +PAM +AUDIT +SELINUX +IMA -APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 -SECCOMP +BLKID +ELFUTILS +KMOD +IDN
        version:
            219
    uid:
        0
    username:
        root
    uuid:
        59fb4d56-835c-5aad-5d09-1506b89a65ec
    virtual:
        VMware
    zfs_feature_flags:
        False
    zfs_support:
        False
    zmqversion:
        4.1.4

grains数据组件中的数据匹配minion

[root@salt_master ~]# salt -G 'master:192.168.140.11' test.ping
192.168.140.14:
    True
192.168.140.15:
    True
[root@salt_master ~]# salt -G 'os:Centos' test.ping
192.168.140.14:
    True
192.168.140.15:
    True

四、常用的模块

1.查看modules组件中的所有模块

[root@salt_master ~]# salt '192.168.140.14' sys.list_modules
192.168.140.14:
    - acl
    - aliases
    - alternatives
    - ansible
    - archive
    - artifactory
    - beacons
    - bigip
    - btrfs
    - buildout
    - cloud
    - cmd
    - composer
    - config
    - consul
    - container_resource
    - cp
    - cron
    - cryptdev
    - data
    - defaults
    - devmap
    - disk
    - django
    - dnsmasq
    - dnsutil
    - drbd
    - environ
    - etcd
    - ethtool
    - event
    - extfs
    - file
    - firewalld
    - gem
    - genesis
    - glassfish
    - gnome
    - google_chat
    - grafana4
    - grains
    - group
    - hashutil
    - highstate_doc
    - hipchat
    - hosts
    - http
    - incron
    - ini
    - inspector
    - introspect
    - iosconfig
    - ip
    - ipset
    - iptables
    - jboss7
    - jboss7_cli
    - k8s
    - kernelpkg
    - key
    - keyboard
    - kmod
    - locale
    - locate
    - log
    - logrotate
    - lowpkg
    - lvm
    - mandrill
    - match
    - mattermost
    - mine
    - minion
    - modjk
    - mount
    - msteams
    - nagios_rpc
    - namecheap_domains
    - namecheap_domains_dns
    - namecheap_domains_ns
    - namecheap_ssl
    - namecheap_users
    - network
    - nexus
    - nova
    - nspawn
    - nxos_api
    - openscap
    - openstack_config
    - opsgenie
    - out
    - pagerduty
    - pagerduty_util
    - pam
    - parallels
    - partition
    - peeringdb
    - pillar
    - pkg
    - pkg_resource
    - postfix
    - ps
    - publish
    - pushover
    - pyenv
    - random
    - random_org
    - rbenv
    - rest_sample_utils
    - restartcheck
    - ret
    - rsync
    - rvm
    - s3
    - s6
    - salt_proxy
    - saltcheck
    - saltutil
    - schedule
    - scsi
    - sdb
    - seed
    - serverdensity_device
    - service
    - shadow
    - slack
    - slsutil
    - smbios
    - smtp
    - solrcloud
    - sqlite3
    - ssh
    - state
    - status
    - statuspage
    - supervisord
    - sys
    - sysctl
    - sysfs
    - syslog_ng
    - system
    - telegram
    - telemetry
    - temp
    - test
    - timezone
    - tuned
    - udev
    - uptime
    - user
    - vault
    - vbox_guest
    - virtualenv
    - vsphere
    - xfs
    - zabbix
    - zenoss

2.查看某个模块的操作方法

[root@salt_master ~]# salt '192.168.140.14' sys.list_functions user
192.168.140.14:
    - user.add
    - user.chfullname
    - user.chgid
    - user.chgroups
    - user.chhome
    - user.chhomephone
    - user.chloginclass
    - user.chother
    - user.chroomnumber
    - user.chshell
    - user.chuid
    - user.chworkphone
    - user.delete
    - user.get_loginclass
    - user.getent
    - user.info
    - user.list_groups
    - user.list_users
    - user.primary_group
    - user.rename
[root@salt_master ~]# salt '192.168.140.14' sys.list_functions service
192.168.140.14:
    - service.available
    - service.disable
    - service.disabled
    - service.enable
    - service.enabled
    - service.execs
    - service.force_reload
    - service.get_all
    - service.get_disabled
    - service.get_enabled
    - service.get_running
    - service.get_static
    - service.mask
    - service.masked
    - service.missing
    - service.reload
    - service.restart
    - service.show
    - service.start
    - service.status
    - service.stop
    - service.systemctl_reload
    - service.unmask

3.查看操作方法的使用说明

[root@salt_master ~]# salt '192.168.140.14' sys.doc user.add
user.add:

    Add a user to the minion

    CLI Example:

        salt '*' user.add name <uid> <gid> <groups> <home> <shell>
[root@salt_master ~]# salt '192.168.140.14' sys.doc service.start
service.start:

    Changed in version 2015.8.12,2016.3.3,2016.11.0
        On minions running systemd>=205, `systemd-run(1)`_ is now used to
        isolate commands run by this function from the ``salt-minion`` daemon's
        control group. This is done to avoid a race condition in cases where
        the ``salt-minion`` service is restarted while a service is being
        modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
        setting a :mod:`config option <salt.modules.config.get>` called
        ``systemd.scope``, with a value of ``False`` (no quotes).

    .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html

    Start the specified service with systemd

    no_block : False
        Set to ``True`` to start the service using ``--no-block``.

        New in version 2017.7.0

    unmask : False
        Set to ``True`` to remove an indefinite mask before attempting to start
        the service.

        New in version 2017.7.0
            In previous releases, Salt would simply unmask a service before
            starting. This behavior is no longer the default.

    unmask_runtime : False
        Set to ``True`` to remove a runtime mask before attempting to start the
        service.

        New in version 2017.7.0
            In previous releases, Salt would simply unmask a service before
            starting. This behavior is no longer the default.

    CLI Example:

        salt '*' service.start <service name>

4.cmd执行命令模块

[root@salt_master ~]# salt '*' cmd.run 'hostname'
192.168.140.14:
    salt_node1.linux.com
192.168.140.15:
    salt_node2.linux.com

5.cron计划任务模块

如果没有ntpdate命令,请安装yum install -y ntpdate

[root@salt_master ~]# salt '*' cron.set_job root '*/30' '*' '*' '*' '*' "/usr/sbin/ntpdate 120.25.115.20 &> /dev/null"
192.168.140.14:
    new
192.168.140.15:
    new
[root@salt_master ~]# salt '*' cmd.run 'crontab -l'
192.168.140.14:
    # Lines below here are managed by Salt, do not edit
    */30 * * * * /usr/sbin/ntpdate 120.25.115.20 &> /dev/null
192.168.140.15:
    # Lines below here are managed by Salt, do not edit
    */30 * * * * /usr/sbin/ntpdate 120.25.115.20 &> /dev/null

6.file管理文件模块

在文件中写入数据,这个文件在被控端上必须存在

[root@salt_master ~]# salt '*' file.append /tmp/file01 "abc123"
192.168.140.15:
    Wrote 1 lines to "/tmp/file01"
192.168.140.14:
    Wrote 1 lines to "/tmp/file01"

7.hosts主机名解析模块

[root@salt_master ~]# salt '*' hosts.set_host 192.168.140.11 salt_master.linux.com
192.168.140.15:
    True
192.168.140.14:
    True
[root@salt_master ~]# salt '*' cmd.run 'cat /etc/hosts'
192.168.140.15:
    127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
    ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
    192.168.140.11		salt_master.linux.com
192.168.140.14:
    127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
    ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
    192.168.140.11		salt_master.linux.com

8.pkg管理软件模块

[root@salt_master ~]# salt '*' pkg.install vsftpd
192.168.140.14:
    ----------
    vsftpd:
        ----------
        new:
            3.0.2-29.el7_9
        old:
192.168.140.15:
    ----------
    vsftpd:
        ----------
        new:
            3.0.2-29.el7_9
        old:

9.service管理服务模块

[root@salt_master ~]# salt '*' service.start vsftpd
192.168.140.15:
    True
192.168.140.14:
    True
[root@salt_master ~]# salt '*' service.enable vsftpd
192.168.140.15:
    True
192.168.140.14:
    True
[root@salt_master ~]# salt '*' cmd.run 'netstat -tunlp | grep ftp'
192.168.140.15:
    tcp6       0      0 :::21                   :::*                    LISTEN      2605/vsftpd
192.168.140.14:
    tcp6       0      0 :::21                   :::*                    LISTEN      12441/vsftpd

10.user/group管理用户和组的模块

[root@salt_master ~]# salt '*' user.add king
192.168.140.14:
    True
192.168.140.15:
    True
[root@salt_master ~]# salt '*' group.add jishu
192.168.140.14:
    True
192.168.140.15:
    True
[root@salt_master ~]# salt '*' group.adduser jishu king
192.168.140.15:
    True
192.168.140.14:
    True