roles/ssh #2

Merged
Ghost merged 2 commits from roles/ssh into main 2025-01-31 15:31:05 +03:00
13 changed files with 245 additions and 64 deletions

View File

@ -1,38 +1,37 @@
Role Name # Роль Ansible: Установка Docker
=========
A brief description of the role goes here. ## Описание
Requirements Данная роль предназначена для установки и настройки Docker на серверах с Debian/Ubuntu. В рамках выполнения роли:
------------
Any pre-requisites that may not be covered by Ansible itself or the role should be mentioned here. For instance, if the role uses the EC2 module, it may be a good idea to mention in this section that the boto package is required. 1. Удаляются старые версии Docker и связанных пакетов.
2. Обновляется кэш `apt`.
3. Устанавливаются необходимые пакеты для работы с репозиториями.
4. Загружается GPG-ключ Docker и добавляется официальный репозиторий.
5. Обновляется кэш пакетов после добавления репозитория.
6. Устанавливаются необходимые компоненты Docker.
7. Обеспечивается запуск и автозапуск службы Docker.
Role Variables ## Требования
--------------
A description of the settable variables for this role should go here, including any variables that are in defaults/main.yml, vars/main.yml, and any variables that can/should be set via parameters to the role. Any variables that are read from other roles and/or the global scope (ie. hostvars, group vars, etc.) should be mentioned here as well. - Поддерживаемая версия ОС: Debian/Ubuntu
- Ansible с правами `root` (например, через `become: yes`)
Dependencies ## Зависимости
------------
A list of other roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles. Данная роль не имеет зависимостей от других ролей.
Example Playbook ## Пример Playbook
----------------
Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too: Пример использования роли в Playbook:
- hosts: servers ```yaml
- hosts: all
become: yes
roles: roles:
- { role: username.rolename, x: 42 } - docker-install
```
License ## Автор
-------
BSD Автор: [Юрий Обрезков]
Author Information
------------------
An optional section for the role authors to include contact information, or a website (HTML is not allowed).

View File

@ -1,20 +1,45 @@
Role Name # Роль Ansible: Инициализация кластера K8s
=========
Это базовый набор, необходимый для инициализации кластера. ## Описание
Тут происходит установка всех модулей, необходимых для настройки кластера K8s
Requirements Данная роль предназначена для базовой настройки и инициализации кластера Kubernetes. В рамках выполнения роли:
------------
Any pre-requisites that may not be covered by Ansible itself or the role should be mentioned here. For instance, if the role uses the EC2 module, it may be a good idea to mention in this section that the boto package is required. 1. Обновляются и очищаются пакеты системы.
2. Удаляются старые репозитории и GPG-ключи Kubernetes и CRI-O.
3. Отключается swap.
4. Загружаются необходимые модули ядра и включается пересылка IPv4-трафика.
5. Устанавливаются базовые пакеты и инструменты для работы с Kubernetes.
6. Добавляются репозитории и GPG-ключи Kubernetes и CRI-O.
7. Устанавливаются `kubelet`, `kubeadm`, `kubectl`, а также `cri-o`.
8. Включается и запускается служба `cri-o`.
Role Variables ## Требования
--------------
A description of the settable variables for this role should go here, including any variables that are in defaults/main.yml, vars/main.yml, and any variables that can/should be set via parameters to the role. Any variables that are read from other roles and/or the global scope (ie. hostvars, group vars, etc.) should be mentioned here as well. - Поддерживаемая версия ОС: Debian/Ubuntu
- Ansible с правами `root` (например, через `become: yes`)
Dependencies ## Переменные роли
------------
A list of other roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles. | Переменная | Значение по умолчанию |
|---------------|--------------------|
| `k8s_version` | `v1.31` |
| `crio_version` | `v1.30` |
## Зависимости
Данная роль не имеет зависимостей от других ролей.
## Пример Playbook
Пример использования роли в Playbook:
```yaml
- hosts: all
become: yes
roles:
- common-kubernetes
```
## Автор
Автор: [Юрий Обрезков]

View File

@ -1,20 +1,45 @@
Role Name # Роль Ansible: Инициализация мастер-ноды K8s
=========
Здесь производится инициализация мастер ноды. ## Описание
Requirements Данная роль предназначена для настройки и инициализации мастер-ноды в кластере Kubernetes. В рамках выполнения роли:
------------
Any pre-requisites that may not be covered by Ansible itself or the role should be mentioned here. For instance, if the role uses the EC2 module, it may be a good idea to mention in this section that the boto package is required. 1. Инициализируется мастер-узел Kubernetes с заданными параметрами.
2. Создается директория `.kube` для хранения конфигурации Kubernetes.
3. Копируется конфигурационный файл `kubeconfig` в домашний каталог пользователя.
4. Устанавливаются корректные права доступа для `kubeconfig`.
5. Устанавливается сетевой аддон Flannel.
Role Variables ## Требования
--------------
A description of the settable variables for this role should go here, including any variables that are in defaults/main.yml, vars/main.yml, and any variables that can/should be set via parameters to the role. Any variables that are read from other roles and/or the global scope (ie. hostvars, group vars, etc.) should be mentioned here as well. - Поддерживаемая версия ОС: Debian/Ubuntu
- Ansible с правами `root` (например, через `become: yes`)
Dependencies ## Переменные роли
------------
A list of other roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles. | Переменная | Значение по умолчанию |
------------- |-------------------|--------------------|
| `cidr_network` | `10.244.0.0/16` |
| `host_ip_address` | `192.168.2.34` |
| `ansible_user_dir` | `/home/user` |
| `ansible_user_id` | `1000` |
| `ansible_user_gid` | `1000` |
## Зависимости
Данная роль не имеет зависимостей от других ролей.
## Пример Playbook
Пример использования роли в Playbook:
```yaml
- hosts: all
become: yes
roles:
- kubernetes-master
```
## Автор
Автор: [Юрий обрезков]

View File

@ -1,20 +1,35 @@
Role Name # Роль Ansible: Инициализация worker-ноды K8s
=========
Здесь воркер присоединяется к кластеру с помощью токена присоединения, который достаётся из мастеры ноды. Для каждого кластера рекомендуется использовать группировку по [master] [worker], а так же самим указывать необходимые значения (как минимум креды) ## Описание
Requirements Данная роль предназначена для присоединения worker-узлов к кластеру Kubernetes. В рамках выполнения роли:
------------
Any pre-requisites that may not be covered by Ansible itself or the role should be mentioned here. For instance, if the role uses the EC2 module, it may be a good idea to mention in this section that the boto package is required. 1. Генерируется токен присоединения на мастер-ноде.
2. Токен передается в worker-ноды.
3. Проверяется, был ли узел уже добавлен в кластер.
4. Выполняется присоединение worker-ноды к кластеру.
Role Variables ## Требования
--------------
A description of the settable variables for this role should go here, including any variables that are in defaults/main.yml, vars/main.yml, and any variables that can/should be set via parameters to the role. Any variables that are read from other roles and/or the global scope (ie. hostvars, group vars, etc.) should be mentioned here as well. - Поддерживаемая версия ОС: Debian/Ubuntu
- Ansible с правами `root` (например, через `become: yes`)
- Группировка хостов в `inventory` по `[master]` и `[worker]`
Dependencies ## Зависимости
------------
A list of other roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles. Данная роль не имеет зависимостей от других ролей.
## Пример Playbook
Пример использования роли в Playbook:
```yaml
- hosts: workers
become: yes
roles:
- kubernetes-worker
```
## Автор
Автор: [Юрий Обрезков]

0
ssh/README.md Normal file
View File

View File

@ -0,0 +1,37 @@
# Роль Ansible: Настройка SSH
## Описание
Данная роль предназначена для настройки сервера SSH на удалённых хостах с помощью Ansible. Она выполняет следующие задачи:
1. Гарантирует, что каталог `/etc/ssh` существует и имеет правильные права доступа.
2. Настраивает параметры SSH-сервера в файле `sshd_config`.
3. Включает и запускает службу `sshd`.
4. При изменении конфигурации SSH перезапускает службу `sshd`.
## Требования
Роль не требует дополнительных зависимостей, кроме установленного Ansible и наличия прав суперпользователя на целевых хостах.
## Переменные роли
Роль не использует внешние переменные и работает с фиксированными параметрами SSH.
## Зависимости
Зависимости от других ролей отсутствуют.
## Пример Playbook
Пример использования роли в Playbook:
```yaml
- hosts: servers
become: yes
roles:
- ssh_config_role
```
## Автор
Автор: [Юрий Обрезков]

View File

@ -0,0 +1,5 @@
---
- name: Restart SSH
service:
name: sshd
state: restarted

View File

@ -0,0 +1,34 @@
galaxy_info:
author: your name
description: your role description
company: your company (optional)
# If the issue tracker for your role is not on github, uncomment the
# next line and provide a value
# issue_tracker_url: http://example.com/issue/tracker
# Choose a valid license ID from https://spdx.org - some suggested licenses:
# - BSD-3-Clause (default)
# - MIT
# - GPL-2.0-or-later
# - GPL-3.0-only
# - Apache-2.0
# - CC-BY-4.0
license: license (GPL-2.0-or-later, MIT, etc)
min_ansible_version: 2.1
# If this a Container Enabled role, provide the minimum Ansible Container version.
# min_ansible_container_version:
galaxy_tags: []
# List tags for your role here, one per line. A tag is a keyword that describes
# and categorizes the role. Users find roles by searching for tags. Be sure to
# remove the '[]' above, if you add tags to this list.
#
# NOTE: A tag is limited to a single word comprised of alphanumeric characters.
# Maximum 20 tags per role.
dependencies: []
# List your role dependencies here, one per line. Be sure to remove the '[]' above,
# if you add dependencies to this list.

View File

@ -0,0 +1,26 @@
- name: Ensure SSH directory exists
file:
path: /etc/ssh
state: directory
mode: '0755'
- name: Configure SSH server
lineinfile:
path: /etc/ssh/sshd_config
regexp: "^{{ item.key }}"
line: "{{ item.key }} {{ item.value }}"
create: yes
state: present
loop:
- { key: "Port", value: "22" }
- { key: "PubkeyAuthentication", value: "yes" }
- { key: "X11Forwarding", value: "yes" }
- { key: "PrintMotd", value: "no" }
- { key: "UsePAM", value: "yes" }
notify: Restart SSH
- name: Ensure SSH service is enabled and running
service:
name: sshd
state: started
enabled: yes

View File

@ -0,0 +1,2 @@
localhost

View File

@ -0,0 +1,5 @@
---
- hosts: localhost
remote_user: root
roles:
- ssh_setup

View File

@ -0,0 +1,2 @@
---
# vars file for ssh

6
ssh/ssh_setup_config.yml Normal file
View File

@ -0,0 +1,6 @@
- name: Update ssh config
become: yes
hosts: all
roles:
- role: ssh_setup
tags: ssh_setup