diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 00741cb06..000000000 --- a/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.DS_Store -.idea/ \ No newline at end of file diff --git a/08-ansible-01-base/README.md b/08-ansible-01-base/README.md deleted file mode 100644 index efc5ab9ad..000000000 --- a/08-ansible-01-base/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# Домашнее задание к занятию 1 «Введение в Ansible» - -## Подготовка к выполнению - -1. Установите Ansible версии 2.10 или выше. -2. Создайте свой публичный репозиторий на GitHub с произвольным именем. -3. Скачайте [Playbook](./playbook/) из репозитория с домашним заданием и перенесите его в свой репозиторий. - -## Основная часть - -1. Попробуйте запустить playbook на окружении из `test.yml`, зафиксируйте значение, которое имеет факт `some_fact` для указанного хоста при выполнении playbook. -2. Найдите файл с переменными (group_vars), в котором задаётся найденное в первом пункте значение, и поменяйте его на `all default fact`. -3. Воспользуйтесь подготовленным (используется `docker`) или создайте собственное окружение для проведения дальнейших испытаний. -4. Проведите запуск playbook на окружении из `prod.yml`. Зафиксируйте полученные значения `some_fact` для каждого из `managed host`. -5. Добавьте факты в `group_vars` каждой из групп хостов так, чтобы для `some_fact` получились значения: для `deb` — `deb default fact`, для `el` — `el default fact`. -6. Повторите запуск playbook на окружении `prod.yml`. Убедитесь, что выдаются корректные значения для всех хостов. -7. При помощи `ansible-vault` зашифруйте факты в `group_vars/deb` и `group_vars/el` с паролем `netology`. -8. Запустите playbook на окружении `prod.yml`. При запуске `ansible` должен запросить у вас пароль. Убедитесь в работоспособности. -9. Посмотрите при помощи `ansible-doc` список плагинов для подключения. Выберите подходящий для работы на `control node`. -10. В `prod.yml` добавьте новую группу хостов с именем `local`, в ней разместите localhost с необходимым типом подключения. -11. Запустите playbook на окружении `prod.yml`. При запуске `ansible` должен запросить у вас пароль. Убедитесь, что факты `some_fact` для каждого из хостов определены из верных `group_vars`. -12. Заполните `README.md` ответами на вопросы. Сделайте `git push` в ветку `master`. В ответе отправьте ссылку на ваш открытый репозиторий с изменённым `playbook` и заполненным `README.md`. -13. Предоставьте скриншоты результатов запуска команд. - -## Необязательная часть - -1. При помощи `ansible-vault` расшифруйте все зашифрованные файлы с переменными. -2. Зашифруйте отдельное значение `PaSSw0rd` для переменной `some_fact` паролем `netology`. Добавьте полученное значение в `group_vars/all/exmp.yml`. -3. Запустите `playbook`, убедитесь, что для нужных хостов применился новый `fact`. -4. Добавьте новую группу хостов `fedora`, самостоятельно придумайте для неё переменную. В качестве образа можно использовать [этот вариант](https://hub.docker.com/r/pycontribs/fedora). -5. Напишите скрипт на bash: автоматизируйте поднятие необходимых контейнеров, запуск ansible-playbook и остановку контейнеров. -6. Все изменения должны быть зафиксированы и отправлены в ваш личный репозиторий. - ---- - -### Как оформить решение задания - -Выполненное домашнее задание пришлите в виде ссылки на .md-файл в вашем репозитории. - ---- diff --git a/08-ansible-01-base/playbook/group_vars/all/examp.yml b/08-ansible-01-base/playbook/group_vars/all/examp.yml deleted file mode 100644 index aae018217..000000000 --- a/08-ansible-01-base/playbook/group_vars/all/examp.yml +++ /dev/null @@ -1,2 +0,0 @@ ---- - some_fact: 12 \ No newline at end of file diff --git a/08-ansible-01-base/playbook/group_vars/deb/examp.yml b/08-ansible-01-base/playbook/group_vars/deb/examp.yml deleted file mode 100644 index 11bc6fe03..000000000 --- a/08-ansible-01-base/playbook/group_vars/deb/examp.yml +++ /dev/null @@ -1,2 +0,0 @@ ---- - some_fact: "deb" \ No newline at end of file diff --git a/08-ansible-01-base/playbook/group_vars/el/examp.yml b/08-ansible-01-base/playbook/group_vars/el/examp.yml deleted file mode 100644 index 4c066eb64..000000000 --- a/08-ansible-01-base/playbook/group_vars/el/examp.yml +++ /dev/null @@ -1,2 +0,0 @@ ---- - some_fact: "el" \ No newline at end of file diff --git a/08-ansible-01-base/playbook/inventory/prod.yml b/08-ansible-01-base/playbook/inventory/prod.yml deleted file mode 100644 index 56470ed41..000000000 --- a/08-ansible-01-base/playbook/inventory/prod.yml +++ /dev/null @@ -1,9 +0,0 @@ ---- - el: - hosts: - centos7: - ansible_connection: docker - deb: - hosts: - ubuntu: - ansible_connection: docker \ No newline at end of file diff --git a/08-ansible-01-base/playbook/inventory/test.yml b/08-ansible-01-base/playbook/inventory/test.yml deleted file mode 100644 index 93c1550cf..000000000 --- a/08-ansible-01-base/playbook/inventory/test.yml +++ /dev/null @@ -1,5 +0,0 @@ ---- - inside: - hosts: - localhost: - ansible_connection: local \ No newline at end of file diff --git a/08-ansible-01-base/playbook/site.yml b/08-ansible-01-base/playbook/site.yml deleted file mode 100644 index 2f9930de1..000000000 --- a/08-ansible-01-base/playbook/site.yml +++ /dev/null @@ -1,10 +0,0 @@ ---- - - name: Print os facts - hosts: all - tasks: - - name: Print OS - debug: - msg: "{{ ansible_distribution }}" - - name: Print fact - debug: - msg: "{{ some_fact }}" \ No newline at end of file diff --git a/08-ansible-02-playbook/README.md b/08-ansible-02-playbook/README.md deleted file mode 100644 index a6b53f08c..000000000 --- a/08-ansible-02-playbook/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Домашнее задание к занятию 2 «Работа с Playbook» - -## Подготовка к выполнению - -1. * Необязательно. Изучите, что такое [ClickHouse](https://www.youtube.com/watch?v=fjTNS2zkeBs) и [Vector](https://www.youtube.com/watch?v=CgEhyffisLY). -2. Создайте свой публичный репозиторий на GitHub с произвольным именем или используйте старый. -3. Скачайте [Playbook](./playbook/) из репозитория с домашним заданием и перенесите его в свой репозиторий. -4. Подготовьте хосты в соответствии с группами из предподготовленного playbook. - -## Основная часть - -1. Подготовьте свой inventory-файл `prod.yml`. -2. Допишите playbook: нужно сделать ещё один play, который устанавливает и настраивает [vector](https://vector.dev). Конфигурация vector должна деплоиться через template файл jinja2. От вас не требуется использовать все возможности шаблонизатора, просто вставьте стандартный конфиг в template файл. Информация по шаблонам по [ссылке](https://www.dmosk.ru/instruktions.php?object=ansible-nginx-install). не забудьте сделать handler на перезапуск vector в случае изменения конфигурации! -3. При создании tasks рекомендую использовать модули: `get_url`, `template`, `unarchive`, `file`. -4. Tasks должны: скачать дистрибутив нужной версии, выполнить распаковку в выбранную директорию, установить vector. -5. Запустите `ansible-lint site.yml` и исправьте ошибки, если они есть. -6. Попробуйте запустить playbook на этом окружении с флагом `--check`. -7. Запустите playbook на `prod.yml` окружении с флагом `--diff`. Убедитесь, что изменения на системе произведены. -8. Повторно запустите playbook с флагом `--diff` и убедитесь, что playbook идемпотентен. -9. Подготовьте README.md-файл по своему playbook. В нём должно быть описано: что делает playbook, какие у него есть параметры и теги. Пример качественной документации ansible playbook по [ссылке](https://github.com/opensearch-project/ansible-playbook). Так же приложите скриншоты выполнения заданий №5-8 -10. Готовый playbook выложите в свой репозиторий, поставьте тег `08-ansible-02-playbook` на фиксирующий коммит, в ответ предоставьте ссылку на него. - ---- - -### Как оформить решение задания - -Выполненное домашнее задание пришлите в виде ссылки на .md-файл в вашем репозитории. - ---- diff --git a/08-ansible-02-playbook/playbook/.gitignore b/08-ansible-02-playbook/playbook/.gitignore deleted file mode 100644 index 5ed0cb64c..000000000 --- a/08-ansible-02-playbook/playbook/.gitignore +++ /dev/null @@ -1 +0,0 @@ -files/* \ No newline at end of file diff --git a/08-ansible-02-playbook/playbook/group_vars/clickhouse/vars.yml b/08-ansible-02-playbook/playbook/group_vars/clickhouse/vars.yml deleted file mode 100644 index da987492b..000000000 --- a/08-ansible-02-playbook/playbook/group_vars/clickhouse/vars.yml +++ /dev/null @@ -1,6 +0,0 @@ ---- -clickhouse_version: "22.3.3.44" -clickhouse_packages: - - clickhouse-client - - clickhouse-server - - clickhouse-common-static diff --git a/08-ansible-02-playbook/playbook/inventory/prod.yml b/08-ansible-02-playbook/playbook/inventory/prod.yml deleted file mode 100644 index 83ddf34cb..000000000 --- a/08-ansible-02-playbook/playbook/inventory/prod.yml +++ /dev/null @@ -1,5 +0,0 @@ ---- -clickhouse: - hosts: - clickhouse-01: - ansible_host: diff --git a/08-ansible-02-playbook/playbook/site.yml b/08-ansible-02-playbook/playbook/site.yml deleted file mode 100755 index ab99c50b6..000000000 --- a/08-ansible-02-playbook/playbook/site.yml +++ /dev/null @@ -1,36 +0,0 @@ ---- -- name: Install Clickhouse - hosts: clickhouse - handlers: - - name: Start clickhouse service - become: true - ansible.builtin.service: - name: clickhouse-server - state: restarted - tasks: - - block: - - name: Get clickhouse distrib - ansible.builtin.get_url: - url: "https://packages.clickhouse.com/rpm/stable/{{ item }}-{{ clickhouse_version }}.noarch.rpm" - dest: "./{{ item }}-{{ clickhouse_version }}.rpm" - with_items: "{{ clickhouse_packages }}" - rescue: - - name: Get clickhouse distrib - ansible.builtin.get_url: - url: "https://packages.clickhouse.com/rpm/stable/clickhouse-common-static-{{ clickhouse_version }}.x86_64.rpm" - dest: "./clickhouse-common-static-{{ clickhouse_version }}.rpm" - - name: Install clickhouse packages - become: true - ansible.builtin.yum: - name: - - clickhouse-common-static-{{ clickhouse_version }}.rpm - - clickhouse-client-{{ clickhouse_version }}.rpm - - clickhouse-server-{{ clickhouse_version }}.rpm - notify: Start clickhouse service - - name: Flush handlers - meta: flush_handlers - - name: Create database - ansible.builtin.command: "clickhouse-client -q 'create database logs;'" - register: create_db - failed_when: create_db.rc != 0 and create_db.rc !=82 - changed_when: create_db.rc == 0 diff --git a/08-ansible-03-yandex/README.md b/08-ansible-03-yandex/README.md deleted file mode 100644 index f0ffd7b4d..000000000 --- a/08-ansible-03-yandex/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# Домашнее задание к занятию 3 «Использование Ansible» - -## Подготовка к выполнению - -1. Подготовьте в Yandex Cloud три хоста: для `clickhouse`, для `vector` и для `lighthouse`. -2. Репозиторий LightHouse находится [по ссылке](https://github.com/VKCOM/lighthouse). - -## Основная часть - -1. Допишите playbook: нужно сделать ещё один play, который устанавливает и настраивает LightHouse. -2. При создании tasks рекомендую использовать модули: `get_url`, `template`, `yum`, `apt`. -3. Tasks должны: скачать статику LightHouse, установить Nginx или любой другой веб-сервер, настроить его конфиг для открытия LightHouse, запустить веб-сервер. -4. Подготовьте свой inventory-файл `prod.yml`. -5. Запустите `ansible-lint site.yml` и исправьте ошибки, если они есть. -6. Попробуйте запустить playbook на этом окружении с флагом `--check`. -7. Запустите playbook на `prod.yml` окружении с флагом `--diff`. Убедитесь, что изменения на системе произведены. -8. Повторно запустите playbook с флагом `--diff` и убедитесь, что playbook идемпотентен. -9. Подготовьте README.md-файл по своему playbook. В нём должно быть описано: что делает playbook, какие у него есть параметры и теги. -10. Готовый playbook выложите в свой репозиторий, поставьте тег `08-ansible-03-yandex` на фиксирующий коммит, в ответ предоставьте ссылку на него. - ---- - -### Как оформить решение задания - -Выполненное домашнее задание пришлите в виде ссылки на .md-файл в вашем репозитории. - ---- diff --git a/08-ansible-04-role/README.md b/08-ansible-04-role/README.md deleted file mode 100644 index 21675a09e..000000000 --- a/08-ansible-04-role/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# Домашнее задание к занятию 4 «Работа с roles» - -## Подготовка к выполнению - -1. * Необязательно. Познакомьтесь с [LightHouse](https://youtu.be/ymlrNlaHzIY?t=929). -2. Создайте два пустых публичных репозитория в любом своём проекте: vector-role и lighthouse-role. -3. Добавьте публичную часть своего ключа к своему профилю на GitHub. - -## Основная часть - -Ваша цель — разбить ваш playbook на отдельные roles. - -Задача — сделать roles для ClickHouse, Vector и LightHouse и написать playbook для использования этих ролей. - -Ожидаемый результат — существуют три ваших репозитория: два с roles и один с playbook. - -**Что нужно сделать** - -1. Создайте в старой версии playbook файл `requirements.yml` и заполните его содержимым: - - ```yaml - --- - - src: git@github.com:AlexeySetevoi/ansible-clickhouse.git - scm: git - version: "1.13" - name: clickhouse - ``` - -2. При помощи `ansible-galaxy` скачайте себе эту роль. -3. Создайте новый каталог с ролью при помощи `ansible-galaxy role init vector-role`. -4. На основе tasks из старого playbook заполните новую role. Разнесите переменные между `vars` и `default`. -5. Перенести нужные шаблоны конфигов в `templates`. -6. Опишите в `README.md` обе роли и их параметры. Пример качественной документации ansible role [по ссылке](https://github.com/cloudalchemy/ansible-prometheus). -7. Повторите шаги 3–6 для LightHouse. Помните, что одна роль должна настраивать один продукт. -8. Выложите все roles в репозитории. Проставьте теги, используя семантическую нумерацию. Добавьте roles в `requirements.yml` в playbook. -9. Переработайте playbook на использование roles. Не забудьте про зависимости LightHouse и возможности совмещения `roles` с `tasks`. -10. Выложите playbook в репозиторий. -11. В ответе дайте ссылки на оба репозитория с roles и одну ссылку на репозиторий с playbook. - ---- - -### Как оформить решение задания - -Выполненное домашнее задание пришлите в виде ссылки на .md-файл в вашем репозитории. - ---- diff --git a/08-ansible-05-testing/README.md b/08-ansible-05-testing/README.md deleted file mode 100644 index 46a63be9a..000000000 --- a/08-ansible-05-testing/README.md +++ /dev/null @@ -1,50 +0,0 @@ -# Домашнее задание к занятию 5 «Тестирование roles» - -## Подготовка к выполнению - -1. Установите molecule и его драйвера: `pip3 install "molecule molecule_docker molecule_podman`. -2. Выполните `docker pull aragast/netology:latest` — это образ с podman, tox и несколькими пайтонами (3.7 и 3.9) внутри. - -## Основная часть - -Ваша цель — настроить тестирование ваших ролей. - -Задача — сделать сценарии тестирования для vector. - -Ожидаемый результат — все сценарии успешно проходят тестирование ролей. - -### Molecule - -1. Запустите `molecule test -s ubuntu_xenial` (или с любым другим сценарием, не имеет значения) внутри корневой директории clickhouse-role, посмотрите на вывод команды. Данная команда может отработать с ошибками или не отработать вовсе, это нормально. Наша цель - посмотреть как другие в реальном мире используют молекулу И из чего может состоять сценарий тестирования. -2. Перейдите в каталог с ролью vector-role и создайте сценарий тестирования по умолчанию при помощи `molecule init scenario --driver-name docker`. -3. Добавьте несколько разных дистрибутивов (oraclelinux:8, ubuntu:latest) для инстансов и протестируйте роль, исправьте найденные ошибки, если они есть. -4. Добавьте несколько assert в verify.yml-файл для проверки работоспособности vector-role (проверка, что конфиг валидный, проверка успешности запуска и др.). -5. Запустите тестирование роли повторно и проверьте, что оно прошло успешно. -5. Добавьте новый тег на коммит с рабочим сценарием в соответствии с семантическим версионированием. - -### Tox - -1. Добавьте в директорию с vector-role файлы из [директории](./example). -2. Запустите `docker run --privileged=True -v :/opt/vector-role -w /opt/vector-role -it aragast/netology:latest /bin/bash`, где path_to_repo — путь до корня репозитория с vector-role на вашей файловой системе. -3. Внутри контейнера выполните команду `tox`, посмотрите на вывод. -5. Создайте облегчённый сценарий для `molecule` с драйвером `molecule_podman`. Проверьте его на исполнимость. -6. Пропишите правильную команду в `tox.ini`, чтобы запускался облегчённый сценарий. -8. Запустите команду `tox`. Убедитесь, что всё отработало успешно. -9. Добавьте новый тег на коммит с рабочим сценарием в соответствии с семантическим версионированием. - -После выполнения у вас должно получится два сценария molecule и один tox.ini файл в репозитории. Не забудьте указать в ответе теги решений Tox и Molecule заданий. В качестве решения пришлите ссылку на ваш репозиторий и скриншоты этапов выполнения задания. - -## Необязательная часть - -1. Проделайте схожие манипуляции для создания роли LightHouse. -2. Создайте сценарий внутри любой из своих ролей, который умеет поднимать весь стек при помощи всех ролей. -3. Убедитесь в работоспособности своего стека. Создайте отдельный verify.yml, который будет проверять работоспособность интеграции всех инструментов между ними. -4. Выложите свои roles в репозитории. - -В качестве решения пришлите ссылки и скриншоты этапов выполнения задания. - ---- - -### Как оформить решение задания - -Выполненное домашнее задание пришлите в виде ссылки на .md-файл в вашем репозитории. diff --git a/08-ansible-05-testing/example/tox-requirements.txt b/08-ansible-05-testing/example/tox-requirements.txt deleted file mode 100644 index 60086614e..000000000 --- a/08-ansible-05-testing/example/tox-requirements.txt +++ /dev/null @@ -1,5 +0,0 @@ -selinux -lxml -molecule -molecule_podman -jmespath diff --git a/08-ansible-05-testing/example/tox.ini b/08-ansible-05-testing/example/tox.ini deleted file mode 100644 index 9ab8bb914..000000000 --- a/08-ansible-05-testing/example/tox.ini +++ /dev/null @@ -1,14 +0,0 @@ -[tox] -minversion = 1.8 -basepython = python3.6 -envlist = py{37,39}-ansible{210,30} -skipsdist = true - -[testenv] -passenv = * -deps = - -r tox-requirements.txt - ansible210: ansible<3.0 - ansible30: ansible<3.1 -commands = - {posargs:molecule test -s compatibility --destroy always} \ No newline at end of file diff --git a/08-ansible-06-module/README.md b/08-ansible-06-module/README.md deleted file mode 100644 index 24939f222..000000000 --- a/08-ansible-06-module/README.md +++ /dev/null @@ -1,206 +0,0 @@ -# Домашнее задание к занятию 6 «Создание собственных модулей» - -## Подготовка к выполнению - -1. Создайте пустой публичный репозиторий в своём любом проекте: `my_own_collection`. -2. Скачайте репозиторий Ansible: `git clone https://github.com/ansible/ansible.git` по любому, удобному вам пути. -3. Зайдите в директорию Ansible: `cd ansible`. -4. Создайте виртуальное окружение: `python3 -m venv venv`. -5. Активируйте виртуальное окружение: `. venv/bin/activate`. Дальнейшие действия производятся только в виртуальном окружении. -6. Установите зависимости `pip install -r requirements.txt`. -7. Запустите настройку окружения `. hacking/env-setup`. -8. Если все шаги прошли успешно — выйдите из виртуального окружения `deactivate`. -9. Ваше окружение настроено. Чтобы запустить его, нужно находиться в директории `ansible` и выполнить конструкцию `. venv/bin/activate && . hacking/env-setup`. - -## Основная часть - -Ваша цель — написать собственный module, который вы можете использовать в своей role через playbook. Всё это должно быть собрано в виде collection и отправлено в ваш репозиторий. - -**Шаг 1.** В виртуальном окружении создайте новый `my_own_module.py` файл. - -**Шаг 2.** Наполните его содержимым: - -```python -#!/usr/bin/python - -# Copyright: (c) 2018, Terry Jones -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import (absolute_import, division, print_function) -__metaclass__ = type - -DOCUMENTATION = r''' ---- -module: my_test - -short_description: This is my test module - -# If this is part of a collection, you need to use semantic versioning, -# i.e. the version is of the form "2.5.0" and not "2.4". -version_added: "1.0.0" - -description: This is my longer description explaining my test module. - -options: - name: - description: This is the message to send to the test module. - required: true - type: str - new: - description: - - Control to demo if the result of this module is changed or not. - - Parameter description can be a list as well. - required: false - type: bool -# Specify this value according to your collection -# in format of namespace.collection.doc_fragment_name -extends_documentation_fragment: - - my_namespace.my_collection.my_doc_fragment_name - -author: - - Your Name (@yourGitHubHandle) -''' - -EXAMPLES = r''' -# Pass in a message -- name: Test with a message - my_namespace.my_collection.my_test: - name: hello world - -# pass in a message and have changed true -- name: Test with a message and changed output - my_namespace.my_collection.my_test: - name: hello world - new: true - -# fail the module -- name: Test failure of the module - my_namespace.my_collection.my_test: - name: fail me -''' - -RETURN = r''' -# These are examples of possible return values, and in general should use other names for return values. -original_message: - description: The original name param that was passed in. - type: str - returned: always - sample: 'hello world' -message: - description: The output message that the test module generates. - type: str - returned: always - sample: 'goodbye' -''' - -from ansible.module_utils.basic import AnsibleModule - - -def run_module(): - # define available arguments/parameters a user can pass to the module - module_args = dict( - name=dict(type='str', required=True), - new=dict(type='bool', required=False, default=False) - ) - - # seed the result dict in the object - # we primarily care about changed and state - # changed is if this module effectively modified the target - # state will include any data that you want your module to pass back - # for consumption, for example, in a subsequent task - result = dict( - changed=False, - original_message='', - message='' - ) - - # the AnsibleModule object will be our abstraction working with Ansible - # this includes instantiation, a couple of common attr would be the - # args/params passed to the execution, as well as if the module - # supports check mode - module = AnsibleModule( - argument_spec=module_args, - supports_check_mode=True - ) - - # if the user is working with this module in only check mode we do not - # want to make any changes to the environment, just return the current - # state with no modifications - if module.check_mode: - module.exit_json(**result) - - # manipulate or modify the state as needed (this is going to be the - # part where your module will do what it needs to do) - result['original_message'] = module.params['name'] - result['message'] = 'goodbye' - - # use whatever logic you need to determine whether or not this module - # made any modifications to your target - if module.params['new']: - result['changed'] = True - - # during the execution of the module, if there is an exception or a - # conditional state that effectively causes a failure, run - # AnsibleModule.fail_json() to pass in the message and the result - if module.params['name'] == 'fail me': - module.fail_json(msg='You requested this to fail', **result) - - # in the event of a successful module execution, you will want to - # simple AnsibleModule.exit_json(), passing the key/value results - module.exit_json(**result) - - -def main(): - run_module() - - -if __name__ == '__main__': - main() -``` -Или возьмите это наполнение [из статьи](https://docs.ansible.com/ansible/latest/dev_guide/developing_modules_general.html#creating-a-module). - -**Шаг 3.** Заполните файл в соответствии с требованиями Ansible так, чтобы он выполнял основную задачу: module должен создавать текстовый файл на удалённом хосте по пути, определённом в параметре `path`, с содержимым, определённым в параметре `content`. - -**Шаг 4.** Проверьте module на исполняемость локально. - -**Шаг 5.** Напишите single task playbook и используйте module в нём. - -**Шаг 6.** Проверьте через playbook на идемпотентность. - -**Шаг 7.** Выйдите из виртуального окружения. - -**Шаг 8.** Инициализируйте новую collection: `ansible-galaxy collection init my_own_namespace.yandex_cloud_elk`. - -**Шаг 9.** В эту collection перенесите свой module в соответствующую директорию. - -**Шаг 10.** Single task playbook преобразуйте в single task role и перенесите в collection. У role должны быть default всех параметров module. - -**Шаг 11.** Создайте playbook для использования этой role. - -**Шаг 12.** Заполните всю документацию по collection, выложите в свой репозиторий, поставьте тег `1.0.0` на этот коммит. - -**Шаг 13.** Создайте .tar.gz этой collection: `ansible-galaxy collection build` в корневой директории collection. - -**Шаг 14.** Создайте ещё одну директорию любого наименования, перенесите туда single task playbook и архив c collection. - -**Шаг 15.** Установите collection из локального архива: `ansible-galaxy collection install .tar.gz`. - -**Шаг 16.** Запустите playbook, убедитесь, что он работает. - -**Шаг 17.** В ответ необходимо прислать ссылки на collection и tar.gz архив, а также скриншоты выполнения пунктов 4, 6, 15 и 16. - -## Необязательная часть - -1. Реализуйте свой модуль для создания хостов в Yandex Cloud. -2. Модуль может и должен иметь зависимость от `yc`, основной функционал: создание ВМ с нужным сайзингом на основе нужной ОС. Дополнительные модули по созданию кластеров ClickHouse, MySQL и прочего реализовывать не надо, достаточно простейшего создания ВМ. -3. Модуль может формировать динамическое inventory, но эта часть не является обязательной, достаточно, чтобы он делал хосты с указанной спецификацией в YAML. -4. Протестируйте модуль на идемпотентность, исполнимость. При успехе добавьте этот модуль в свою коллекцию. -5. Измените playbook так, чтобы он умел создавать инфраструктуру под inventory, а после устанавливал весь ваш стек Observability на нужные хосты и настраивал его. -6. В итоге ваша коллекция обязательно должна содержать: clickhouse-role (если есть своя), lighthouse-role, vector-role, два модуля: my_own_module и модуль управления Yandex Cloud хостами и playbook, который демонстрирует создание Observability стека. - ---- - -### Как оформить решение задания - -Выполненное домашнее задание пришлите в виде ссылки на .md-файл в вашем репозитории. - ---- diff --git a/08-ansible-additional/README.md b/08-ansible-additional/README.md deleted file mode 100644 index c301958d1..000000000 --- a/08-ansible-additional/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# Дополнительные материалы к лекциям по Ansible - -1. [Как работать с Windows](http://onreader.mdl.ru/MasteringAnsible.3ed/content/Ch03.html). -2. [Скачать Elasticsearch](https://www.elastic.co/downloads/elasticsearch). -3. [Скачать Kibana](https://www.elastic.co/downloads/kibana). -4. [Скачать Filebeat](https://www.elastic.co/downloads/beats/filebeat). -5. [Все виды beat](https://www.elastic.co/downloads/beats/). -6. [Что такое ansible?](https://youtu.be/oCmkKrLJE_4) -7. [Что такое playbook?](https://youtu.be/170tFeEgT94) -8. [Как написать playbook?](https://www.youtube.com/watch?v=tL76CB1bnPE) diff --git a/09-ci-01-intro/README.md b/09-ci-01-intro/README.md deleted file mode 100644 index 840dacf84..000000000 --- a/09-ci-01-intro/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# Домашнее задание к занятию 7 «Жизненный цикл ПО» - -## Подготовка к выполнению - -1. Получить бесплатную версию Jira - https://www.atlassian.com/ru/software/jira/work-management/free (скопируйте ссылку в адресную строку). Вы можете воспользоваться любым(в том числе бесплатным vpn сервисом) если сайт у вас недоступен. Кроме того вы можете скачать [docker образ](https://hub.docker.com/r/atlassian/jira-software/#) и запустить на своем хосте self-managed версию jira. -2. Настроить её для своей команды разработки. -3. Создать доски Kanban и Scrum. -4. [Дополнительные инструкции от разработчика Jira](https://support.atlassian.com/jira-cloud-administration/docs/import-and-export-issue-workflows/). - -## Основная часть - -Необходимо создать собственные workflow для двух типов задач: bug и остальные типы задач. Задачи типа bug должны проходить жизненный цикл: - -1. Open -> On reproduce. -2. On reproduce -> Open, Done reproduce. -3. Done reproduce -> On fix. -4. On fix -> On reproduce, Done fix. -5. Done fix -> On test. -6. On test -> On fix, Done. -7. Done -> Closed, Open. - -Остальные задачи должны проходить по упрощённому workflow: - -1. Open -> On develop. -2. On develop -> Open, Done develop. -3. Done develop -> On test. -4. On test -> On develop, Done. -5. Done -> Closed, Open. - -**Что нужно сделать** - -1. Создайте задачу с типом bug, попытайтесь провести его по всему workflow до Done. -1. Создайте задачу с типом epic, к ней привяжите несколько задач с типом task, проведите их по всему workflow до Done. -1. При проведении обеих задач по статусам используйте kanban. -1. Верните задачи в статус Open. -1. Перейдите в Scrum, запланируйте новый спринт, состоящий из задач эпика и одного бага, стартуйте спринт, проведите задачи до состояния Closed. Закройте спринт. -2. Если всё отработалось в рамках ожидания — выгрузите схемы workflow для импорта в XML. Файлы с workflow и скриншоты workflow приложите к решению задания. - ---- - -### Как оформить решение задания - -Выполненное домашнее задание пришлите в виде ссылки на .md-файл в вашем репозитории. - ---- diff --git a/09-ci-02-devops/README.md b/09-ci-02-devops/README.md deleted file mode 100644 index 984fbec4d..000000000 --- a/09-ci-02-devops/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# Домашнее задание к занятию 8 «DevOps и SRE» - -Домашнее задание находится у вас в личном кабинете в виде теста. - diff --git a/09-ci-03-cicd/README.md b/09-ci-03-cicd/README.md deleted file mode 100644 index 23046d272..000000000 --- a/09-ci-03-cicd/README.md +++ /dev/null @@ -1,67 +0,0 @@ -# Домашнее задание к занятию 9 «Процессы CI/CD» - -## Подготовка к выполнению - -1. Создайте два VM в Yandex Cloud с параметрами: 2CPU 4RAM Centos7 (остальное по минимальным требованиям). -2. Пропишите в [inventory](./infrastructure/inventory/cicd/hosts.yml) [playbook](./infrastructure/site.yml) созданные хосты. -3. Добавьте в [files](./infrastructure/files/) файл со своим публичным ключом (id_rsa.pub). Если ключ называется иначе — найдите таску в плейбуке, которая использует id_rsa.pub имя, и исправьте на своё. -4. Запустите playbook, ожидайте успешного завершения. -5. Проверьте готовность SonarQube через [браузер](http://localhost:9000). -6. Зайдите под admin\admin, поменяйте пароль на свой. -7. Проверьте готовность Nexus через [бразуер](http://localhost:8081). -8. Подключитесь под admin\admin123, поменяйте пароль, сохраните анонимный доступ. - -## Знакомоство с SonarQube - -### Основная часть - -1. Создайте новый проект, название произвольное. -2. Скачайте пакет sonar-scanner, который вам предлагает скачать SonarQube. -3. Сделайте так, чтобы binary был доступен через вызов в shell (или поменяйте переменную PATH, или любой другой, удобный вам способ). -4. Проверьте `sonar-scanner --version`. -5. Запустите анализатор против кода из директории [example](./example) с дополнительным ключом `-Dsonar.coverage.exclusions=fail.py`. -6. Посмотрите результат в интерфейсе. -7. Исправьте ошибки, которые он выявил, включая warnings. -8. Запустите анализатор повторно — проверьте, что QG пройдены успешно. -9. Сделайте скриншот успешного прохождения анализа, приложите к решению ДЗ. - -## Знакомство с Nexus - -### Основная часть - -1. В репозиторий `maven-public` загрузите артефакт с GAV-параметрами: - - * groupId: netology; - * artifactId: java; - * version: 8_282; - * classifier: distrib; - * type: tar.gz. - -2. В него же загрузите такой же артефакт, но с version: 8_102. -3. Проверьте, что все файлы загрузились успешно. -4. В ответе пришлите файл `maven-metadata.xml` для этого артефекта. - -### Знакомство с Maven - -### Подготовка к выполнению - -1. Скачайте дистрибутив с [maven](https://maven.apache.org/download.cgi). -2. Разархивируйте, сделайте так, чтобы binary был доступен через вызов в shell (или поменяйте переменную PATH, или любой другой, удобный вам способ). -3. Удалите из `apache-maven-/conf/settings.xml` упоминание о правиле, отвергающем HTTP- соединение — раздел mirrors —> id: my-repository-http-unblocker. -4. Проверьте `mvn --version`. -5. Заберите директорию [mvn](./mvn) с pom. - -### Основная часть - -1. Поменяйте в `pom.xml` блок с зависимостями под ваш артефакт из первого пункта задания для Nexus (java с версией 8_282). -2. Запустите команду `mvn package` в директории с `pom.xml`, ожидайте успешного окончания. -3. Проверьте директорию `~/.m2/repository/`, найдите ваш артефакт. -4. В ответе пришлите исправленный файл `pom.xml`. - ---- - -### Как оформить решение задания - -Выполненное домашнее задание пришлите в виде ссылки на .md-файл в вашем репозитории. - ---- diff --git a/09-ci-03-cicd/example/fail.py b/09-ci-03-cicd/example/fail.py deleted file mode 100644 index e49bbef02..000000000 --- a/09-ci-03-cicd/example/fail.py +++ /dev/null @@ -1,13 +0,0 @@ -def increment(index): - index =+ 1 - return index -def get_square(numb): - return numb*numb -def print_numb(numb): - print("Number is {}".format(numb)) - pass - -index = 0 -while (index < 10): - index = increment(index) - print(get_square(index)) \ No newline at end of file diff --git a/09-ci-03-cicd/infrastructure/.gitignore b/09-ci-03-cicd/infrastructure/.gitignore deleted file mode 100644 index 483815e4c..000000000 --- a/09-ci-03-cicd/infrastructure/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -files/*.pub -roles/* \ No newline at end of file diff --git a/09-ci-03-cicd/infrastructure/files/CentOS-Base.repo b/09-ci-03-cicd/infrastructure/files/CentOS-Base.repo deleted file mode 100644 index 0984327f0..000000000 --- a/09-ci-03-cicd/infrastructure/files/CentOS-Base.repo +++ /dev/null @@ -1,48 +0,0 @@ -# CentOS-Base.repo -# -# The mirror system uses the connecting IP address of the client and the -# update status of each mirror to pick mirrors that are updated to and -# geographically close to the client. You should use this for CentOS updates -# unless you are manually picking other mirrors. -# -# If the mirrorlist= does not work for you, as a fall back you can try the -# remarked out baseurl= line instead. -# -# - -[base] -name=CentOS-$releasever - Base -mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra -#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/ -gpgcheck=1 -gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 - -exclude=postgresql* - -#released updates -[updates] -name=CentOS-$releasever - Updates -mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates&infra=$infra -#baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/ -gpgcheck=1 -gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 - -exclude=postgresql* - -#additional packages that may be useful -[extras] -name=CentOS-$releasever - Extras -mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras&infra=$infra -#baseurl=http://mirror.centos.org/centos/$releasever/extras/$basearch/ -gpgcheck=1 -gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 - -#additional packages that extend functionality of existing packages -[centosplus] -name=CentOS-$releasever - Plus -mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus&infra=$infra -#baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/ -gpgcheck=1 -enabled=0 -gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 - diff --git a/09-ci-03-cicd/infrastructure/files/pg_hba.conf b/09-ci-03-cicd/infrastructure/files/pg_hba.conf deleted file mode 100644 index b5c361a7b..000000000 --- a/09-ci-03-cicd/infrastructure/files/pg_hba.conf +++ /dev/null @@ -1,89 +0,0 @@ -# PostgreSQL Client Authentication Configuration File -# =================================================== -# -# Refer to the "Client Authentication" section in the PostgreSQL -# documentation for a complete description of this file. A short -# synopsis follows. -# -# This file controls: which hosts are allowed to connect, how clients -# are authenticated, which PostgreSQL user names they can use, which -# databases they can access. Records take one of these forms: -# -# local DATABASE USER METHOD [OPTIONS] -# host DATABASE USER ADDRESS METHOD [OPTIONS] -# hostssl DATABASE USER ADDRESS METHOD [OPTIONS] -# hostnossl DATABASE USER ADDRESS METHOD [OPTIONS] -# -# (The uppercase items must be replaced by actual values.) -# -# The first field is the connection type: "local" is a Unix-domain -# socket, "host" is either a plain or SSL-encrypted TCP/IP socket, -# "hostssl" is an SSL-encrypted TCP/IP socket, and "hostnossl" is a -# plain TCP/IP socket. -# -# DATABASE can be "all", "sameuser", "samerole", "replication", a -# database name, or a comma-separated list thereof. The "all" -# keyword does not match "replication". Access to replication -# must be enabled in a separate record (see example below). -# -# USER can be "all", a user name, a group name prefixed with "+", or a -# comma-separated list thereof. In both the DATABASE and USER fields -# you can also write a file name prefixed with "@" to include names -# from a separate file. -# -# ADDRESS specifies the set of hosts the record matches. It can be a -# host name, or it is made up of an IP address and a CIDR mask that is -# an integer (between 0 and 32 (IPv4) or 128 (IPv6) inclusive) that -# specifies the number of significant bits in the mask. A host name -# that starts with a dot (.) matches a suffix of the actual host name. -# Alternatively, you can write an IP address and netmask in separate -# columns to specify the set of hosts. Instead of a CIDR-address, you -# can write "samehost" to match any of the server's own IP addresses, -# or "samenet" to match any address in any subnet that the server is -# directly connected to. -# -# METHOD can be "trust", "reject", "md5", "password", "scram-sha-256", -# "gss", "sspi", "ident", "peer", "pam", "ldap", "radius" or "cert". -# Note that "password" sends passwords in clear text; "md5" or -# "scram-sha-256" are preferred since they send encrypted passwords. -# -# OPTIONS are a set of options for the authentication in the format -# NAME=VALUE. The available options depend on the different -# authentication methods -- refer to the "Client Authentication" -# section in the documentation for a list of which options are -# available for which authentication methods. -# -# Database and user names containing spaces, commas, quotes and other -# special characters must be quoted. Quoting one of the keywords -# "all", "sameuser", "samerole" or "replication" makes the name lose -# its special character, and just match a database or username with -# that name. -# -# This file is read on server startup and when the server receives a -# SIGHUP signal. If you edit the file on a running system, you have to -# SIGHUP the server for the changes to take effect, run "pg_ctl reload", -# or execute "SELECT pg_reload_conf()". -# -# Put your actual configuration here -# ---------------------------------- -# -# If you want to allow non-local connections, you need to add more -# "host" records. In that case you will also need to make PostgreSQL -# listen on a non-local interface via the listen_addresses -# configuration parameter, or via the -i or -h command line switches. - - - -# TYPE DATABASE USER ADDRESS METHOD - -# "local" is for Unix domain socket connections only -local all all trust -# IPv4 local connections: -host all all 127.0.0.1/32 md5 -# IPv6 local connections: -host all all ::1/128 md5 -# Allow replication connections from localhost, by a user with the -# replication privilege. -local replication all trust -host replication all 127.0.0.1/32 md5 -host replication all ::1/128 md5 diff --git a/09-ci-03-cicd/infrastructure/inventory/cicd/group_vars/all.yml b/09-ci-03-cicd/infrastructure/inventory/cicd/group_vars/all.yml deleted file mode 100644 index f6afeefb1..000000000 --- a/09-ci-03-cicd/infrastructure/inventory/cicd/group_vars/all.yml +++ /dev/null @@ -1,8 +0,0 @@ ---- -jdk_url: https://download.java.net/openjdk/jdk11/ri/openjdk-11+28_linux-x64_bin.tar.gz -jdk_distr_name: openjdk-11+28_linux-x64_bin.tar.gz -jdk_folder: "{{ jdk_distr_name.split('-')[:2] | join('-') }}" -java_home: "/opt/jdk/{{ jdk_folder }}" -sonarqube_db_name: sonar -sonarqube_db_user: sonar -sonarqube_db_password: sonar \ No newline at end of file diff --git a/09-ci-03-cicd/infrastructure/inventory/cicd/group_vars/nexus.yml b/09-ci-03-cicd/infrastructure/inventory/cicd/group_vars/nexus.yml deleted file mode 100644 index b84eba748..000000000 --- a/09-ci-03-cicd/infrastructure/inventory/cicd/group_vars/nexus.yml +++ /dev/null @@ -1,22 +0,0 @@ ---- -nexus_user_group: nexus -nexus_user_name: nexus -nexus_directory_data: "/home/{{ nexus_user_name }}/sonatype-work/nexus3" -nexus_directory_home: "/home/{{ nexus_user_name }}/nexus" -nexus_directory_log: "/home/{{ nexus_user_name }}/log" -nexus_directory_package: "/home/{{ nexus_user_name }}/pkg" -nexus_directory_tmp: "/home/{{ nexus_user_name }}/tmp" -nexus_version: 3.14.0-04 -nexus_download_url: https://download.sonatype.com/nexus/3 -nexus_service_enabled: true -nexus_ulimit: 65536 -nexus_context_path: / -nexus_host: 0.0.0.0 -nexus_port: 8081 -nexus_port_check_timeout: 600 -nexus_edition: nexus-oss-edition -nexus_features: nexus-oss-feature -nexus_java_heap_size: 1200M -nexus_java_max_direct_memory: 2G -nexus_service_start_on_boot: true -nexus_configuration_disk_free_space_limit: ~ \ No newline at end of file diff --git a/09-ci-03-cicd/infrastructure/inventory/cicd/group_vars/postgres.yml b/09-ci-03-cicd/infrastructure/inventory/cicd/group_vars/postgres.yml deleted file mode 100644 index e0499e7e9..000000000 --- a/09-ci-03-cicd/infrastructure/inventory/cicd/group_vars/postgres.yml +++ /dev/null @@ -1 +0,0 @@ -postgresql_version: 11 \ No newline at end of file diff --git a/09-ci-03-cicd/infrastructure/inventory/cicd/group_vars/sonarqube.yml b/09-ci-03-cicd/infrastructure/inventory/cicd/group_vars/sonarqube.yml deleted file mode 100644 index 89b9116c4..000000000 --- a/09-ci-03-cicd/infrastructure/inventory/cicd/group_vars/sonarqube.yml +++ /dev/null @@ -1,5 +0,0 @@ -sonar_version: 9.1.0.47736 -sonar_download_url: "https://binaries.sonarsource.com/Distribution/sonarqube/sonarqube-{{ sonar_version }}.zip" -sonar_version_directory: "sonarqube-{{ sonar_version }}" -sonar_db_port: "5432" -sonar_web_context: '' \ No newline at end of file diff --git a/09-ci-03-cicd/infrastructure/inventory/cicd/hosts.yml b/09-ci-03-cicd/infrastructure/inventory/cicd/hosts.yml deleted file mode 100644 index ef7633b5a..000000000 --- a/09-ci-03-cicd/infrastructure/inventory/cicd/hosts.yml +++ /dev/null @@ -1,20 +0,0 @@ ---- -all: - hosts: - sonar-01: - ansible_host: - nexus-01: - ansible_host: - children: - sonarqube: - hosts: - sonar-01: - nexus: - hosts: - nexus-01: - postgres: - hosts: - sonar-01: - vars: - ansible_connection_type: paramiko - ansible_user: \ No newline at end of file diff --git a/09-ci-03-cicd/infrastructure/site.yml b/09-ci-03-cicd/infrastructure/site.yml deleted file mode 100644 index 49d31b3bb..000000000 --- a/09-ci-03-cicd/infrastructure/site.yml +++ /dev/null @@ -1,382 +0,0 @@ ---- -- name: Get OpenJDK installed - hosts: sonarqube - pre_tasks: - - name: install unzip - become: true - yum: - name: unzip - state: present - tasks: - - name: Upload .tar.gz file conaining binaries from remote storage - get_url: - url: "{{ jdk_url }}" - dest: "/tmp/jdk-{{ jdk_distr_name }}" - mode: 0755 - register: download_java_remote_binaries - until: download_java_remote_binaries is succeeded - - - name: Ensure installation dir exists - become: true - file: - state: directory - path: "{{ java_home }}" - mode: 0755 - - - name: Extract java in the installation directory - become: true - unarchive: - copy: false - src: "/tmp/jdk-{{ jdk_distr_name }}" - dest: "{{ java_home }}" - extra_opts: [--strip-components=1] - creates: "{{ java_home }}/bin/java" - - - name: Export environment variables - become: true - template: - src: jdk.sh.j2 - dest: /etc/profile.d/jdk.sh - owner: root - group: root - mode: 0644 - -- name: Get PostgreSQL installed - hosts: postgres - become: true - tasks: - - name: Change repo file - copy: - src: CentOS-Base.repo - dest: /etc/yum.repos.d/CentOS-Base.repo - mode: 0644 - owner: root - group: root - - - name: Install PostgreSQL repos - yum: - name: https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm - state: present - validate_certs: false - - - name: Install PostgreSQL - yum: - name: "postgresql{{ postgresql_version }}-server" - state: present - - - name: Init template1 DB - command: /usr/pgsql-11/bin/postgresql-11-setup initdb - failed_when: false - - - name: Start pgsql service - systemd: - name: "postgresql-{{ postgresql_version }}" - state: started - enabled: true - - - name: Create user in system - user: - name: "{{ sonarqube_db_user }}" - - name: Create user for Sonar in PostgreSQL - become_user: postgres - command: "createuser -s -e {{ sonarqube_db_user }}" - failed_when: false - - - name: Change password for Sonar user in PostgreSQL - become_user: postgres - command: "psql -c \"ALTER USER sonar WITH ENCRYPTED password '{{ sonarqube_db_password }}';\"" - - - name: Create Sonar DB - become_user: postgres - command: "createdb {{ sonarqube_db_name }}" - failed_when: false - - - name: Copy pg_hba.conf - copy: - src: pg_hba.conf - dest: /var/lib/pgsql/11/data/pg_hba.conf - mode: 0600 - owner: postgres - group: postgres - -- name: Prepare Sonar host - hosts: sonarqube - become: true - tasks: - - name: Create group in system - group: - name: "{{ sonarqube_db_user }}" - state: present - - - name: Create user in system - user: - name: "{{ sonarqube_db_user }}" - group: "{{ sonarqube_db_user }}" - - - name: "Set up ssh key to access for managed node" - authorized_key: - user: "{{ sonarqube_db_user }}" - state: present - key: "{{ lookup('file', 'id_rsa.pub') }}" - - - name: "Allow group to have passwordless sudo" - lineinfile: - dest: /etc/sudoers - state: present - regexp: '^%{{ sonarqube_db_user }}' - line: '%{{ sonarqube_db_user }} ALL=(ALL) NOPASSWD: ALL' - validate: 'visudo -cf %s' - - - name: Increase Virtual Memory - lineinfile: - dest: /etc/sysctl.conf - state: present - regexp: '^vm.max_map_count' - line: 'vm.max_map_count=262144' - - name: Reboot VM - reboot: - -- name: Get Sonarqube installed - hosts: sonarqube - vars: - ansible_user: "{{ sonarqube_db_user }}" - tasks: - - name: Get distrib ZIP - get_url: - url: "{{ sonar_download_url }}" - dest: "/tmp/{{ sonar_version_directory }}.zip" - validate_certs: false - - - name: Unzip Sonar - become: true - unarchive: - src: "/tmp/{{ sonar_version_directory }}.zip" - dest: /usr/local/ - copy: false - owner: "{{ sonarqube_db_user }}" - group: "{{ sonarqube_db_user }}" - creates: /usr/local/sonar/COPYING - - - name: Move Sonar into place. - become: true - copy: - src: /usr/local/{{ sonar_version_directory }}/ - dest: /usr/local/sonar/ - owner: "{{ sonarqube_db_user }}" - group: "{{ sonarqube_db_user }}" - remote_src: true - - - name: Configure SonarQube JDBC settings for PostgreSQL. - lineinfile: - dest: /usr/local/sonar/conf/sonar.properties - regexp: "{{ item.regexp }}" - line: "{{ item.line }}" - with_items: - - regexp: "^sonar.jdbc.username" - line: "sonar.jdbc.username={{ sonarqube_db_user }}" - - regexp: "^sonar.jdbc.password" - line: "sonar.jdbc.password={{ sonarqube_db_password }}" - - regexp: "^sonar.jdbc.url" - line: "sonar.jdbc.url=jdbc:postgresql://localhost:{{ sonar_db_port }}/{{ sonarqube_db_name }}?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance" - - regexp: "^sonar.web.context" - line: "sonar.web.context={{ sonar_web_context }}" - - - name: Generate wrapper.conf - template: - src: wrapper.conf.j2 - dest: /usr/local/sonar/conf/wrapper.conf - mode: 0644 - - - name: Symlink sonar bin. - become: true - file: - src: /usr/local/sonar/bin/linux-x86-64/sonar.sh - dest: /usr/bin/sonar - state: link - register: sonar_symlink - - - name: Copy SonarQube systemd unit file into place (for systemd systems). - become: true - template: - src: sonar.unit.j2 - dest: /etc/systemd/system/sonar.service - owner: root - group: root - mode: 0755 - - - name: Ensure Sonar is running and set to start on boot. - become: true - service: - name: sonar - state: restarted - enabled: true - - - name: Allow Sonar time to build on first start. - pause: - seconds: 180 - when: sonar_symlink.changed - tags: ['skip_ansible_lint'] - - - name: Make sure Sonar is responding on the configured port. - wait_for: - port: 9000 - delay: 3 - timeout: 300 -- name: Get Nexus installed - hosts: nexus - pre_tasks: - - name: Create Nexus group - become: true - group: - name: "{{ nexus_user_group }}" - state: present - - name: Create Nexus user - become: true - user: - name: "{{ nexus_user_name }}" - - name: Install JDK - become: true - package: - name: [java-1.8.0-openjdk, java-1.8.0-openjdk-devel] - state: present - tasks: - - name: Create Nexus directories - become: true - file: - group: "{{ nexus_user_group }}" - owner: "{{ nexus_user_name }}" - path: "{{ item }}" - state: directory - with_items: - - "{{ nexus_directory_log }}" - - "{{ nexus_directory_data }}" - - "{{ nexus_directory_data }}/etc" - - "{{ nexus_directory_package }}" - - "{{ nexus_directory_tmp }}" - - - name: Download Nexus - become: true - become_user: "{{ nexus_user_name }}" - get_url: - dest: "{{ nexus_directory_package }}/nexus-{{ nexus_version }}.tar.gz" - url: "{{ nexus_download_url }}/nexus-{{ nexus_version }}-unix.tar.gz" - validate_certs: false - - - name: Unpack Nexus - become: true - become_user: "{{ nexus_user_name }}" - unarchive: - copy: no - creates: "{{ nexus_directory_package }}/nexus-{{ nexus_version }}" - dest: "{{ nexus_directory_package }}" - src: "{{ nexus_directory_package }}/nexus-{{ nexus_version }}.tar.gz" - - - name: Link to Nexus Directory - become: true - become_user: "{{ nexus_user_name }}" - file: - dest: "{{ nexus_directory_home }}" - src: "{{ nexus_directory_package }}/nexus-{{ nexus_version }}" - state: link - - - name: Add NEXUS_HOME for Nexus user - become: true - become_user: "{{ nexus_user_name }}" - lineinfile: - create: yes - dest: "/home/{{ nexus_user_name }}/.bashrc" - insertafter: EOF - line: "export NEXUS_HOME={{ nexus_directory_home }}" - - - name: Add run_as_user to Nexus.rc - become: true - become_user: "{{ nexus_user_name }}" - lineinfile: - create: yes - dest: "{{ nexus_directory_home }}/bin/nexus.rc" - insertafter: EOF - line: "run_as_user=\"{{ nexus_user_name }}\"" - regexp: "^run_as_user" - - - name: Raise nofile limit for Nexus user - become: true - pam_limits: - domain: "{{ nexus_user_name }}" - limit_type: "-" - limit_item: nofile - value: "{{ nexus_ulimit }}" - - - name: Create Nexus service for SystemD - become: true - template: - dest: /lib/systemd/system/nexus.service - mode: 0644 - src: nexus.systemd.j2 - - - name: Ensure Nexus service is enabled for SystemD - become: true - systemd: - daemon_reload: yes - enabled: yes - name: nexus - when: - - nexus_service_enabled - - - name: Create Nexus vmoptions - become: true - become_user: "{{ nexus_user_name }}" - template: - dest: "{{ nexus_directory_home }}/bin/nexus.vmoptions" - src: nexus.vmoptions.j2 - register: nexus_config_changed - - - name: Create Nexus properties - become: true - become_user: "{{ nexus_user_name }}" - template: - dest: "{{ nexus_directory_data }}/etc/nexus.properties" - src: nexus.properties.j2 - register: nexus_config_changed - - - name: Lower Nexus disk space threshold - become: true - become_user: "{{ nexus_user_name }}" - lineinfile: - backrefs: yes - dest: "{{ nexus_directory_home }}/etc/karaf/system.properties" - insertafter: EOF - line: "storage.diskCache.diskFreeSpaceLimit={{ nexus_configuration_disk_free_space_limit }}" - regexp: ^storage\.diskCache\.diskFreeSpaceLimit - when: nexus_configuration_disk_free_space_limit is not none - register: nexus_config_changed - - - name: Start Nexus service if enabled - become: true - service: - enabled: yes - name: nexus - state: started - when: - - nexus_service_start_on_boot - - not nexus_config_changed.changed - tags: - - skip_ansible_lint - - - name: Ensure Nexus service is restarted - become: true - service: - name: nexus - state: restarted - when: - - nexus_service_start_on_boot - - nexus_config_changed.changed - tags: - - skip_ansible_lint - - - name: Wait for Nexus port if started - wait_for: - port: "{{ nexus_port }}" - state: started - timeout: "{{ nexus_port_check_timeout }}" - when: - - nexus_service_start_on_boot diff --git a/09-ci-03-cicd/infrastructure/templates/jdk.sh.j2 b/09-ci-03-cicd/infrastructure/templates/jdk.sh.j2 deleted file mode 100644 index 39887b6ab..000000000 --- a/09-ci-03-cicd/infrastructure/templates/jdk.sh.j2 +++ /dev/null @@ -1,5 +0,0 @@ -# Warning: This file is Ansible Managed, manual changes will be overwritten on next playbook run. -#!/usr/bin/env bash - -export JAVA_HOME={{ java_home }} -export PATH=$PATH:$JAVA_HOME/bin \ No newline at end of file diff --git a/09-ci-03-cicd/infrastructure/templates/nexus.properties.j2 b/09-ci-03-cicd/infrastructure/templates/nexus.properties.j2 deleted file mode 100644 index aa2645463..000000000 --- a/09-ci-03-cicd/infrastructure/templates/nexus.properties.j2 +++ /dev/null @@ -1,12 +0,0 @@ -# -# - -# Jetty section -application-host={{ nexus_host }} -application-port={{ nexus_port }} -nexus-context-path={{ nexus_context_path }} - -# Nexus section -nexus-edition={{ nexus_edition }} -nexus-features=\ - {{ nexus_features }} \ No newline at end of file diff --git a/09-ci-03-cicd/infrastructure/templates/nexus.systemd.j2 b/09-ci-03-cicd/infrastructure/templates/nexus.systemd.j2 deleted file mode 100644 index 7665d96a8..000000000 --- a/09-ci-03-cicd/infrastructure/templates/nexus.systemd.j2 +++ /dev/null @@ -1,15 +0,0 @@ -[Unit] -Description=nexus service -After=network.target - -[Service] -Type=forking -User={{ nexus_user_name }} -Group={{ nexus_user_group }} -LimitNOFILE={{ nexus_ulimit }} -ExecStart={{ nexus_directory_home }}/bin/nexus start -ExecStop={{ nexus_directory_home }}/bin/nexus stop -Restart=on-abort - -[Install] -WantedBy=multi-user.target \ No newline at end of file diff --git a/09-ci-03-cicd/infrastructure/templates/nexus.vmoptions.j2 b/09-ci-03-cicd/infrastructure/templates/nexus.vmoptions.j2 deleted file mode 100644 index dea2288a7..000000000 --- a/09-ci-03-cicd/infrastructure/templates/nexus.vmoptions.j2 +++ /dev/null @@ -1,16 +0,0 @@ --Xms{{ nexus_java_heap_size }} --Xmx{{ nexus_java_heap_size }} --XX:MaxDirectMemorySize={{ nexus_java_max_direct_memory }} --XX:+UnlockDiagnosticVMOptions --XX:+UnsyncloadClass --XX:+LogVMOutput --XX:LogFile={{ nexus_directory_log }}/jvm.log --XX:-OmitStackTraceInFastThrow --Djava.net.preferIPv4Stack=true --Dkaraf.home=. --Dkaraf.base=. --Dkaraf.etc=etc/karaf --Djava.util.logging.config.file=etc/karaf/java.util.logging.properties --Dkaraf.data={{ nexus_directory_data }} --Djava.io.tmpdir={{ nexus_directory_tmp }} --Dkaraf.startLocalConsole=false \ No newline at end of file diff --git a/09-ci-03-cicd/infrastructure/templates/sonar.unit.j2 b/09-ci-03-cicd/infrastructure/templates/sonar.unit.j2 deleted file mode 100644 index fb48c8067..000000000 --- a/09-ci-03-cicd/infrastructure/templates/sonar.unit.j2 +++ /dev/null @@ -1,22 +0,0 @@ -[Unit] -Description=SonarQube -After=network.target network-online.target -Wants=network-online.target - -[Service] -LimitNOFILE=131072 -LimitNPROC=8192 -User={{ sonarqube_db_user }} -Group={{ sonarqube_db_user }} -ExecStart=/usr/bin/sonar start -ExecStop=/usr/bin/sonar stop -ExecReload=/usr/bin/sonar restart -PIDFile=/usr/local/sonar/bin/linux-x86-64/./SonarQube.pid -Type=simple -PermissionsStartOnly=true -TimeoutStartSec=5 -Restart=always -SuccessExitStatus=143 - -[Install] -WantedBy=multi-user.target diff --git a/09-ci-03-cicd/infrastructure/templates/wrapper.conf.j2 b/09-ci-03-cicd/infrastructure/templates/wrapper.conf.j2 deleted file mode 100644 index bb271c188..000000000 --- a/09-ci-03-cicd/infrastructure/templates/wrapper.conf.j2 +++ /dev/null @@ -1,98 +0,0 @@ -# Path to JVM executable. By default it must be available in PATH. -# Can be an absolute path, for example: -wrapper.java.command={{ java_home }}/bin/java - - -# -# DO NOT EDIT THE FOLLOWING SECTIONS -# - - -#******************************************************************** -# Wrapper Java -#******************************************************************** -wrapper.java.additional.1=-Dsonar.wrapped=true -wrapper.java.additional.2=-Djava.awt.headless=true -# extra args needed by hazelcast -wrapper.java.additional.3=--add-exports=java.base/jdk.internal.ref=ALL-UNNAMED -wrapper.java.additional.4=--add-opens=java.base/java.lang=ALL-UNNAMED -wrapper.java.additional.5=--add-opens=java.base/java.nio=ALL-UNNAMED -wrapper.java.additional.6=--add-opens=java.base/sun.nio.ch=ALL-UNNAMED -wrapper.java.additional.7=--add-opens=java.management/sun.management=ALL-UNNAMED -wrapper.java.additional.8=--add-opens=jdk.management/com.sun.management.internal=ALL-UNNAMED - -wrapper.java.mainclass=org.tanukisoftware.wrapper.WrapperSimpleApp -wrapper.java.classpath.1=../../lib/sonar-application-9.1.0.47736.jar -wrapper.java.classpath.2=../../lib/jsw/wrapper-3.2.3.jar -wrapper.java.classpath.3=../../lib/sonar-shutdowner-9.1.0.47736.jar -wrapper.java.library.path.1=./lib -wrapper.app.parameter.1=org.sonar.application.App -wrapper.java.initmemory=8 -wrapper.java.maxmemory=32 - -#******************************************************************** -# Wrapper Logs -#******************************************************************** - -wrapper.console.format=PM -wrapper.console.loglevel=INFO -wrapper.logfile.format=M -wrapper.logfile.loglevel=INFO -wrapper.logfile.rollmode=DATE -wrapper.logfile=../../logs/sonar.YYYYMMDD.log - -# Maximum size that the log file will be allowed to grow to before -# the log is rolled. Size is specified in bytes. The default value -# of 0, disables log rolling. May abbreviate with the 'k' (kb) or -# 'm' (mb) suffix. For example: 10m = 10 megabytes. -#wrapper.logfile.maxsize=0 - -# Maximum number of rolled log files which will be allowed before old -# files are deleted. The default value of 0 implies no limit. -wrapper.logfile.maxfiles=7 - -# Log Level for sys/event log output. (See docs for log levels) -wrapper.syslog.loglevel=NONE - -#******************************************************************** -# Wrapper Windows Properties -#******************************************************************** -# Title to use when running as a console -wrapper.console.title=SonarQube - -# Disallow start of multiple instances of an application at the same time on Windows -wrapper.single_invocation=true - -#******************************************************************** -# Wrapper Windows NT/2000/XP Service Properties -#******************************************************************** -# WARNING - Do not modify any of these properties when an application -# using this configuration file has been installed as a service. -# Please uninstall the service before modifying this section. The -# service can then be reinstalled. - -# Name of the service -wrapper.ntservice.name=SonarQube - -# Display name of the service -wrapper.ntservice.displayname=SonarQube - -# Description of the service -wrapper.ntservice.description=SonarQube - -# Service dependencies. Add dependencies as needed starting from 1 -wrapper.ntservice.dependency.1= - -# Mode in which the service is installed. AUTO_START or DEMAND_START -wrapper.ntservice.starttype=AUTO_START - -# Allow the service to interact with the desktop. -wrapper.ntservice.interactive=false - -#******************************************************************** -# Forking Properties -#******************************************************************** -wrapper.disable_restarts=TRUE -wrapper.ping.timeout=0 -wrapper.shutdown.timeout=0 -wrapper.jvm_exit.timeout=0 diff --git a/09-ci-03-cicd/mvn/pom.xml b/09-ci-03-cicd/mvn/pom.xml deleted file mode 100644 index 7d2812f8b..000000000 --- a/09-ci-03-cicd/mvn/pom.xml +++ /dev/null @@ -1,24 +0,0 @@ - - 4.0.0 - - com.netology.app - simple-app - 1.0-SNAPSHOT - - - my-repo - maven-public - http://localhost:8081/repository/maven-public/ - - - - - - \ No newline at end of file diff --git a/09-ci-04-jenkins/README.md b/09-ci-04-jenkins/README.md deleted file mode 100644 index 3f54f1002..000000000 --- a/09-ci-04-jenkins/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# Домашнее задание к занятию 10 «Jenkins» - -## Подготовка к выполнению - -1. Создать два VM: для jenkins-master и jenkins-agent. -2. Установить Jenkins при помощи playbook. -3. Запустить и проверить работоспособность. -4. Сделать первоначальную настройку. - -## Основная часть - -1. Сделать Freestyle Job, который будет запускать `molecule test` из любого вашего репозитория с ролью. -2. Сделать Declarative Pipeline Job, который будет запускать `molecule test` из любого вашего репозитория с ролью. -3. Перенести Declarative Pipeline в репозиторий в файл `Jenkinsfile`. -4. Создать Multibranch Pipeline на запуск `Jenkinsfile` из репозитория. -5. Создать Scripted Pipeline, наполнить его скриптом из [pipeline](./pipeline). -6. Внести необходимые изменения, чтобы Pipeline запускал `ansible-playbook` без флагов `--check --diff`, если не установлен параметр при запуске джобы (prod_run = True). По умолчанию параметр имеет значение False и запускает прогон с флагами `--check --diff`. -7. Проверить работоспособность, исправить ошибки, исправленный Pipeline вложить в репозиторий в файл `ScriptedJenkinsfile`. -8. Отправить ссылку на репозиторий с ролью и Declarative Pipeline и Scripted Pipeline. -9. Сопроводите процесс настройки скриншотами для каждого пункта задания!! - -## Необязательная часть - -1. Создать скрипт на groovy, который будет собирать все Job, завершившиеся хотя бы раз неуспешно. Добавить скрипт в репозиторий с решением и названием `AllJobFailure.groovy`. -2. Создать Scripted Pipeline так, чтобы он мог сначала запустить через Yandex Cloud CLI необходимое количество инстансов, прописать их в инвентори плейбука и после этого запускать плейбук. Мы должны при нажатии кнопки получить готовую к использованию систему. - ---- - -### Как оформить решение задания - -Выполненное домашнее задание пришлите в виде ссылки на .md-файл в вашем репозитории. - ---- diff --git a/09-ci-04-jenkins/infrastructure/.gitignore b/09-ci-04-jenkins/infrastructure/.gitignore deleted file mode 100644 index 483815e4c..000000000 --- a/09-ci-04-jenkins/infrastructure/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -files/*.pub -roles/* \ No newline at end of file diff --git a/09-ci-04-jenkins/infrastructure/files/CentOS-Base.repo b/09-ci-04-jenkins/infrastructure/files/CentOS-Base.repo deleted file mode 100644 index 0984327f0..000000000 --- a/09-ci-04-jenkins/infrastructure/files/CentOS-Base.repo +++ /dev/null @@ -1,48 +0,0 @@ -# CentOS-Base.repo -# -# The mirror system uses the connecting IP address of the client and the -# update status of each mirror to pick mirrors that are updated to and -# geographically close to the client. You should use this for CentOS updates -# unless you are manually picking other mirrors. -# -# If the mirrorlist= does not work for you, as a fall back you can try the -# remarked out baseurl= line instead. -# -# - -[base] -name=CentOS-$releasever - Base -mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra -#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/ -gpgcheck=1 -gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 - -exclude=postgresql* - -#released updates -[updates] -name=CentOS-$releasever - Updates -mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates&infra=$infra -#baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/ -gpgcheck=1 -gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 - -exclude=postgresql* - -#additional packages that may be useful -[extras] -name=CentOS-$releasever - Extras -mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras&infra=$infra -#baseurl=http://mirror.centos.org/centos/$releasever/extras/$basearch/ -gpgcheck=1 -gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 - -#additional packages that extend functionality of existing packages -[centosplus] -name=CentOS-$releasever - Plus -mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus&infra=$infra -#baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/ -gpgcheck=1 -enabled=0 -gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 - diff --git a/09-ci-04-jenkins/infrastructure/files/pg_hba.conf b/09-ci-04-jenkins/infrastructure/files/pg_hba.conf deleted file mode 100644 index b5c361a7b..000000000 --- a/09-ci-04-jenkins/infrastructure/files/pg_hba.conf +++ /dev/null @@ -1,89 +0,0 @@ -# PostgreSQL Client Authentication Configuration File -# =================================================== -# -# Refer to the "Client Authentication" section in the PostgreSQL -# documentation for a complete description of this file. A short -# synopsis follows. -# -# This file controls: which hosts are allowed to connect, how clients -# are authenticated, which PostgreSQL user names they can use, which -# databases they can access. Records take one of these forms: -# -# local DATABASE USER METHOD [OPTIONS] -# host DATABASE USER ADDRESS METHOD [OPTIONS] -# hostssl DATABASE USER ADDRESS METHOD [OPTIONS] -# hostnossl DATABASE USER ADDRESS METHOD [OPTIONS] -# -# (The uppercase items must be replaced by actual values.) -# -# The first field is the connection type: "local" is a Unix-domain -# socket, "host" is either a plain or SSL-encrypted TCP/IP socket, -# "hostssl" is an SSL-encrypted TCP/IP socket, and "hostnossl" is a -# plain TCP/IP socket. -# -# DATABASE can be "all", "sameuser", "samerole", "replication", a -# database name, or a comma-separated list thereof. The "all" -# keyword does not match "replication". Access to replication -# must be enabled in a separate record (see example below). -# -# USER can be "all", a user name, a group name prefixed with "+", or a -# comma-separated list thereof. In both the DATABASE and USER fields -# you can also write a file name prefixed with "@" to include names -# from a separate file. -# -# ADDRESS specifies the set of hosts the record matches. It can be a -# host name, or it is made up of an IP address and a CIDR mask that is -# an integer (between 0 and 32 (IPv4) or 128 (IPv6) inclusive) that -# specifies the number of significant bits in the mask. A host name -# that starts with a dot (.) matches a suffix of the actual host name. -# Alternatively, you can write an IP address and netmask in separate -# columns to specify the set of hosts. Instead of a CIDR-address, you -# can write "samehost" to match any of the server's own IP addresses, -# or "samenet" to match any address in any subnet that the server is -# directly connected to. -# -# METHOD can be "trust", "reject", "md5", "password", "scram-sha-256", -# "gss", "sspi", "ident", "peer", "pam", "ldap", "radius" or "cert". -# Note that "password" sends passwords in clear text; "md5" or -# "scram-sha-256" are preferred since they send encrypted passwords. -# -# OPTIONS are a set of options for the authentication in the format -# NAME=VALUE. The available options depend on the different -# authentication methods -- refer to the "Client Authentication" -# section in the documentation for a list of which options are -# available for which authentication methods. -# -# Database and user names containing spaces, commas, quotes and other -# special characters must be quoted. Quoting one of the keywords -# "all", "sameuser", "samerole" or "replication" makes the name lose -# its special character, and just match a database or username with -# that name. -# -# This file is read on server startup and when the server receives a -# SIGHUP signal. If you edit the file on a running system, you have to -# SIGHUP the server for the changes to take effect, run "pg_ctl reload", -# or execute "SELECT pg_reload_conf()". -# -# Put your actual configuration here -# ---------------------------------- -# -# If you want to allow non-local connections, you need to add more -# "host" records. In that case you will also need to make PostgreSQL -# listen on a non-local interface via the listen_addresses -# configuration parameter, or via the -i or -h command line switches. - - - -# TYPE DATABASE USER ADDRESS METHOD - -# "local" is for Unix domain socket connections only -local all all trust -# IPv4 local connections: -host all all 127.0.0.1/32 md5 -# IPv6 local connections: -host all all ::1/128 md5 -# Allow replication connections from localhost, by a user with the -# replication privilege. -local replication all trust -host replication all 127.0.0.1/32 md5 -host replication all ::1/128 md5 diff --git a/09-ci-04-jenkins/infrastructure/inventory/cicd/group_vars/jenkins.yml b/09-ci-04-jenkins/infrastructure/inventory/cicd/group_vars/jenkins.yml deleted file mode 100644 index e23ccd83d..000000000 --- a/09-ci-04-jenkins/infrastructure/inventory/cicd/group_vars/jenkins.yml +++ /dev/null @@ -1,9 +0,0 @@ ---- -user_group: "{{ jenkins_user_group }}" -user_name: "{{ jenkins_user_name }}" -jenkins_user_name: jenkins -jenkins_user_group: jenkins -java_packages: - - java-11-openjdk-devel - - java-11-openjdk -jenkins_agent_dir: /opt/jenkins_agent/ \ No newline at end of file diff --git a/09-ci-04-jenkins/infrastructure/inventory/cicd/hosts.yml b/09-ci-04-jenkins/infrastructure/inventory/cicd/hosts.yml deleted file mode 100644 index 47da9ddbd..000000000 --- a/09-ci-04-jenkins/infrastructure/inventory/cicd/hosts.yml +++ /dev/null @@ -1,19 +0,0 @@ ---- -all: - hosts: - jenkins-master-01: - ansible_host: - jenkins-agent-01: - ansible_host: - children: - jenkins: - children: - jenkins_masters: - hosts: - jenkins-master-01: - jenkins_agents: - hosts: - jenkins-agent-01: - vars: - ansible_connection_type: paramiko - ansible_user: \ No newline at end of file diff --git a/09-ci-04-jenkins/infrastructure/site.yml b/09-ci-04-jenkins/infrastructure/site.yml deleted file mode 100644 index 5528ffc5b..000000000 --- a/09-ci-04-jenkins/infrastructure/site.yml +++ /dev/null @@ -1,149 +0,0 @@ ---- -- name: Preapre all hosts - hosts: all - tasks: - - name: Create group - become: true - group: - name: "{{ user_group }}" - state: present - - name: Create user - become: true - user: - name: "{{ user_name }}" - generate_ssh_key: true - register: ssh_key_info - - name: Install JDK - become: true - package: - name: "{{ java_packages }}" - state: present - -- name: Get Jenkins master installed - hosts: jenkins_masters - tasks: - - name: Get repo Jenkins - become: true - get_url: - url: https://pkg.jenkins.io/redhat-stable/jenkins.repo - dest: /etc/yum.repos.d/jenkins.repo - validate_certs: false - - name: Add Jenkins key - become: true - rpm_key: - key: https://pkg.jenkins.io/redhat-stable/jenkins.io-2023.key - state: present - validate_certs: false - - name: Install epel-release - become: true - yum: - name: epel-release - state: present - - name: Install Jenkins and requirements - become: true - yum: - name: - - jenkins - - git - state: present - register: jenkins_installed - - name: Ensure jenkins agents are present in known_hosts file - become: true - become_user: "{{ jenkins_user_name }}" - known_hosts: - name: "{{ hostvars[item].ansible_host }}" - state: present - key: "{{ lookup('pipe', 'ssh-keyscan {{ hostvars[item].ansible_host }}') }}" - hash_host: true - with_items: "{{ groups.jenkins_agents }}" - - name: Start Jenkins - become: true - systemd: - name: jenkins - state: restarted - enabled: true - when: jenkins_installed is changed -- name: Prepare jenkins agent - hosts: jenkins_agents - become: true - become_user: "{{ jenkins_user_name }}" - tasks: - - name: Add master publickey into authorized_key - authorized_key: - user: "{{ jenkins_user_name }}" - state: present - key: "{{ hostvars['jenkins-master-01']['ssh_key_info']['ssh_public_key'] }}" - - name: Create agent_dir - become_user: root - file: - path: "{{ jenkins_agent_dir }}" - state: directory - owner: "{{ jenkins_user_name }}" - group: "{{ jenkins_user_group }}" - - name: Add docker repo - become_user: root - get_url: - url: https://download.docker.com/linux/centos/docker-ce.repo - dest: /etc/yum.repos.d/docker-ce.repo - validate_certs: false - - name: Install some required - become_user: root - yum: - name: - - git - - python3 - - docker-ce - - docker-ce-cli - - containerd.io - state: present - - name: Update pip - become_user: root - pip: - executable: pip3 - name: pip - extra_args: --upgrade - - name: Install Ansible - become_user: root - pip: - executable: pip3 - name: - - selinux - - ansible<3.0 - state: present - - name: Reinstall Selinux - become_user: root - pip: - executable: pip3 - name: - - selinux - state: forcereinstall - - name: Add local to PATH - lineinfile: - dest: ~/.bashrc - regexp: export PATH=$PATH:/home/jenkins/.local/bin - line: export PATH=$PATH:/home/jenkins/.local/bin - - name: Create docker group - become_user: root - group: - name: docker - state: present - - name: Add jenkinsuser to dockergroup - become_user: root - user: - name: "{{ jenkins_user_name }}" - groups: docker - - name: Restart docker - become_user: root - systemd: - name: docker - state: restarted - enabled: true - - name: Install agent.jar - get_url: - url: "http://{{ hostvars['jenkins-master-01']['ansible_host'] }}:8080/jnlpJars/agent.jar" - dest: "{{ jenkins_agent_dir }}" - register: install_agent - until: install_agent is succeeded - retries: 10 - timeout: 10 - diff --git a/09-ci-04-jenkins/mnt-homeworks-ansible b/09-ci-04-jenkins/mnt-homeworks-ansible deleted file mode 160000 index e91639035..000000000 --- a/09-ci-04-jenkins/mnt-homeworks-ansible +++ /dev/null @@ -1 +0,0 @@ -Subproject commit e916390350bef6de7c0896a4625f2da98ec73a93 diff --git a/09-ci-04-jenkins/pipeline/Jenkinsfile b/09-ci-04-jenkins/pipeline/Jenkinsfile deleted file mode 100644 index 1b12b6e96..000000000 --- a/09-ci-04-jenkins/pipeline/Jenkinsfile +++ /dev/null @@ -1,17 +0,0 @@ -node("linux"){ - stage("Git checkout"){ - git credentialsId: '5ac0095d-0185-431b-94da-09a0ad9b0e2c', url: 'git@github.com:aragastmatb/example-playbook.git' - } - stage("Sample define secret_check"){ - secret_check=true - } - stage("Run playbook"){ - if (secret_check){ - sh 'ansible-playbook site.yml -i inventory/prod.yml' - } - else{ - echo 'need more action' - } - - } -} \ No newline at end of file diff --git a/09-ci-05-teamcity/README.md b/09-ci-05-teamcity/README.md deleted file mode 100644 index f800bdcea..000000000 --- a/09-ci-05-teamcity/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# Домашнее задание к занятию 11 «Teamcity» - -## Подготовка к выполнению - -1. В Yandex Cloud создайте новый инстанс (4CPU4RAM) на основе образа `jetbrains/teamcity-server`. -2. Дождитесь запуска teamcity, выполните первоначальную настройку. -3. Создайте ещё один инстанс (2CPU4RAM) на основе образа `jetbrains/teamcity-agent`. Пропишите к нему переменную окружения `SERVER_URL: "http://:8111"`. -4. Авторизуйте агент. -5. Сделайте fork [репозитория](https://github.com/aragastmatb/example-teamcity). -6. Создайте VM (2CPU4RAM) и запустите [playbook](./infrastructure). - -## Основная часть - -1. Создайте новый проект в teamcity на основе fork. -2. Сделайте autodetect конфигурации. -3. Сохраните необходимые шаги, запустите первую сборку master. -4. Поменяйте условия сборки: если сборка по ветке `master`, то должен происходит `mvn clean deploy`, иначе `mvn clean test`. -5. Для deploy будет необходимо загрузить [settings.xml](./teamcity/settings.xml) в набор конфигураций maven у teamcity, предварительно записав туда креды для подключения к nexus. -6. В pom.xml необходимо поменять ссылки на репозиторий и nexus. -7. Запустите сборку по master, убедитесь, что всё прошло успешно и артефакт появился в nexus. -8. Мигрируйте `build configuration` в репозиторий. -9. Создайте отдельную ветку `feature/add_reply` в репозитории. -10. Напишите новый метод для класса Welcomer: метод должен возвращать произвольную реплику, содержащую слово `hunter`. -11. Дополните тест для нового метода на поиск слова `hunter` в новой реплике. -12. Сделайте push всех изменений в новую ветку репозитория. -13. Убедитесь, что сборка самостоятельно запустилась, тесты прошли успешно. -14. Внесите изменения из произвольной ветки `feature/add_reply` в `master` через `Merge`. -15. Убедитесь, что нет собранного артефакта в сборке по ветке `master`. -16. Настройте конфигурацию так, чтобы она собирала `.jar` в артефакты сборки. -17. Проведите повторную сборку мастера, убедитесь, что сбора прошла успешно и артефакты собраны. -18. Проверьте, что конфигурация в репозитории содержит все настройки конфигурации из teamcity. -19. В ответе пришлите ссылку на репозиторий. - ---- - -### Как оформить решение задания - -Выполненное домашнее задание пришлите в виде ссылки на .md-файл в вашем репозитории. - ---- diff --git a/09-ci-05-teamcity/infrastructure/.gitignore b/09-ci-05-teamcity/infrastructure/.gitignore deleted file mode 100644 index 483815e4c..000000000 --- a/09-ci-05-teamcity/infrastructure/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -files/*.pub -roles/* \ No newline at end of file diff --git a/09-ci-05-teamcity/infrastructure/inventory/cicd/group_vars/nexus.yml b/09-ci-05-teamcity/infrastructure/inventory/cicd/group_vars/nexus.yml deleted file mode 100644 index b84eba748..000000000 --- a/09-ci-05-teamcity/infrastructure/inventory/cicd/group_vars/nexus.yml +++ /dev/null @@ -1,22 +0,0 @@ ---- -nexus_user_group: nexus -nexus_user_name: nexus -nexus_directory_data: "/home/{{ nexus_user_name }}/sonatype-work/nexus3" -nexus_directory_home: "/home/{{ nexus_user_name }}/nexus" -nexus_directory_log: "/home/{{ nexus_user_name }}/log" -nexus_directory_package: "/home/{{ nexus_user_name }}/pkg" -nexus_directory_tmp: "/home/{{ nexus_user_name }}/tmp" -nexus_version: 3.14.0-04 -nexus_download_url: https://download.sonatype.com/nexus/3 -nexus_service_enabled: true -nexus_ulimit: 65536 -nexus_context_path: / -nexus_host: 0.0.0.0 -nexus_port: 8081 -nexus_port_check_timeout: 600 -nexus_edition: nexus-oss-edition -nexus_features: nexus-oss-feature -nexus_java_heap_size: 1200M -nexus_java_max_direct_memory: 2G -nexus_service_start_on_boot: true -nexus_configuration_disk_free_space_limit: ~ \ No newline at end of file diff --git a/09-ci-05-teamcity/infrastructure/inventory/cicd/hosts.yml b/09-ci-05-teamcity/infrastructure/inventory/cicd/hosts.yml deleted file mode 100644 index 8926822f0..000000000 --- a/09-ci-05-teamcity/infrastructure/inventory/cicd/hosts.yml +++ /dev/null @@ -1,12 +0,0 @@ ---- -all: - hosts: - nexus-01: - ansible_host: - children: - nexus: - hosts: - nexus-01: - vars: - ansible_connection_type: paramiko - ansible_user: \ No newline at end of file diff --git a/09-ci-05-teamcity/infrastructure/site.yml b/09-ci-05-teamcity/infrastructure/site.yml deleted file mode 100644 index 4a7aab0bf..000000000 --- a/09-ci-05-teamcity/infrastructure/site.yml +++ /dev/null @@ -1,158 +0,0 @@ ---- -- name: Get Nexus installed - hosts: nexus - pre_tasks: - - name: Create Nexus group - become: true - group: - name: "{{ nexus_user_group }}" - state: present - - name: Create Nexus user - become: true - user: - name: "{{ nexus_user_name }}" - - name: Install JDK - become: true - package: - name: [java-1.8.0-openjdk, java-1.8.0-openjdk-devel] - state: present - tasks: - - name: Create Nexus directories - become: true - file: - group: "{{ nexus_user_group }}" - owner: "{{ nexus_user_name }}" - path: "{{ item }}" - state: directory - with_items: - - "{{ nexus_directory_log }}" - - "{{ nexus_directory_data }}" - - "{{ nexus_directory_data }}/etc" - - "{{ nexus_directory_package }}" - - "{{ nexus_directory_tmp }}" - - - name: Download Nexus - become: true - become_user: "{{ nexus_user_name }}" - get_url: - dest: "{{ nexus_directory_package }}/nexus-{{ nexus_version }}.tar.gz" - url: "{{ nexus_download_url }}/nexus-{{ nexus_version }}-unix.tar.gz" - - - name: Unpack Nexus - become: true - become_user: "{{ nexus_user_name }}" - unarchive: - copy: no - creates: "{{ nexus_directory_package }}/nexus-{{ nexus_version }}" - dest: "{{ nexus_directory_package }}" - src: "{{ nexus_directory_package }}/nexus-{{ nexus_version }}.tar.gz" - - - name: Link to Nexus Directory - become: true - become_user: "{{ nexus_user_name }}" - file: - dest: "{{ nexus_directory_home }}" - src: "{{ nexus_directory_package }}/nexus-{{ nexus_version }}" - state: link - - - name: Add NEXUS_HOME for Nexus user - become: true - become_user: "{{ nexus_user_name }}" - lineinfile: - create: yes - dest: "/home/{{ nexus_user_name }}/.bashrc" - insertafter: EOF - line: "export NEXUS_HOME={{ nexus_directory_home }}" - - - name: Add run_as_user to Nexus.rc - become: true - become_user: "{{ nexus_user_name }}" - lineinfile: - create: yes - dest: "{{ nexus_directory_home }}/bin/nexus.rc" - insertafter: EOF - line: "run_as_user=\"{{ nexus_user_name }}\"" - regexp: "^run_as_user" - - - name: Raise nofile limit for Nexus user - become: true - pam_limits: - domain: "{{ nexus_user_name }}" - limit_type: "-" - limit_item: nofile - value: "{{ nexus_ulimit }}" - - - name: Create Nexus service for SystemD - become: true - template: - dest: /lib/systemd/system/nexus.service - mode: 0644 - src: nexus.systemd.j2 - - - name: Ensure Nexus service is enabled for SystemD - become: true - systemd: - daemon_reload: yes - enabled: yes - name: nexus - when: - - nexus_service_enabled - - - name: Create Nexus vmoptions - become: true - become_user: "{{ nexus_user_name }}" - template: - dest: "{{ nexus_directory_home }}/bin/nexus.vmoptions" - src: nexus.vmoptions.j2 - register: nexus_config_changed - - - name: Create Nexus properties - become: true - become_user: "{{ nexus_user_name }}" - template: - dest: "{{ nexus_directory_data }}/etc/nexus.properties" - src: nexus.properties.j2 - register: nexus_config_changed - - - name: Lower Nexus disk space threshold - become: true - become_user: "{{ nexus_user_name }}" - lineinfile: - backrefs: yes - dest: "{{ nexus_directory_home }}/etc/karaf/system.properties" - insertafter: EOF - line: "storage.diskCache.diskFreeSpaceLimit={{ nexus_configuration_disk_free_space_limit }}" - regexp: ^storage\.diskCache\.diskFreeSpaceLimit - when: nexus_configuration_disk_free_space_limit is not none - register: nexus_config_changed - - - name: Start Nexus service if enabled - become: true - service: - enabled: yes - name: nexus - state: started - when: - - nexus_service_start_on_boot - - not nexus_config_changed.changed - tags: - - skip_ansible_lint - - - name: Ensure Nexus service is restarted - become: true - service: - name: nexus - state: restarted - when: - - nexus_service_start_on_boot - - nexus_config_changed.changed - tags: - - skip_ansible_lint - - - name: Wait for Nexus port if started - wait_for: - port: "{{ nexus_port }}" - state: started - timeout: "{{ nexus_port_check_timeout }}" - when: - - nexus_service_start_on_boot diff --git a/09-ci-05-teamcity/infrastructure/templates/nexus.properties.j2 b/09-ci-05-teamcity/infrastructure/templates/nexus.properties.j2 deleted file mode 100644 index aa2645463..000000000 --- a/09-ci-05-teamcity/infrastructure/templates/nexus.properties.j2 +++ /dev/null @@ -1,12 +0,0 @@ -# -# - -# Jetty section -application-host={{ nexus_host }} -application-port={{ nexus_port }} -nexus-context-path={{ nexus_context_path }} - -# Nexus section -nexus-edition={{ nexus_edition }} -nexus-features=\ - {{ nexus_features }} \ No newline at end of file diff --git a/09-ci-05-teamcity/infrastructure/templates/nexus.systemd.j2 b/09-ci-05-teamcity/infrastructure/templates/nexus.systemd.j2 deleted file mode 100644 index 7665d96a8..000000000 --- a/09-ci-05-teamcity/infrastructure/templates/nexus.systemd.j2 +++ /dev/null @@ -1,15 +0,0 @@ -[Unit] -Description=nexus service -After=network.target - -[Service] -Type=forking -User={{ nexus_user_name }} -Group={{ nexus_user_group }} -LimitNOFILE={{ nexus_ulimit }} -ExecStart={{ nexus_directory_home }}/bin/nexus start -ExecStop={{ nexus_directory_home }}/bin/nexus stop -Restart=on-abort - -[Install] -WantedBy=multi-user.target \ No newline at end of file diff --git a/09-ci-05-teamcity/infrastructure/templates/nexus.vmoptions.j2 b/09-ci-05-teamcity/infrastructure/templates/nexus.vmoptions.j2 deleted file mode 100644 index dea2288a7..000000000 --- a/09-ci-05-teamcity/infrastructure/templates/nexus.vmoptions.j2 +++ /dev/null @@ -1,16 +0,0 @@ --Xms{{ nexus_java_heap_size }} --Xmx{{ nexus_java_heap_size }} --XX:MaxDirectMemorySize={{ nexus_java_max_direct_memory }} --XX:+UnlockDiagnosticVMOptions --XX:+UnsyncloadClass --XX:+LogVMOutput --XX:LogFile={{ nexus_directory_log }}/jvm.log --XX:-OmitStackTraceInFastThrow --Djava.net.preferIPv4Stack=true --Dkaraf.home=. --Dkaraf.base=. --Dkaraf.etc=etc/karaf --Djava.util.logging.config.file=etc/karaf/java.util.logging.properties --Dkaraf.data={{ nexus_directory_data }} --Djava.io.tmpdir={{ nexus_directory_tmp }} --Dkaraf.startLocalConsole=false \ No newline at end of file diff --git a/09-ci-05-teamcity/teamcity/docker-compose.yml b/09-ci-05-teamcity/teamcity/docker-compose.yml deleted file mode 100644 index 57731325a..000000000 --- a/09-ci-05-teamcity/teamcity/docker-compose.yml +++ /dev/null @@ -1,17 +0,0 @@ -version: "3" -services: - teamcity: - image: jetbrains/teamcity-server - volumes: - - ~/teamcity/data/:/data/teamcity_server/datadir - - ~/teamcity/logs/:/opt/teamcity/logs - ports: - - 8111:8111 - teamcity-agent: - image: jetbrains/teamcity-agent - depends_on: - - teamcity - volumes: - - ~/teamcity/agent/:/data/teamcity_agent/conf - environment: - SERVER_URL: "http://teamcity:8111" \ No newline at end of file diff --git a/09-ci-05-teamcity/teamcity/example-teamcity b/09-ci-05-teamcity/teamcity/example-teamcity deleted file mode 160000 index e84d9cf3e..000000000 --- a/09-ci-05-teamcity/teamcity/example-teamcity +++ /dev/null @@ -1 +0,0 @@ -Subproject commit e84d9cf3e3f8712bb21f2ef676fe27984ca79a0f diff --git a/09-ci-05-teamcity/teamcity/settings.xml b/09-ci-05-teamcity/teamcity/settings.xml deleted file mode 100644 index 7a49a5a81..000000000 --- a/09-ci-05-teamcity/teamcity/settings.xml +++ /dev/null @@ -1,261 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - nexus - admin - admin123 - - - - - - - - - - - - - - - - - - diff --git a/09-ci-06-gitlab/README.md b/09-ci-06-gitlab/README.md deleted file mode 100644 index 5db5ac2da..000000000 --- a/09-ci-06-gitlab/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# Домашнее задание к занятию 12 «GitLab» - -## Подготовка к выполнению - - -1. Или подготовьте к работе Managed GitLab от yandex cloud [по инструкции](https://cloud.yandex.ru/docs/managed-gitlab/operations/instance/instance-create) . -Или создайте виртуальную машину из публичного образа [по инструкции](https://cloud.yandex.ru/marketplace/products/yc/gitlab ) . -2. Создайте виртуальную машину и установите на нее gitlab runner, подключите к вашему серверу gitlab [по инструкции](https://docs.gitlab.com/runner/install/linux-repository.html) . - -3. (* Необязательное задание повышенной сложности. ) Если вы уже знакомы с k8s попробуйте выполнить задание, запустив gitlab server и gitlab runner в k8s [по инструкции](https://cloud.yandex.ru/docs/tutorials/infrastructure-management/gitlab-containers). - -4. Создайте свой новый проект. -5. Создайте новый репозиторий в GitLab, наполните его [файлами](./repository). -6. Проект должен быть публичным, остальные настройки по желанию. - -## Основная часть - -### DevOps - -В репозитории содержится код проекта на Python. Проект — RESTful API сервис. Ваша задача — автоматизировать сборку образа с выполнением python-скрипта: - -1. Образ собирается на основе [centos:7](https://hub.docker.com/_/centos?tab=tags&page=1&ordering=last_updated). -2. Python версии не ниже 3.7. -3. Установлены зависимости: `flask` `flask-jsonpify` `flask-restful`. -4. Создана директория `/python_api`. -5. Скрипт из репозитория размещён в /python_api. -6. Точка вызова: запуск скрипта. -7. При комите в любую ветку должен собираться docker image с форматом имени hello:gitlab-$CI_COMMIT_SHORT_SHA . Образ должен быть выложен в Gitlab registry или yandex registry. - -### Product Owner - -Вашему проекту нужна бизнесовая доработка: нужно поменять JSON ответа на вызов метода GET `/rest/api/get_info`, необходимо создать Issue в котором указать: - -1. Какой метод необходимо исправить. -2. Текст с `{ "message": "Already started" }` на `{ "message": "Running"}`. -3. Issue поставить label: feature. - -### Developer - -Пришёл новый Issue на доработку, вам нужно: - -1. Создать отдельную ветку, связанную с этим Issue. -2. Внести изменения по тексту из задания. -3. Подготовить Merge Request, влить необходимые изменения в `master`, проверить, что сборка прошла успешно. - - -### Tester - -Разработчики выполнили новый Issue, необходимо проверить валидность изменений: - -1. Поднять докер-контейнер с образом `python-api:latest` и проверить возврат метода на корректность. -2. Закрыть Issue с комментарием об успешности прохождения, указав желаемый результат и фактически достигнутый. - -## Итог - -В качестве ответа пришлите подробные скриншоты по каждому пункту задания: - -- файл gitlab-ci.yml; -- Dockerfile; -- лог успешного выполнения пайплайна; -- решённый Issue. - -### Важно -После выполнения задания выключите и удалите все задействованные ресурсы в Yandex Cloud. - diff --git a/09-ci-06-gitlab/repository/python-api.py b/09-ci-06-gitlab/repository/python-api.py deleted file mode 100644 index a2d01111f..000000000 --- a/09-ci-06-gitlab/repository/python-api.py +++ /dev/null @@ -1,16 +0,0 @@ -from flask import Flask, request -from flask_restful import Resource, Api -from json import dumps -from flask_jsonpify import jsonify - -app = Flask(__name__) -api = Api(app) - -class Info(Resource): - def get(self): - return {'version': 3, 'method': 'GET', 'message': 'Already started'} - -api.add_resource(Info, '/get_info') - -if __name__ == '__main__': - app.run(host='0.0.0.0', port='5290') diff --git a/09-ci-additional/README.md b/09-ci-additional/README.md deleted file mode 100644 index ee13d8823..000000000 --- a/09-ci-additional/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# Дополнительные материалы к лекциям по CICD - -1. [Топология DevOps команд](https://web.devopstopologies.com). -2. [Что такое Жизненный цикл ПО](https://youtu.be/G5DsB5wZ1kw). -3. [Что такое модели жизненного цикла ПО и их примеры](https://youtu.be/iObvvaH079w) -4. [Как установить Jenkins?](https://youtu.be/R4iON42SnuI) -5. [Про разные джобы, пайплайны и вообще про использование Jenkins](https://youtu.be/-tTS5IzVrZQ) -6. [Как можно донастроить Jenkins?](https://youtu.be/0MV-DJCglFk) diff --git a/10-monitoring-01-base/README.md b/10-monitoring-01-base/README.md deleted file mode 100644 index ea55a0f4f..000000000 --- a/10-monitoring-01-base/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# Домашнее задание к занятию 13 «Введение в мониторинг» - -## Обязательные задания - -1. Вас пригласили настроить мониторинг на проект. На онбординге вам рассказали, что проект представляет из себя платформу для вычислений с выдачей текстовых отчётов, которые сохраняются на диск. -Взаимодействие с платформой осуществляется по протоколу http. Также вам отметили, что вычисления загружают ЦПУ. Какой минимальный набор метрик вы выведите в мониторинг и почему? - -2. Менеджер продукта, посмотрев на ваши метрики, сказал, что ему непонятно, что такое RAM/inodes/CPUla. Также он сказал, что хочет понимать, насколько мы выполняем свои обязанности перед клиентами и какое качество обслуживания. Что вы можете ему предложить? - -3. Вашей DevOps-команде в этом году не выделили финансирование на построение системы сбора логов. Разработчики, в свою очередь, хотят видеть все ошибки, которые выдают их приложения. Какое решение вы можете предпринять в этой ситуации, чтобы разработчики получали ошибки приложения? - -3. Вы, как опытный SRE, сделали мониторинг, куда вывели отображения выполнения SLA = 99% по http-кодам ответов. -Этот параметр вычисляется по формуле: summ_2xx_requests/summ_all_requests. Он не поднимается выше 70%, но при этом в вашей системе нет кодов ответа 5xx и 4xx. Где у вас ошибка? - -## Дополнительное задание* (со звёздочкой) - -Выполнение этого задания необязательно и никак не влияет на получение зачёта по домашней работе. - -_____ - -Вы устроились на работу в стартап. На данный момент у вас нет возможности развернуть полноценную систему -мониторинга, и вы решили самостоятельно написать простой python3-скрипт для сбора основных метрик сервера. - -Вы, как опытный системный администратор, знаете, что системная информация сервера лежит в директории `/proc`. Также знаете, что в системе Linux есть планировщик задач cron, который может запускать задачи по расписанию. - -Суммировав всё, вы спроектировали приложение, которое: - -- является python3-скриптом; -- собирает метрики из папки `/proc`; -- складывает метрики в файл 'YY-MM-DD-awesome-monitoring.log' в директорию /var/log -(YY — год, MM — месяц, DD — день); -- каждый сбор метрик складывается в виде json-строки, в виде: - + timestamp — временная метка, int, unixtimestamp; - + metric_1 — метрика 1; - + metric_2 — метрика 2; - - ... - - + metric_N — метрика N. - -- сбор метрик происходит каждую минуту по cron-расписанию. - -Для успешного выполнения задания нужно привести: - -* работающий код python3-скрипта; -* конфигурацию cron-расписания; -* пример верно сформированного 'YY-MM-DD-awesome-monitoring.log', имеющий не меньше пяти записей. - -Дополнительная информация: - -1. Количество собираемых метрик должно быть не меньше четырёх. -1. По желанию можно не ограничивать себя только сбором метрик из `/proc`. - ---- - -### Как оформить решение задания - -Выполненное домашнее задание пришлите в виде ссылки на .md-файл в вашем репозитории. - - ---- diff --git a/10-monitoring-02-systems/README.md b/10-monitoring-02-systems/README.md deleted file mode 100644 index 2710b3aa9..000000000 --- a/10-monitoring-02-systems/README.md +++ /dev/null @@ -1,129 +0,0 @@ -# Домашнее задание к занятию "13.Системы мониторинга" - -## Обязательные задания - -1. Вас пригласили настроить мониторинг на проект. На онбординге вам рассказали, что проект представляет из себя -платформу для вычислений с выдачей текстовых отчетов, которые сохраняются на диск. Взаимодействие с платформой -осуществляется по протоколу http. Также вам отметили, что вычисления загружают ЦПУ. Какой минимальный набор метрик вы -выведите в мониторинг и почему? -# -2. Менеджер продукта посмотрев на ваши метрики сказал, что ему непонятно что такое RAM/inodes/CPUla. Также он сказал, -что хочет понимать, насколько мы выполняем свои обязанности перед клиентами и какое качество обслуживания. Что вы -можете ему предложить? -# -3. Вашей DevOps команде в этом году не выделили финансирование на построение системы сбора логов. Разработчики в свою -очередь хотят видеть все ошибки, которые выдают их приложения. Какое решение вы можете предпринять в этой ситуации, -чтобы разработчики получали ошибки приложения? -# -4. Вы, как опытный SRE, сделали мониторинг, куда вывели отображения выполнения SLA=99% по http кодам ответов. -Вычисляете этот параметр по следующей формуле: summ_2xx_requests/summ_all_requests. Данный параметр не поднимается выше -70%, но при этом в вашей системе нет кодов ответа 5xx и 4xx. Где у вас ошибка? -# -5. Опишите основные плюсы и минусы pull и push систем мониторинга. -# -6. Какие из ниже перечисленных систем относятся к push модели, а какие к pull? А может есть гибридные? - - - Prometheus - - TICK - - Zabbix - - VictoriaMetrics - - Nagios -# -7. Склонируйте себе [репозиторий](https://github.com/influxdata/sandbox/tree/master) и запустите TICK-стэк, -используя технологии docker и docker-compose. - -В виде решения на это упражнение приведите скриншот веб-интерфейса ПО chronograf (`http://localhost:8888`). - -P.S.: если при запуске некоторые контейнеры будут падать с ошибкой - проставьте им режим `Z`, например -`./data:/var/lib:Z` -# -8. Перейдите в веб-интерфейс Chronograf (http://localhost:8888) и откройте вкладку Data explorer. - - - Нажмите на кнопку Add a query - - Изучите вывод интерфейса и выберите БД telegraf.autogen - - В `measurments` выберите cpu->host->telegraf-getting-started, а в `fields` выберите usage_system. Внизу появится график утилизации cpu. - - Вверху вы можете увидеть запрос, аналогичный SQL-синтаксису. Поэкспериментируйте с запросом, попробуйте изменить группировку и интервал наблюдений. - -Для выполнения задания приведите скриншот с отображением метрик утилизации cpu из веб-интерфейса. -# -9. Изучите список [telegraf inputs](https://github.com/influxdata/telegraf/tree/master/plugins/inputs). -Добавьте в конфигурацию telegraf следующий плагин - [docker](https://github.com/influxdata/telegraf/tree/master/plugins/inputs/docker): -``` -[[inputs.docker]] - endpoint = "unix:///var/run/docker.sock" -``` - -Дополнительно вам может потребоваться донастройка контейнера telegraf в `docker-compose.yml` дополнительного volume и -режима privileged: -``` - telegraf: - image: telegraf:1.4.0 - privileged: true - volumes: - - ./etc/telegraf.conf:/etc/telegraf/telegraf.conf:Z - - /var/run/docker.sock:/var/run/docker.sock:Z - links: - - influxdb - ports: - - "8092:8092/udp" - - "8094:8094" - - "8125:8125/udp" -``` - -После настройке перезапустите telegraf, обновите веб интерфейс и приведите скриншотом список `measurments` в -веб-интерфейсе базы telegraf.autogen . Там должны появиться метрики, связанные с docker. - -Факультативно можете изучить какие метрики собирает telegraf после выполнения данного задания. - -## Дополнительное задание (со звездочкой*) - необязательно к выполнению - -1. Вы устроились на работу в стартап. На данный момент у вас нет возможности развернуть полноценную систему -мониторинга, и вы решили самостоятельно написать простой python3-скрипт для сбора основных метрик сервера. Вы, как -опытный системный-администратор, знаете, что системная информация сервера лежит в директории `/proc`. -Также, вы знаете, что в системе Linux есть планировщик задач cron, который может запускать задачи по расписанию. - -Суммировав все, вы спроектировали приложение, которое: -- является python3 скриптом -- собирает метрики из папки `/proc` -- складывает метрики в файл 'YY-MM-DD-awesome-monitoring.log' в директорию /var/log -(YY - год, MM - месяц, DD - день) -- каждый сбор метрик складывается в виде json-строки, в виде: - + timestamp (временная метка, int, unixtimestamp) - + metric_1 (метрика 1) - + metric_2 (метрика 2) - - ... - - + metric_N (метрика N) - -- сбор метрик происходит каждую 1 минуту по cron-расписанию - -Для успешного выполнения задания нужно привести: - -а) работающий код python3-скрипта, - -б) конфигурацию cron-расписания, - -в) пример верно сформированного 'YY-MM-DD-awesome-monitoring.log', имеющий не менее 5 записей, - -P.S.: количество собираемых метрик должно быть не менее 4-х. -P.P.S.: по желанию можно себя не ограничивать только сбором метрик из `/proc`. - -2. В веб-интерфейсе откройте вкладку `Dashboards`. Попробуйте создать свой dashboard с отображением: - - - утилизации ЦПУ - - количества использованного RAM - - утилизации пространства на дисках - - количество поднятых контейнеров - - аптайм - - ... - - фантазируйте) - - --- - -### Как оформить ДЗ? - -Выполненное домашнее задание пришлите ссылкой на .md-файл в вашем репозитории. - ---- - diff --git a/10-monitoring-03-grafana/README.md b/10-monitoring-03-grafana/README.md deleted file mode 100644 index 3fb6c8d05..000000000 --- a/10-monitoring-03-grafana/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# Домашнее задание к занятию 14 «Средство визуализации Grafana» - -## Задание повышенной сложности - -**При решении задания 1** не используйте директорию [help](./help) для сборки проекта. Самостоятельно разверните grafana, где в роли источника данных будет выступать prometheus, а сборщиком данных будет node-exporter: - -- grafana; -- prometheus-server; -- prometheus node-exporter. - -За дополнительными материалами можете обратиться в официальную документацию grafana и prometheus. - -В решении к домашнему заданию также приведите все конфигурации, скрипты, манифесты, которые вы -использовали в процессе решения задания. - -**При решении задания 3** вы должны самостоятельно завести удобный для вас канал нотификации, например, Telegram или email, и отправить туда тестовые события. - -В решении приведите скриншоты тестовых событий из каналов нотификаций. - -## Обязательные задания - -### Задание 1 - -1. Используя директорию [help](./help) внутри этого домашнего задания, запустите связку prometheus-grafana. -1. Зайдите в веб-интерфейс grafana, используя авторизационные данные, указанные в манифесте docker-compose. -1. Подключите поднятый вами prometheus, как источник данных. -1. Решение домашнего задания — скриншот веб-интерфейса grafana со списком подключенных Datasource. - -## Задание 2 - -Изучите самостоятельно ресурсы: - -1. [PromQL tutorial for beginners and humans](https://valyala.medium.com/promql-tutorial-for-beginners-9ab455142085). -1. [Understanding Machine CPU usage](https://www.robustperception.io/understanding-machine-cpu-usage). -1. [Introduction to PromQL, the Prometheus query language](https://grafana.com/blog/2020/02/04/introduction-to-promql-the-prometheus-query-language/). - -Создайте Dashboard и в ней создайте Panels: - -- утилизация CPU для nodeexporter (в процентах, 100-idle); -- CPULA 1/5/15; -- количество свободной оперативной памяти; -- количество места на файловой системе. - -Для решения этого задания приведите promql-запросы для выдачи этих метрик, а также скриншот получившейся Dashboard. - -## Задание 3 - -1. Создайте для каждой Dashboard подходящее правило alert — можно обратиться к первой лекции в блоке «Мониторинг». -1. В качестве решения задания приведите скриншот вашей итоговой Dashboard. - -## Задание 4 - -1. Сохраните ваш Dashboard.Для этого перейдите в настройки Dashboard, выберите в боковом меню «JSON MODEL». Далее скопируйте отображаемое json-содержимое в отдельный файл и сохраните его. -1. В качестве решения задания приведите листинг этого файла. - ---- - -### Как оформить решение задания - -Выполненное домашнее задание пришлите в виде ссылки на .md-файл в вашем репозитории. - ---- diff --git a/10-monitoring-03-grafana/help/docker-compose.yml b/10-monitoring-03-grafana/help/docker-compose.yml deleted file mode 100644 index 075271af3..000000000 --- a/10-monitoring-03-grafana/help/docker-compose.yml +++ /dev/null @@ -1,68 +0,0 @@ -version: '3.8' - -services: - prometheus: - image: prom/prometheus:v2.24.1 - container_name: prometheus - volumes: - - ./prometheus:/etc/prometheus:Z - command: - - '--config.file=/etc/prometheus/prometheus.yml' - - '--storage.tsdb.path=/prometheus' - - '--web.console.libraries=/etc/prometheus/console_libraries' - - '--web.console.templates=/etc/prometheus/consoles' - - '--storage.tsdb.retention.time=200h' - - '--web.enable-lifecycle' - restart: unless-stopped - depends_on: - - nodeexporter - expose: - - 9090 - networks: - - monitor-net - - nodeexporter: - image: prom/node-exporter:v1.0.1 - container_name: nodeexporter - volumes: - - /proc:/host/proc:ro - - /sys:/host/sys:ro - - /:/rootfs:ro - command: - - '--path.procfs=/host/proc' - - '--path.rootfs=/rootfs' - - '--path.sysfs=/host/sys' - - '--collector.filesystem.ignored-mount-points=^/(sys|proc|dev|host|etc)($$|/)' - restart: unless-stopped - expose: - - 9100 - networks: - - monitor-net - - - grafana: - image: grafana/grafana:7.4.0 - container_name: grafana - volumes: - - grafana_data:/var/lib/grafana - environment: - - GF_SECURITY_ADMIN_USER=admin - - GF_SECURITY_ADMIN_PASSWORD=admin - - GF_USERS_ALLOW_SIGN_UP=false - restart: unless-stopped - depends_on: - - prometheus - ports: - - 3000:3000 - expose: - - 3000 - networks: - - monitor-net - -networks: - monitor-net: - driver: bridge - -volumes: - prometheus_data: {} - grafana_data: {} \ No newline at end of file diff --git a/10-monitoring-03-grafana/help/prometheus/prometheus.yml b/10-monitoring-03-grafana/help/prometheus/prometheus.yml deleted file mode 100644 index 413e59a9b..000000000 --- a/10-monitoring-03-grafana/help/prometheus/prometheus.yml +++ /dev/null @@ -1,9 +0,0 @@ -global: - scrape_interval: 15s - evaluation_interval: 15s - -scrape_configs: - - job_name: 'nodeexporter' - scrape_interval: 5s - static_configs: - - targets: ['nodeexporter:9100'] diff --git a/10-monitoring-04-elk/README.md b/10-monitoring-04-elk/README.md deleted file mode 100644 index 9930b022f..000000000 --- a/10-monitoring-04-elk/README.md +++ /dev/null @@ -1,64 +0,0 @@ -# Домашнее задание к занятию 15 «Система сбора логов Elastic Stack» - -## Дополнительные ссылки - -При выполнении задания используйте дополнительные ресурсы: - -- [поднимаем elk в docker](https://www.elastic.co/guide/en/elastic-stack-get-started/current/get-started-docker.html); -- [поднимаем elk в docker с filebeat и docker-логами](https://www.sarulabs.com/post/5/2019-08-12/sending-docker-logs-to-elasticsearch-and-kibana-with-filebeat.html); -- [конфигурируем logstash](https://www.elastic.co/guide/en/logstash/current/configuration.html); -- [плагины filter для logstash](https://www.elastic.co/guide/en/logstash/current/filter-plugins.html); -- [конфигурируем filebeat](https://www.elastic.co/guide/en/beats/libbeat/5.3/config-file-format.html); -- [привязываем индексы из elastic в kibana](https://www.elastic.co/guide/en/kibana/current/index-patterns.html); -- [как просматривать логи в kibana](https://www.elastic.co/guide/en/kibana/current/discover.html); -- [решение ошибки increase vm.max_map_count elasticsearch](https://stackoverflow.com/questions/42889241/how-to-increase-vm-max-map-count). - -В процессе выполнения в зависимости от системы могут также возникнуть не указанные здесь проблемы. - -Используйте output stdout filebeat/kibana и api elasticsearch для изучения корня проблемы и её устранения. - -## Задание повышенной сложности - -Не используйте директорию [help](./help) при выполнении домашнего задания. - -## Задание 1 - -Вам необходимо поднять в докере и связать между собой: - -- elasticsearch (hot и warm ноды); -- logstash; -- kibana; -- filebeat. - -Logstash следует сконфигурировать для приёма по tcp json-сообщений. - -Filebeat следует сконфигурировать для отправки логов docker вашей системы в logstash. - -В директории [help](./help) находится манифест docker-compose и конфигурации filebeat/logstash для быстрого -выполнения этого задания. - -Результатом выполнения задания должны быть: - -- скриншот `docker ps` через 5 минут после старта всех контейнеров (их должно быть 5); -- скриншот интерфейса kibana; -- docker-compose манифест (если вы не использовали директорию help); -- ваши yml-конфигурации для стека (если вы не использовали директорию help). - -## Задание 2 - -Перейдите в меню [создания index-patterns в kibana](http://localhost:5601/app/management/kibana/indexPatterns/create) и создайте несколько index-patterns из имеющихся. - -Перейдите в меню просмотра логов в kibana (Discover) и самостоятельно изучите, как отображаются логи и как производить поиск по логам. - -В манифесте директории help также приведенно dummy-приложение, которое генерирует рандомные события в stdout-контейнера. -Эти логи должны порождать индекс logstash-* в elasticsearch. Если этого индекса нет — воспользуйтесь советами и источниками из раздела «Дополнительные ссылки» этого задания. - ---- - -### Как оформить решение задания - -Выполненное домашнее задание пришлите в виде ссылки на .md-файл в вашем репозитории. - ---- - - diff --git a/10-monitoring-04-elk/help/configs/filebeat.yml b/10-monitoring-04-elk/help/configs/filebeat.yml deleted file mode 100644 index 560bc9a08..000000000 --- a/10-monitoring-04-elk/help/configs/filebeat.yml +++ /dev/null @@ -1,20 +0,0 @@ -filebeat.inputs: - - type: container - paths: - - '/var/lib/docker/containers/*/*.log' - -processors: - - add_docker_metadata: - host: "unix:///var/run/docker.sock" - - - decode_json_fields: - fields: ["message"] - target: "json" - overwrite_keys: true - -output.logstash: - hosts: ["logstash:5046"] - protocol: tcp - -logging.json: true -logging.metrics.enabled: false diff --git a/10-monitoring-04-elk/help/configs/logstash.conf b/10-monitoring-04-elk/help/configs/logstash.conf deleted file mode 100644 index 28b1555f1..000000000 --- a/10-monitoring-04-elk/help/configs/logstash.conf +++ /dev/null @@ -1,18 +0,0 @@ -input { - beats { - port => 5046 - } -} - -filter{ - json{ - source => "json" - } -} - -output { - elasticsearch { - hosts => ["es-hot:9200"] - index => "logstash-%{+YYYY.MM.dd}" - } -} diff --git a/10-monitoring-04-elk/help/configs/logstash.yml b/10-monitoring-04-elk/help/configs/logstash.yml deleted file mode 100644 index 342d19af8..000000000 --- a/10-monitoring-04-elk/help/configs/logstash.yml +++ /dev/null @@ -1 +0,0 @@ -http.host: "0.0.0.0" diff --git a/10-monitoring-04-elk/help/docker-compose.yml b/10-monitoring-04-elk/help/docker-compose.yml deleted file mode 100644 index a60b23df5..000000000 --- a/10-monitoring-04-elk/help/docker-compose.yml +++ /dev/null @@ -1,125 +0,0 @@ -##Предварительно выполнить на Linux хосте команду: sudo sysctl -w vm.max_map_count=262144 -##https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html#_set_vm_max_map_count_to_at_least_262144 -# -##kibana address: http://127.0.0.1:5601 будет доступно через ~1-2 мин -# -# -version: '2.2' -services: - - es-hot: - image: elasticsearch:8.7.0 - container_name: es-hot - environment: - - node.name=es-hot - - cluster.name=es-docker-cluster - - discovery.seed_hosts=es-hot,es-warm - - cluster.initial_master_nodes=es-hot,es-warm - - node.roles=master,data_content,data_hot - - "ES_JAVA_OPTS=-Xms512m -Xmx512m" - - "http.host=0.0.0.0" - - xpack.security.enabled=false - volumes: - - data01:/usr/share/elasticsearch/data:Z - ulimits: - memlock: - soft: -1 - hard: -1 - nofile: - soft: 65536 - hard: 65536 - ports: - - 9200:9200 - networks: - - elastic - depends_on: - - es-warm - - es-warm: - image: elasticsearch:8.7.0 - container_name: es-warm - environment: - - node.name=es-warm - - cluster.name=es-docker-cluster - - discovery.seed_hosts=es-hot,es-warm - - cluster.initial_master_nodes=es-hot,es-warm - - node.roles=master,data_warm - - "ES_JAVA_OPTS=-Xms512m -Xmx512m" - - xpack.security.enabled=false - - "http.host=0.0.0.0" - volumes: - - data02:/usr/share/elasticsearch/data:Z - ulimits: - memlock: - soft: -1 - hard: -1 - nofile: - soft: 65536 - hard: 65536 - networks: - - elastic - - kibana: - image: kibana:8.7.0 - container_name: kibana - ports: - - 5601:5601 - environment: - ELASTICSEARCH_URL: http://es-hot:9200 - ELASTICSEARCH_HOSTS: '["http://es-hot:9200","http://es-warm:9200"]' - networks: - - elastic - depends_on: - - es-hot - - es-warm - - logstash: - image: logstash:8.7.0 - container_name: logstash - environment: - - "LS_JAVA_OPTS=-Xms256m -Xmx256m" - ports: - - 5046:5046 - - 5044:5044 - volumes: - - ./configs/logstash.conf:/usr/share/logstash/pipeline/logstash.conf:Z - - ./configs/logstash.yml:/opt/logstash/config/logstash.yml:Z - networks: - - elastic - depends_on: - - es-hot - - es-warm - - filebeat: - image: elastic/filebeat:8.7.0 - container_name: filebeat - privileged: true - user: root - command: filebeat -e -strict.perms=false - volumes: - - ./configs/filebeat.yml:/usr/share/filebeat/filebeat.yml:Z - - /var/lib/docker:/var/lib/docker:Z - - /var/run/docker.sock:/var/run/docker.sock:Z - depends_on: - - logstash - networks: - - elastic - - some_application: - image: library/python:3.9-alpine - container_name: some_app - volumes: - - ./pinger/:/opt/:Z - entrypoint: python3 /opt/run.py - -volumes: - data01: - driver: local - data02: - driver: local - data03: - driver: local - -networks: - elastic: - driver: bridge diff --git a/10-monitoring-04-elk/help/pinger/run.py b/10-monitoring-04-elk/help/pinger/run.py deleted file mode 100644 index 8ab37e664..000000000 --- a/10-monitoring-04-elk/help/pinger/run.py +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env python3 - -import logging -import random -import time - -while True: - - number = random.randrange(0, 4) - - if number == 0: - logging.info('Hello there!!') - elif number == 1: - logging.warning('Hmmm....something strange') - elif number == 2: - logging.error('OH NO!!!!!!') - elif number == 3: - logging.exception(Exception('this is exception')) - - time.sleep(1) \ No newline at end of file diff --git a/10-monitoring-05-sentry/README.md b/10-monitoring-05-sentry/README.md deleted file mode 100644 index cfe3e1494..000000000 --- a/10-monitoring-05-sentry/README.md +++ /dev/null @@ -1,53 +0,0 @@ -# Домашнее задание к занятию 16 «Платформа мониторинга Sentry» - -## Задание 1 - -Так как Self-Hosted Sentry довольно требовательная к ресурсам система, мы будем использовать Free Сloud account. - -Free Cloud account имеет ограничения: - -- 5 000 errors; -- 10 000 transactions; -- 1 GB attachments. - -Для подключения Free Cloud account: - -- зайдите на sentry.io; -- нажмите «Try for free»; -- используйте авторизацию через ваш GitHub-аккаунт; -- далее следуйте инструкциям. - -В качестве решения задания пришлите скриншот меню Projects. - -## Задание 2 - -1. Создайте python-проект и нажмите `Generate sample event` для генерации тестового события. -1. Изучите информацию, представленную в событии. -1. Перейдите в список событий проекта, выберите созданное вами и нажмите `Resolved`. -1. В качестве решения задание предоставьте скриншот `Stack trace` из этого события и список событий проекта после нажатия `Resolved`. - -## Задание 3 - -1. Перейдите в создание правил алёртинга. -2. Выберите проект и создайте дефолтное правило алёртинга без настройки полей. -3. Снова сгенерируйте событие `Generate sample event`. -Если всё было выполнено правильно — через некоторое время вам на почту, привязанную к GitHub-аккаунту, придёт оповещение о произошедшем событии. -4. Если сообщение не пришло — проверьте настройки аккаунта Sentry (например, привязанную почту), что у вас не было -`sample issue` до того, как вы его сгенерировали, и то, что правило алёртинга выставлено по дефолту (во всех полях all). -Также проверьте проект, в котором вы создаёте событие — возможно алёрт привязан к другому. -5. В качестве решения задания пришлите скриншот тела сообщения из оповещения на почте. -6. Дополнительно поэкспериментируйте с правилами алёртинга. Выбирайте разные условия отправки и создавайте sample events. - -## Задание повышенной сложности - -1. Создайте проект на ЯП Python или GO (около 10–20 строк), подключите к нему sentry SDK и отправьте несколько тестовых событий. -2. Поэкспериментируйте с различными передаваемыми параметрами, но помните об ограничениях Free учётной записи Cloud Sentry. -3. В качестве решения задания пришлите скриншот меню issues вашего проекта и пример кода подключения sentry sdk/отсылки событий. - ---- - -### Как оформить решение задания - -Выполненное домашнее задание пришлите в виде ссылки на .md-файл в вашем репозитории. - ---- diff --git a/10-monitoring-06-incident-management/README.md b/10-monitoring-06-incident-management/README.md deleted file mode 100644 index 2d6d25ed6..000000000 --- a/10-monitoring-06-incident-management/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# Домашнее задание к занятию 17 «Инцидент-менеджмент» - -## Задание - -Составьте постмортем на основе реального сбоя системы GitHub в 2018 году. - -Информацию о сбое можно изучить по ссылкам ниже: - -* [краткое описание на русском языке](https://habr.com/ru/post/427301/); -* [развёрнутое описание на английском языке](https://github.blog/2018-10-30-oct21-post-incident-analysis/). - - - - diff --git a/README.md b/README.md index 38f0af1bc..8bb53ad1c 100644 --- a/README.md +++ b/README.md @@ -1,55 +1,24 @@ -# Домашние задания по курсу «CI, мониторинг и управление конфигурациями» +Vector +========= -В этом репозитории собраны ваши домашние задания к каждой лекции. +This role can install Vector -Задачи без звёздочки обязательные. Их выполнение необходимо для получения зачёта и диплома о профессиональной переподготовке. -Задачи со звёздочкой (*) являются дополнительными или задачами повышенной сложности. Они необязательные, но их решение поможет лучше понять тему. +Example Playbook +---------------- -Любые вопросы по решению задач задавайте в учебном чате. +Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too: -## Система управления конфигурациями + - hosts: servers + roles: + - { role: vector } -1. [Введение в Ansible](./08-ansible-01-base). +License +------- -2. [Работа с Playbook](./08-ansible-02-playbook). +MIT -3. [Использование Ansible](./08-ansible-03-yandex). +Author Information +------------------ -4. [Работа с Roles](./08-ansible-04-role). - -5. [Тестирование Roles](./08-ansible-05-testing). - -6. [Создание собственных модулей](./08-ansible-06-module). - -## Непрерывная разработка и интеграция - -7. [Жизненный цикл ПО](./09-ci-01-intro/README.md). - -8. [DevOps и SRE](./09-ci-02-devops/README.md). - -9. [Процессы CI/CD](./09-ci-03-cicd/README.md). - -10. [Jenkins](./09-ci-04-jenkins/README.md). - -11. [Teamcity](./09-ci-05-teamcity/README.md). - -12. [GitLab](./09-ci-06-gitlab/README.md). - -## Системы мониторинга - -13. [Системы мониторинга](./10-monitoring-02-systems). - -14. [Средство визуализации Grafana](./10-monitoring-03-grafana). - -15. [Система сбора логов Elastic Stack](./10-monitoring-04-elk). - -16. [Платформа мониторинга Sentry](./10-monitoring-05-sentry). - -17. [Инцидент-менеджмент](/10-monitoring-06-incident-management). - - -## Дополнительные материалы к лекциям - -1. [Дополнительные материалы к лекциям по Ansible](./08-ansible-additional). -1. [Дополнительные материалы к лекциям по CI\CD](./09-ci-additional). +Vladislav Cherepanov diff --git a/defaults/main.yml b/defaults/main.yml new file mode 100644 index 000000000..70e612f87 --- /dev/null +++ b/defaults/main.yml @@ -0,0 +1,11 @@ +--- +# defaults file for vector +vector_version: "0.36.1" +vector_packages: vector +dummy_logs_type: demo_logs +dummy_logs_format: syslog +parse_logs_type: remap +print_type: console +message: it's new file +family_deb: amd64 +family_rpm: x86_64 diff --git a/handlers/main.yml b/handlers/main.yml new file mode 100644 index 000000000..e3fa8ba69 --- /dev/null +++ b/handlers/main.yml @@ -0,0 +1,14 @@ +--- +# handlers file for vector +- name: Start vector service + become: true + become_method: su + ansible.builtin.service: + name: vector + state: strated +- name: Restart vector service + become: true + become_method: su + ansible.builtin.service: + name: vector + state: restarted diff --git a/meta/main.yml b/meta/main.yml new file mode 100644 index 000000000..117706c5f --- /dev/null +++ b/meta/main.yml @@ -0,0 +1,57 @@ +galaxy_info: + author: Vladislav Cherepanov + description: install vector + company: none + role-name: vector + namespace: test + # 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: MIT + + min_ansible_version: 2.10 + + # If this a Container Enabled role, provide the minimum Ansible Container version. + # min_ansible_container_version: + + # + # Provide a list of supported platforms, and for each platform a list of versions. + # If you don't wish to enumerate all versions for a particular platform, use 'all'. + # To view available platforms and versions (or releases), visit: + # https://galaxy.ansible.com/api/v1/platforms/ + # + platforms: + - name: OracleLinux + versions: + - 8 + - name: Ubuntu + versions: + - 22.04 + - 22.10 + - 24.04 + # - name: SomePlatform + # versions: + # - all + # - 1.0 + # - 7 + # - 99.99 + + 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/tasks/centos.yml b/tasks/centos.yml new file mode 100644 index 000000000..d262437cf --- /dev/null +++ b/tasks/centos.yml @@ -0,0 +1,24 @@ +--- +# tasks file for vector +- name: update + become: true + become_method: su + ansible.builtin.yum: + name: '*' + state: latest +- name: Get vector distrib + ansible.builtin.get_url: + url: "https://packages.timber.io/vector/{{ vector_version }}/vector-{{ vector_version }}-1.x86_64.rpm" + dest: "./vector-{{ vector_version }}.rpm" +- name: Install vector packages + become: true + become_method: su + ansible.builtin.yum: + name: + - vector-{{ vector_version }}.rpm +- name: Replace vector.yaml + become: true + become_method: su + template: + src: templates/vector.yaml + dest: /etc/vector/vector.yaml diff --git a/tasks/main.yml b/tasks/main.yml new file mode 100644 index 000000000..8df35acfa --- /dev/null +++ b/tasks/main.yml @@ -0,0 +1,10 @@ +--- +# tasks file for vector +- name: CentOS + ansible.builtin.include_tasks: "centos.yml" + when: + - ansible_facts['distribution'] == "CentOS" +- name: Ubuntu + ansible.builtin.include_tasks: "ubuntu.yml" + when: + - ansible_facts['distribution'] == "Ubuntu" diff --git a/tasks/ubuntu.yml b/tasks/ubuntu.yml new file mode 100644 index 000000000..78b9317e1 --- /dev/null +++ b/tasks/ubuntu.yml @@ -0,0 +1,23 @@ +--- +# tasks file for vector +- name: update + become: true + become_method: su + ansible.builtin.apt: + name: '*' + state: latest +- name: Get vector distrib + ansible.builtin.get_url: + url: "https://packages.timber.io/vector/{{ vector_version }}/vector_{{ vector_version }}-1_{{ family_deb }}.deb" + dest: "./vector-{{ vector_version }}.deb" +- name: Install vector packages + become: true + become_method: su + ansible.builtin.apt: + deb: vector-{{ vector_version }}.deb +- name: Replace vector.yaml + become: true + become_method: su + template: + src: templates/vector.yaml + dest: /etc/vector/vector.yaml diff --git a/templates/vector.yaml b/templates/vector.yaml new file mode 100644 index 000000000..479412ff8 --- /dev/null +++ b/templates/vector.yaml @@ -0,0 +1,48 @@ +# __ __ __ +# \ \ / / / / +# \ V / / / +# \_/ \/ +# +# V E C T O R +# Configuration +# +# ------------------------------------------------------------------------------ +# Website: https://vector.dev +# Docs: https://vector.dev/docs +# Chat: https://chat.vector.dev +# ------------------------------------------------------------------------------ + +# Change this to use a non-default directory for Vector data storage: +# data_dir: "/var/lib/vector" + +# Random Syslog-formatted logs +sources: + dummy_logs: + type: "{{ dummy_logs_type }}" + format: "{{ dummy_logs_format }}" + interval: 1 + +# Parse Syslog logs +# See the Vector Remap Language reference for more info: https://vrl.dev +transforms: + parse_logs: + type: "{{ parse_logs_type }}" + inputs: ["dummy_logs"] + source: | + . = parse_syslog!(string!(.message)) + +# Print parsed logs to stdout +sinks: + print: + type: "{{ print_type }}" + inputs: ["parse_logs"] + encoding: + codec: "json" + +# Vector's GraphQL API (disabled by default) +# Uncomment to try it out with the `vector top` command or +# in your browser at http://localhost:8686 +# api: +# enabled: true +# address: "127.0.0.1:8686" +## {{ message }} \ No newline at end of file diff --git a/tests/inventory b/tests/inventory new file mode 100644 index 000000000..878877b07 --- /dev/null +++ b/tests/inventory @@ -0,0 +1,2 @@ +localhost + diff --git a/tests/test.yml b/tests/test.yml new file mode 100644 index 000000000..efbfd5b7b --- /dev/null +++ b/tests/test.yml @@ -0,0 +1,5 @@ +--- +- hosts: localhost + remote_user: root + roles: + - vector diff --git a/vars/main.yml b/vars/main.yml new file mode 100644 index 000000000..32644c712 --- /dev/null +++ b/vars/main.yml @@ -0,0 +1,3 @@ +--- +# vars file for vector +cfg_path: /etc/vector/vector.yaml