salt/README.md

17 KiB
Raw Blame History

Краткое руководство по Salt Stack



В качестве тестового стенда используется виртуальная лаборатория

stand

Установка Salt

процесс установки описан в документации https://docs.saltproject.io/salt/install-guide/en/latest/index.html

Master на Альт сервер

apt-get update && apt-get install -y salt-master salt-minion salt-api

systemctl enable --now salt-master
systemctl enable --now salt-minion

вверх

Minion на CentOS Stream 9

sudo rpm --import https://repo.saltproject.io/salt/py3/redhat/9/x86_64/SALT-PROJECT-GPG-PUBKEY-2023.pub
curl -fsSL https://repo.saltproject.io/salt/py3/redhat/9/x86_64/latest.repo | sudo tee /etc/yum.repos.d/salt.repo

sudo dnf install -y salt-minion

sudo systemctl enable --now salt-minion

Minion на Debian 12

su -
mkdir /etc/apt/keyrings

curl -fsSL -o /etc/apt/keyrings/salt-archive-keyring-2023.gpg https://repo.saltproject.io/salt/py3/debian/12/amd64/SALT-PROJECT-GPG-PUBKEY-2023.gpg
echo "deb [signed-by=/etc/apt/keyrings/salt-archive-keyring-2023.gpg arch=amd64] https://repo.saltproject.io/salt/py3/debian/12/amd64/latest bookworm main" | tee /etc/apt/sources.list.d/salt.list

apt update


apt install -y salt-minion

systemctl enable --now salt-minion

вверх

Minion на Альт Сервер 10.2

su -
apt-get update


apt-get install -y salt-minion

systemctl enable --now salt-minion

Настройка master

Описание возможных директив конфигурационного файла приводится в файле /etc/salt/master или в документации https://docs.saltproject.io/en/latest/ref/configuration/master.html

Хорошим тоном является создание своих конфигурационных файлов в директории *.d

vim /etc/salt/master.d/master.conf
# The network interface to bind to
interface: 0.0.0.0

# The Request/Reply port
# Для файлового сервера, аутентификации, возврата результатов и проч.
ret_port: 4506

# The port minions bind to for commands, aka the publish port
publish_port: 4505

# Писать статистику после выполнения команд
cli_summary: true

# Объединение узлов в группы
# Пробелы в выборках нужно обрабатывать
# НЕ правильно - 'G@os:CentOS Strem'
# Правильно - 'G@os:CentOS?Stream' или 'P@os:CentOS\sStream' или 'G@os:CentOS*'
nodegroups:
  alt: 'G@os:ALT'
  centos-stream: 'G@os:CentOS?Stream'
  centos: 'P@os:CentOS\sStream'
  debian: 'G@os:Debian'
  apt: 'deb-*'
  rpm: 'centos-*'


worker_threads: 5

вверх

Настройка minion

https://docs.saltproject.io/en/latest/ref/configuration/minion.html

cat /etc/salt/minion.d/minion.conf
# Адрес мастера
master: 10.1.4.1

# Уникальный идентификатор миньона
# по-умолчанию берётся hostname
id: centos-minion-1

Ключи

Для аутентификации и авторизации в Salt используются пары ключей (закрытый, открытый). При включении службы миньона формируется пара ключей, открытый ключ отправляется на мастер.

У мастера есть специальная утилита для работы с ключами - salt-key

Некоторые примеры работы с ней:

Посмотреть все ключи

[root@alt-master ~]#  salt-key -L
Accepted Keys:
Denied Keys:
Unaccepted Keys:
alt-minion-5
alt-minion-6
centos-minion-1
centos-minion-2
deb-minion-3
deb-minion-4
Rejected Keys:

вверх

Принять ключ конкретного миньона

[root@alt-master ~]# salt-key -l accepted
Accepted Keys:
[root@alt-master ~]# salt-key -a centos-minion-1
The following keys are going to be accepted:
Unaccepted Keys:
centos-minion-1
Proceed? [n/Y] 
Key for minion centos-minion-1 accepted.

Принять ключи по маске идентификаторов

[root@alt-master ~]# salt-key -a 'deb*'
The following keys are going to be accepted:
Unaccepted Keys:
deb-minion-3
deb-minion-4
Proceed? [n/Y] 
Key for minion deb-minion-3 accepted.
Key for minion deb-minion-4 accepted.

Показать только принятые ключи

salt-key -l accepted

Принять все предлагаемые ключи

salt-key -A

Удалить ключи по маске

salt-key -d 'deb*'

Удалить конкретный ключ

salt-key -d deb-minion-3

Удалить все ключи

salt-key -D

Для дальнейшей работы необходимо принять ключи миньонов (уверены в том, что в текущем окружении только проверенные узлы)

[root@alt-master ~]# salt-key -A
The following keys are going to be accepted:
Unaccepted Keys:
alt-minion-5
alt-minion-6
centos-minion-2
Proceed? [n/Y] 
Key for minion alt-minion-5 accepted.
Key for minion alt-minion-6 accepted.
Key for minion centos-minion-2 accepted.

Таким образом должен получиться такой вывод

[root@alt-master ~]# salt-key -L
Accepted Keys:
alt-minion-5
alt-minion-6
centos-minion-1
centos-minion-2
deb-minion-3
deb-minion-4
Denied Keys:
Unaccepted Keys:
Rejected Keys:

вверх

Первый тест

[root@alt-master ~]# salt '*' test.ping
centos-minion-2:
    True
deb-minion-3:
    True
deb-minion-4:
    True
centos-minion-1:
    True
alt-minion-6:
    True
alt-minion-5:
    True


-------------------------------------------
Summary
-------------------------------------------
# of minions targeted: 6
# of minions returned: 6
# of minions that did not return: 0
# of minions with errors: 0
-------------------------------------------

Сбор данных

grains - зёрна, переменные, которые получает мастер с миньона

[root@alt-master ~]# salt 'alt-minion-6' grains.
grains.append     grains.delval     grains.fetch      grains.get        grains.item       grains.ls         grains.set        grains.setvals    
grains.delkey     grains.equals     grains.filter_by  grains.has_value  grains.items      grains.remove     grains.setval

двойной Tab покажет возможные варианты команды

Сбор всех данных

salt 'alt-minion-6' grains.items

Получение конкретных значений

salt 'alt-minion-6' grains.item ipv4
salt 'alt-minion-6' grains.item os
salt 'alt-minion-6' grains.item cpuarch

вверх

Указание конкретных миньонов для запуска

По маске имён

salt 'deb-*' test.ping

* - и прочие подстановочные символы необходимо оборачивать кавычками, иначе оболочка их будет интерпретировать по-своему - Glob-подстановки

По зёрнам (grains) в качестве фильтров

salt -G 'os:ALT' test.ping
salt -G 'os:CentOS Stream' test.ping

По группам узлов

Группы узлов необходимо заранее создать в настройках мастера

salt -N debian test.ping

Составные подстановки

В составных выборках необходимо обрабатывать пробелы, т.к. не ясно где заканчивается условие, а где составное имя
НЕ правильно - 'G@os:CentOS Strem'
Правильно - 'G@os:CentOS?Stream'
Правильно - 'P@os:CentOS\sStream'
Правильно - G@os:CentOS*

deb_ip=$(salt 'deb-minion-3' network.ipaddrs --out=newline_values_only)
salt -C "( G@os:CentOS* and alt* ) or S@${deb_ip}" test.ping

вверх

Модули исполнения

Несколько стандартных модулей

  • test, saltutils - служебные модули для тестирования и диагностики
  • file, package, service, system, cmd - назначение понятно из названия, работа с файлами, пакетами, службами systemd и пр.
  • apache, postgres, nginx, redis - модули для работы с одноимёнными системами
  • ansiblegate, chef, puppet - шлюзы для соединения с другими системами управления состоянием

Двойной Tab позволяет получить сведения о возможных командах в каждом модуле

[root@alt-master ~]# salt -G 'os:CentOS Stream' test.
test.arg                   test.conf_test             test.get_opts              test.provider              test.sleep                 test.versions_information
test.arg_clean             test.cross_test            test.kwarg                 test.providers             test.stack                 test.versions_report
test.arg_repr              test.deprecation_warning   test.module_report         test.raise_exception       test.true                  
test.arg_type              test.echo                  test.not_loaded            test.random_hash           test.try                   
test.assertion             test.exception             test.opts_pkg              test.rand_sleep            test.tty                   
test.attr_call             test.false                 test.outputter             test.rand_str              test.version               
test.collatz               test.fib                   test.ping                  test.retcode               test.versions              
[root@alt-master ~]# 
[root@alt-master ~]# 
[root@alt-master ~]# salt -G 'os:CentOS Stream' file.
file.access                      file.directory_exists            file.group_to_gid                file.mknod_blkdev                file.rmdir
file.append                      file.dirname                     file.is_blkdev                   file.mknod_chrdev                file.search
file.apply_template_on_contents  file.diskusage                   file.is_chrdev                   file.mknod_fifo                  file.sed
file.basename                    file.extract_hash                file.is_fifo                     file.move                        file.sed_contains
file.blockreplace                file.file_exists                 file.is_hardlink                 file.normpath                    file.seek_read
file.chattr                      file.find                        file.is_link                     file.open_files                  file.seek_write
file.check_file_meta             file.get_devmm                   file.join                        file.pardir                      file.set_mode
file.check_hash                  file.get_diff                    file.lchown                      file.patch                       file.set_selinux_context
file.check_managed               file.get_gid                     file.line                        file.path_exists_glob            file.source_list
file.check_managed_changes       file.get_group                   file.link                        file.prepend                     file.stats
file.check_perms                 file.get_hash                    file.list_backup                 file.psed                        file.statvfs
file.chgrp                       file.get_managed                 file.list_backups                file.read                        file.symlink
file.chown                       file.get_mode                    file.list_backups_dir            file.readdir                     file.touch
file.comment                     file.get_selinux_context         file.lsattr                      file.readlink                    file.truncate
file.comment_line                file.get_source_sum              file.lstat                       file.remove                      file.uid_to_user
file.contains                    file.get_sum                     file.makedirs                    file.remove_backup               file.uncomment
file.contains_glob               file.get_uid                     file.makedirs_perms              file.rename                      file.user_to_uid
file.contains_regex              file.get_user                    file.manage_file                 file.replace                     file.write
file.copy                        file.gid_to_group                file.mkdir                       file.restore_backup              
file.delete_backup               file.grep                        file.mknod                       file.restorecon    

Несколько полезных функций

  • test.ping - доступность миньона
  • saltutil.sync_all - синхронизация всех сущностей, которые имеются на мастере
  • sys.doc - получение справки о модуле
  • state.test - проверка возможности исполнения без непосредственного исполнения, алиас для state.apply test=True

Формулы

вверх

Источники

https://www.youtube.com/watch?v=6zY41M2anrY
https://gitlab.com/bergentroll-docs/saltstack-tutorial
https://docs.saltproject.io/en/latest/contents.html