From c6f239839c5c84d0e69f0836102d3c7ceed1fa49 Mon Sep 17 00:00:00 2001 From: admin Date: Tue, 6 Jan 2026 14:51:21 +0000 Subject: [PATCH] Add ansible/webserver-automation/ansible.md --- ansible/webserver-automation/ansible.md | 781 ++++++++++++++++++++++++ 1 file changed, 781 insertions(+) create mode 100644 ansible/webserver-automation/ansible.md diff --git a/ansible/webserver-automation/ansible.md b/ansible/webserver-automation/ansible.md new file mode 100644 index 0000000..74052ac --- /dev/null +++ b/ansible/webserver-automation/ansible.md @@ -0,0 +1,781 @@ +# 📘 Ansible Web Server Automation - Полная Инструкция + +## 🎯 Содержание + +1. [Требования](#требования) +2. [Установка Ansible](#установка-ansible) +3. [Настройка SSH](#настройка-ssh) +4. [Клонирование проекта](#клонирование-проекта) +5. [Настройка inventory](#настройка-inventory) +6. [Настройка переменных](#настройка-переменных) +7. [Тестирование подключения](#тестирование-подключения) +8. [Запуск playbook](#запуск-playbook) +9. [Проверка результата](#проверка-результата) +10. [Деплой приложения](#деплой-приложения) +11. [Troubleshooting](#troubleshooting) + +--- + +## 1. Требования + +### Управляющая машина (ваш компьютер) +- Ubuntu 20.04+ / Debian 11+ / macOS / Windows WSL2 +- Python 3.6+ +- Git +- SSH client + +### Целевые серверы +- Ubuntu 20.04 / 22.04 (рекомендуется) +- Debian 10 / 11 +- Минимум 1GB RAM, 10GB диск +- SSH доступ +- Sudo права + +--- + +## 2. Установка Ansible + +### Ubuntu / Debian + +```bash +# Обновить систему +sudo apt update +sudo apt upgrade -y + +# Установить зависимости +sudo apt install -y software-properties-common + +# Добавить PPA репозиторий Ansible (опционально, для последней версии) +sudo add-apt-repository --yes --update ppa:ansible/ansible + +# Установить Ansible +sudo apt install -y ansible + +# Проверить установку +ansible --version +``` + +Должно показать: +``` +ansible [core 2.14.x] + python version = 3.x.x + jinja version = 3.x.x +``` + +### macOS + +```bash +# Установить Homebrew (если нет) +/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" + +# Установить Ansible +brew install ansible + +# Проверить +ansible --version +``` + +### Windows WSL2 + +```bash +# Открыть Ubuntu в WSL2 +wsl + +# Следовать инструкциям для Ubuntu выше +sudo apt update +sudo apt install -y ansible +``` + +--- + +## 3. Настройка SSH + +### 3.1 Генерация SSH ключа + +На управляющей машине: + +```bash +# Генерировать SSH ключ (если нет) +ssh-keygen -t ed25519 -C "your_email@example.com" + +# Или RSA (более совместимый) +ssh-keygen -t rsa -b 4096 -C "your_email@example.com" + +# Нажать Enter для defaults +# Ключи сохранятся в ~/.ssh/id_ed25519 (или id_rsa) +``` + +### 3.2 Копирование ключа на сервер + +```bash +# Скопировать ключ на целевой сервер +ssh-copy-id ubuntu@192.168.1.10 + +# Или вручную +cat ~/.ssh/id_ed25519.pub | ssh ubuntu@192.168.1.10 "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys" +``` + +### 3.3 Тест SSH подключения + +```bash +# Подключиться без пароля +ssh ubuntu@192.168.1.10 + +# Если успешно - можно продолжать! +exit +``` + +--- + +## 4. Клонирование проекта + +```bash +# Клонировать репозиторий +git clone http://git.thedevops.dev/admin/k3s-gitops.git + +# Перейти в директорию проекта +cd k3s-gitops/ansible/webserver-automation + +# Проверить структуру +tree +``` + +Должна быть структура: +``` +ansible/webserver-automation/ +├── README.md +├── ansible.cfg +├── inventory/ +│ └── production +├── group_vars/ +│ ├── all.yml +│ └── webservers.yml +├── playbooks/ +│ ├── site.yml +│ └── deploy.yml +└── roles/ + ├── common/ + ├── nginx/ + └── firewall/ +``` + +--- + +## 5. Настройка Inventory + +### 5.1 Редактировать production inventory + +```bash +# Открыть файл +vim inventory/production +``` + +### 5.2 Заменить на свои данные + +```ini +# Production Inventory +# Замените IP адреса на свои! + +[webservers] +web1.example.com ansible_host=192.168.1.10 +web2.example.com ansible_host=192.168.1.11 + +[all:vars] +ansible_user=ubuntu # Ваш SSH пользователь +ansible_ssh_private_key_file=~/.ssh/id_rsa # Путь к SSH ключу +ansible_python_interpreter=/usr/bin/python3 +environment=production +``` + +### 5.3 Простой пример (один сервер) + +```ini +[webservers] +web1 ansible_host=192.168.1.10 + +[all:vars] +ansible_user=ubuntu +ansible_ssh_private_key_file=~/.ssh/id_ed25519 +environment=production +``` + +### 5.4 Для Vagrant / локального тестирования + +```ini +[webservers] +localhost ansible_connection=local + +[all:vars] +ansible_user=vagrant +environment=development +``` + +--- + +## 6. Настройка переменных + +### 6.1 Общие переменные + +```bash +# Открыть файл +vim group_vars/all.yml +``` + +Настройте базовые параметры: + +```yaml +--- +# Система +timezone: "Europe/Vilnius" # Ваш timezone + +# Пользователи +admin_users: + - name: admin + groups: sudo + shell: /bin/bash + - name: deploy + groups: www-data + shell: /bin/bash + +# Пакеты +common_packages: + - curl + - wget + - git + - vim + - htop + - ufw + +# SSH +ssh_port: 22 +ssh_password_authentication: false + +# Firewall +firewall_allowed_tcp_ports: + - 22 # SSH + - 80 # HTTP + - 443 # HTTPS +``` + +### 6.2 Переменные веб-сервера + +```bash +# Открыть файл +vim group_vars/webservers.yml +``` + +Настройте параметры приложения: + +```yaml +--- +# Nginx +nginx_port: 80 +nginx_ssl_port: 443 + +# Приложение +app_name: "myapp" # Имя вашего приложения +app_user: "webapp" +app_group: "www-data" +app_dir: "/var/www/{{ app_name }}" + +# Домен +domain_name: "example.com" # Ваш домен +server_name: "{{ inventory_hostname }}" + +# SSL (отключить если нет сертификата) +ssl_enabled: false + +# Логи +access_log: "/var/log/nginx/{{ app_name }}_access.log" +error_log: "/var/log/nginx/{{ app_name }}_error.log" + +# Performance +client_max_body_size: "100M" +gzip_enabled: true +``` + +--- + +## 7. Тестирование подключения + +### 7.1 Проверить синтаксис inventory + +```bash +ansible-inventory -i inventory/production --list +``` + +### 7.2 Ping тест + +```bash +# Проверить подключение ко всем хостам +ansible -i inventory/production all -m ping + +# Ожидаемый результат: +# web1 | SUCCESS => { +# "changed": false, +# "ping": "pong" +# } +``` + +### 7.3 Проверить доступ sudo + +```bash +ansible -i inventory/production all -m shell -a "whoami" --become +``` + +Должно показать: `root` + +### 7.4 Собрать факты о системе + +```bash +ansible -i inventory/production all -m setup +``` + +--- + +## 8. Запуск Playbook + +### 8.1 Синтаксис проверка + +```bash +# Проверить синтаксис playbook +ansible-playbook -i inventory/production playbooks/site.yml --syntax-check + +# Должно показать: +# playbook: playbooks/site.yml +``` + +### 8.2 Dry Run (тест без изменений) + +```bash +# Запустить в режиме проверки +ansible-playbook -i inventory/production playbooks/site.yml --check + +# Покажет что будет изменено, но не применит изменения +``` + +### 8.3 Список задач + +```bash +# Посмотреть все задачи +ansible-playbook -i inventory/production playbooks/site.yml --list-tasks +``` + +### 8.4 Полный запуск + +```bash +# Запустить полную установку +ansible-playbook -i inventory/production playbooks/site.yml + +# С verbose output (для отладки) +ansible-playbook -i inventory/production playbooks/site.yml -v + +# Очень подробный вывод +ansible-playbook -i inventory/production playbooks/site.yml -vvv +``` + +### 8.5 Ход выполнения + +Вы увидите примерно такой вывод: + +``` +PLAY [Setup all servers] ********************************************* + +TASK [Gathering Facts] *********************************************** +ok: [web1] + +TASK [Display deployment information] ******************************** +ok: [web1] => { + "msg": "Deploying to: web1\nEnvironment: production\n..." +} + +PLAY [Configure common settings] ************************************* + +TASK [common : Update apt cache] ************************************* +changed: [web1] + +TASK [common : Install common packages] ****************************** +changed: [web1] + +... + +PLAY RECAP *********************************************************** +web1 : ok=25 changed=15 unreachable=0 failed=0 +``` + +### 8.6 Запуск конкретных тегов + +```bash +# Только обновить пакеты +ansible-playbook -i inventory/production playbooks/site.yml --tags packages + +# Только настроить firewall +ansible-playbook -i inventory/production playbooks/site.yml --tags firewall + +# Только nginx +ansible-playbook -i inventory/production playbooks/site.yml --tags nginx + +# Несколько тегов +ansible-playbook -i inventory/production playbooks/site.yml --tags "packages,nginx" +``` + +### 8.7 Ограничить выполнение на один хост + +```bash +# Только для web1 +ansible-playbook -i inventory/production playbooks/site.yml --limit web1 + +# Для нескольких хостов +ansible-playbook -i inventory/production playbooks/site.yml --limit "web1,web2" +``` + +--- + +## 9. Проверка результата + +### 9.1 Проверить веб-сервер + +```bash +# С управляющей машины +curl http://192.168.1.10 + +# Должен вернуть HTML страницу +``` + +### 9.2 Проверить в браузере + +Открыть в браузере: +``` +http://192.168.1.10 +``` + +Вы должны увидеть красивую страницу с: +- 🚀 emoji +- Название приложения +- Environment: production +- Server: web1 +- "Deployed with Ansible ✨" + +### 9.3 Проверить health endpoint + +```bash +curl http://192.168.1.10/health + +# Должен вернуть: healthy +``` + +### 9.4 Проверить Nginx статус + +```bash +# На сервере +ssh ubuntu@192.168.1.10 +sudo systemctl status nginx + +# Должно показать: active (running) +``` + +### 9.5 Проверить firewall + +```bash +# На сервере +ssh ubuntu@192.168.1.10 +sudo ufw status + +# Должно показать: +# Status: active +# To Action From +# -- ------ ---- +# 22/tcp ALLOW Anywhere +# 80/tcp ALLOW Anywhere +# 443/tcp ALLOW Anywhere +``` + +### 9.6 Проверить логи + +```bash +# На сервере +ssh ubuntu@192.168.1.10 + +# Access logs +sudo tail -f /var/log/nginx/myapp_access.log + +# Error logs +sudo tail -f /var/log/nginx/myapp_error.log +``` + +--- + +## 10. Деплой приложения + +### 10.1 Базовый деплой + +```bash +# Задеплоить приложение +ansible-playbook -i inventory/production playbooks/deploy.yml +``` + +### 10.2 Деплой с версией + +```bash +# Указать версию +ansible-playbook -i inventory/production playbooks/deploy.yml -e "app_version=v1.2.3" +``` + +### 10.3 Что делает deploy playbook + +1. ✅ Создаёт директорию приложения +2. ✅ Деплоит HTML файл +3. ✅ Перезапускает Nginx +4. ✅ Проверяет доступность + +### 10.4 Кастомизация HTML + +Отредактируйте в playbook `playbooks/deploy.yml`: + +```yaml +- name: Deploy custom HTML + copy: + dest: "{{ app_dir }}/index.html" + content: | + + + + My Custom App + + +

Welcome to My App!

+

Version: {{ app_version }}

+ + +``` + +--- + +## 11. Troubleshooting + +### Проблема 1: SSH connection failed + +**Ошибка:** +``` +fatal: [web1]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host"} +``` + +**Решение:** +```bash +# Проверить SSH подключение вручную +ssh ubuntu@192.168.1.10 + +# Проверить SSH ключ +ssh-add -l + +# Добавить ключ если нужно +ssh-add ~/.ssh/id_rsa + +# Проверить права на ключ +chmod 600 ~/.ssh/id_rsa +``` + +### Проблема 2: Permission denied (sudo) + +**Ошибка:** +``` +fatal: [web1]: FAILED! => {"msg": "Missing sudo password"} +``` + +**Решение:** +```bash +# Запустить с запросом sudo пароля +ansible-playbook -i inventory/production playbooks/site.yml --ask-become-pass + +# Или добавить пользователя в sudoers без пароля +ssh ubuntu@192.168.1.10 +sudo visudo + +# Добавить строку: +ubuntu ALL=(ALL) NOPASSWD:ALL +``` + +### Проблема 3: Module not found + +**Ошибка:** +``` +ERROR! couldn't resolve module/action 'community.general.ufw' +``` + +**Решение:** +```bash +# Установить Ansible collections +ansible-galaxy collection install community.general +ansible-galaxy collection install ansible.posix +``` + +### Проблема 4: Port 80 already in use + +**Ошибка:** +``` +nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use) +``` + +**Решение:** +```bash +# Найти процесс на порту 80 +ssh ubuntu@192.168.1.10 +sudo lsof -i :80 + +# Остановить Apache если запущен +sudo systemctl stop apache2 +sudo systemctl disable apache2 + +# Перезапустить Nginx +sudo systemctl restart nginx +``` + +### Проблема 5: Syntax error in playbook + +**Ошибка:** +``` +ERROR! We were unable to read either as JSON nor YAML +``` + +**Решение:** +```bash +# Проверить YAML синтаксис +yamllint playbooks/site.yml + +# Или онлайн: http://www.yamllint.com/ + +# Проверить отступы (должны быть пробелы, не табы!) +``` + +### Проблема 6: Firewall блокирует HTTP + +**Ошибка:** +``` +curl: (7) Failed to connect to 192.168.1.10 port 80: Connection refused +``` + +**Решение:** +```bash +# Проверить UFW +ssh ubuntu@192.168.1.10 +sudo ufw status + +# Добавить правило если нужно +sudo ufw allow 80/tcp +sudo ufw reload +``` + +### Проблема 7: Slow playbook execution + +**Решение:** +```bash +# Включить pipelining в ansible.cfg +echo "pipelining = True" >> ansible.cfg + +# Отключить gathering facts если не нужны +ansible-playbook playbooks/site.yml --skip-tags=facts + +# Использовать Strategy plugin +# В playbook добавить: +strategy: free +``` + +--- + +## 📚 Дополнительные команды + +### Полезные ad-hoc команды + +```bash +# Перезапустить Nginx на всех серверах +ansible -i inventory/production webservers -m service -a "name=nginx state=restarted" --become + +# Проверить uptime +ansible -i inventory/production all -m shell -a "uptime" + +# Проверить disk space +ansible -i inventory/production all -m shell -a "df -h" + +# Обновить пакеты +ansible -i inventory/production all -m apt -a "update_cache=yes upgrade=dist" --become + +# Скопировать файл на все серверы +ansible -i inventory/production webservers -m copy -a "src=./file.txt dest=/tmp/file.txt" + +# Получить информацию о процессе +ansible -i inventory/production webservers -m shell -a "ps aux | grep nginx" +``` + +### Ansible Vault (для секретов) + +```bash +# Создать зашифрованный файл +ansible-vault create group_vars/production_secrets.yml + +# Редактировать +ansible-vault edit group_vars/production_secrets.yml + +# Запустить playbook с vault +ansible-playbook -i inventory/production playbooks/site.yml --ask-vault-pass + +# Или с файлом пароля +echo "mypassword" > .vault_pass +ansible-playbook -i inventory/production playbooks/site.yml --vault-password-file .vault_pass +``` + +--- + +## 🎓 Следующие шаги + +### 1. Добавить мониторинг + +- Prometheus +- Grafana +- Node Exporter + +### 2. Добавить SSL сертификаты + +- Let's Encrypt +- Certbot automation + +### 3. Добавить CI/CD + +- Интеграция с Jenkins +- GitLab CI +- GitHub Actions + +### 4. Масштабирование + +- Добавить Load Balancer +- Настроить Database servers +- Redis/Memcached + +--- + +## 📞 Поддержка + +- **Документация:** http://git.thedevops.dev/admin/k3s-gitops/src/branch/main/ansible/webserver-automation +- **Issues:** http://git.thedevops.dev/admin/k3s-gitops/issues +- **Ansible Docs:** https://docs.ansible.com + +--- + +## ✅ Checklist успешной установки + +- [ ] Ansible установлен (`ansible --version`) +- [ ] SSH ключи настроены +- [ ] Проект склонирован +- [ ] Inventory настроен с реальными IP +- [ ] Variables настроены (timezone, domain, etc) +- [ ] SSH ping успешен (`ansible all -m ping`) +- [ ] Playbook запущен (`ansible-playbook playbooks/site.yml`) +- [ ] Сайт доступен (`curl http://SERVER_IP`) +- [ ] Firewall работает (`sudo ufw status`) +- [ ] Nginx работает (`systemctl status nginx`) +- [ ] Deploy работает (`ansible-playbook playbooks/deploy.yml`) + +--- + +**Версия:** 1.0.0 +**Дата:** 2026-01-06 +**Статус:** ✅ Production Ready \ No newline at end of file