From a75826141405f970c2a7e7968cde0d8fd38ad3d6 Mon Sep 17 00:00:00 2001 From: yuobrezkov Date: Fri, 31 Jan 2025 15:27:31 +0300 Subject: [PATCH 1/2] Updated README for all rolers, added role for configure sshd_config --- ssh/README.md | 0 ssh/roles/ssh_setup/README.md | 37 +++++++++++++++++++++++++++ ssh/roles/ssh_setup/handlers/main.yml | 5 ++++ ssh/roles/ssh_setup/meta/main.yml | 34 ++++++++++++++++++++++++ ssh/roles/ssh_setup/tasks/main.yml | 26 +++++++++++++++++++ ssh/roles/ssh_setup/tests/inventory | 2 ++ ssh/roles/ssh_setup/tests/test.yml | 5 ++++ ssh/roles/ssh_setup/vars/main.yml | 2 ++ ssh/ssh_setup_config.yml | 6 +++++ 9 files changed, 117 insertions(+) create mode 100644 ssh/README.md create mode 100644 ssh/roles/ssh_setup/README.md create mode 100644 ssh/roles/ssh_setup/handlers/main.yml create mode 100644 ssh/roles/ssh_setup/meta/main.yml create mode 100644 ssh/roles/ssh_setup/tasks/main.yml create mode 100644 ssh/roles/ssh_setup/tests/inventory create mode 100644 ssh/roles/ssh_setup/tests/test.yml create mode 100644 ssh/roles/ssh_setup/vars/main.yml create mode 100644 ssh/ssh_setup_config.yml diff --git a/ssh/README.md b/ssh/README.md new file mode 100644 index 0000000..e69de29 diff --git a/ssh/roles/ssh_setup/README.md b/ssh/roles/ssh_setup/README.md new file mode 100644 index 0000000..30b0ddf --- /dev/null +++ b/ssh/roles/ssh_setup/README.md @@ -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 +``` + +## Автор + +Автор: [Юрий Обрезков] \ No newline at end of file diff --git a/ssh/roles/ssh_setup/handlers/main.yml b/ssh/roles/ssh_setup/handlers/main.yml new file mode 100644 index 0000000..074dad3 --- /dev/null +++ b/ssh/roles/ssh_setup/handlers/main.yml @@ -0,0 +1,5 @@ +--- +- name: Restart SSH + service: + name: sshd + state: restarted \ No newline at end of file diff --git a/ssh/roles/ssh_setup/meta/main.yml b/ssh/roles/ssh_setup/meta/main.yml new file mode 100644 index 0000000..ea68190 --- /dev/null +++ b/ssh/roles/ssh_setup/meta/main.yml @@ -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. diff --git a/ssh/roles/ssh_setup/tasks/main.yml b/ssh/roles/ssh_setup/tasks/main.yml new file mode 100644 index 0000000..5f5e33b --- /dev/null +++ b/ssh/roles/ssh_setup/tasks/main.yml @@ -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 \ No newline at end of file diff --git a/ssh/roles/ssh_setup/tests/inventory b/ssh/roles/ssh_setup/tests/inventory new file mode 100644 index 0000000..878877b --- /dev/null +++ b/ssh/roles/ssh_setup/tests/inventory @@ -0,0 +1,2 @@ +localhost + diff --git a/ssh/roles/ssh_setup/tests/test.yml b/ssh/roles/ssh_setup/tests/test.yml new file mode 100644 index 0000000..393d02e --- /dev/null +++ b/ssh/roles/ssh_setup/tests/test.yml @@ -0,0 +1,5 @@ +--- +- hosts: localhost + remote_user: root + roles: + - ssh_setup diff --git a/ssh/roles/ssh_setup/vars/main.yml b/ssh/roles/ssh_setup/vars/main.yml new file mode 100644 index 0000000..91d7182 --- /dev/null +++ b/ssh/roles/ssh_setup/vars/main.yml @@ -0,0 +1,2 @@ +--- +# vars file for ssh diff --git a/ssh/ssh_setup_config.yml b/ssh/ssh_setup_config.yml new file mode 100644 index 0000000..0ec2459 --- /dev/null +++ b/ssh/ssh_setup_config.yml @@ -0,0 +1,6 @@ +- name: Update ssh config + become: yes + hosts: all + roles: + - role: ssh_setup + tags: ssh_setup From 7c458385979aa79a5ad8d402181bf49180256b33 Mon Sep 17 00:00:00 2001 From: yuobrezkov Date: Fri, 31 Jan 2025 15:28:35 +0300 Subject: [PATCH 2/2] Updated README for all rolers, added role for configure sshd_config --- docker/roles/docker-common/README.md | 51 +++++++++++++-------------- k8s/roles/common-kubernetes/README.md | 51 ++++++++++++++++++++------- k8s/roles/kubernetes-master/README.md | 51 ++++++++++++++++++++------- k8s/roles/kubernetes-worker/README.md | 39 +++++++++++++------- 4 files changed, 128 insertions(+), 64 deletions(-) diff --git a/docker/roles/docker-common/README.md b/docker/roles/docker-common/README.md index 225dd44..4881b68 100644 --- a/docker/roles/docker-common/README.md +++ b/docker/roles/docker-common/README.md @@ -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 - roles: - - { role: username.rolename, x: 42 } +```yaml +- hosts: all + become: yes + roles: + - docker-install +``` -License -------- +## Автор -BSD - -Author Information ------------------- - -An optional section for the role authors to include contact information, or a website (HTML is not allowed). +Автор: [Юрий Обрезков] diff --git a/k8s/roles/common-kubernetes/README.md b/k8s/roles/common-kubernetes/README.md index 7ebfb80..b33c788 100644 --- a/k8s/roles/common-kubernetes/README.md +++ b/k8s/roles/common-kubernetes/README.md @@ -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. \ No newline at end of file +| Переменная | Значение по умолчанию | +|---------------|--------------------| +| `k8s_version` | `v1.31` | +| `crio_version` | `v1.30` | + +## Зависимости + +Данная роль не имеет зависимостей от других ролей. + +## Пример Playbook + +Пример использования роли в Playbook: + +```yaml +- hosts: all + become: yes + roles: + - common-kubernetes +``` + +## Автор + +Автор: [Юрий Обрезков] \ No newline at end of file diff --git a/k8s/roles/kubernetes-master/README.md b/k8s/roles/kubernetes-master/README.md index 5ffd381..408a60a 100644 --- a/k8s/roles/kubernetes-master/README.md +++ b/k8s/roles/kubernetes-master/README.md @@ -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. -------------- \ No newline at end of file +| Переменная | Значение по умолчанию | +|-------------------|--------------------| +| `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 +``` + +## Автор + +Автор: [Юрий обрезков] \ No newline at end of file diff --git a/k8s/roles/kubernetes-worker/README.md b/k8s/roles/kubernetes-worker/README.md index a1cb11c..b583db1 100644 --- a/k8s/roles/kubernetes-worker/README.md +++ b/k8s/roles/kubernetes-worker/README.md @@ -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 +``` + +## Автор + +Автор: [Юрий Обрезков]