Files
prod/infra/ansible/playbook.yml
Andrey bb91e139bc Update Ansible configuration and enhance playbook
- Add UFW configuration to secure server ports
- Install additional packages including vim, zsh, and monitoring tools
- Change default shell for 'deploy' user to zsh
- Update .gitignore to include Ansible inventory files
2025-09-09 23:00:15 +03:00

286 lines
8.7 KiB
YAML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
- name: Полная миграция ботов на новый сервер
hosts: new_server
become: yes
vars:
# Основная директория проекта
project_root: "/home/prod"
# Пользователь и группа
deploy_user: "deploy"
uid: "1001"
gid: "1001"
# Старый сервер для копирования данных
old_server: "root@77.223.98.129"
# Опция: пересоздавать папку /home/prod (по умолчанию — нет)
recreate_project: false
tasks:
- name: Обновить кэш пакетов
apt:
update_cache: yes
- name: Установить необходимые пакеты
apt:
name:
- docker.io
- docker-compose
- make
- git
- python3-pip
- curl
- sshpass
- rsync
- vim
- zsh
- ufw
- htop
- iotop
- traceroute
- ncdu
state: present
- name: Включить и запустить Docker
systemd:
name: docker
enabled: yes
state: started
- name: Настроить UFW (файрвол)
ufw:
state: enabled
policy: deny
direction: incoming
rule: allow
port: "22"
proto: tcp
notify: restart ufw
- name: Открыть порты для сервисов
ufw:
rule: allow
port: "{{ item }}"
proto: tcp
loop:
- "8080" # Telegram Bot
- "8081" # AnonBot
- "9090" # Prometheus
- "3000" # Grafana
notify: restart ufw
- name: Проверить существование пользователя deploy
getent:
database: passwd
key: "{{ deploy_user }}"
register: user_exists
failed_when: false
- name: Создать группу deploy с GID 1001
group:
name: "{{ deploy_user }}"
gid: "{{ gid }}"
when: not user_exists.exists
- name: Создать пользователя deploy с UID 1001 (если не существует)
user:
name: "{{ deploy_user }}"
uid: "{{ uid }}"
group: "{{ gid }}"
shell: /bin/zsh
create_home: yes
system: no
groups: docker
append: yes
when: not user_exists.exists
- name: Установить zsh как оболочку по умолчанию для существующего пользователя deploy
user:
name: "{{ deploy_user }}"
shell: /bin/zsh
when: user_exists.exists
- name: Настроить безопасный SSH
lineinfile:
path: /etc/ssh/sshd_config
regexp: "^{{ item.regexp }}"
line: "{{ item.line }}"
backup: yes
loop:
- { regexp: "PermitRootLogin", line: "PermitRootLogin no" }
- { regexp: "PasswordAuthentication", line: "PasswordAuthentication no" }
- { regexp: "PubkeyAuthentication", line: "PubkeyAuthentication yes" }
notify: reload ssh
- name: Удалить /home/prod, если требуется (чистое развертывание)
file:
path: "{{ project_root }}"
state: absent
when: recreate_project | bool
- name: Создать директорию проекта /home/prod
file:
path: "{{ project_root }}"
state: directory
owner: "{{ deploy_user }}"
group: "{{ deploy_user }}"
mode: '0755'
- name: Настроить SSH ключи для GitHub
authorized_key:
user: "{{ deploy_user }}"
key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"
state: present
- name: Настроить SSH config для GitHub
lineinfile:
path: "/home/{{ deploy_user }}/.ssh/config"
line: "Host github.com\n StrictHostKeyChecking no\n UserKnownHostsFile /dev/null"
create: yes
owner: "{{ deploy_user }}"
group: "{{ deploy_user }}"
mode: '0600'
- name: Клонировать основной репозиторий prod
git:
repo: git@github.com:KerradKerridi/prod.git
dest: "{{ project_root }}"
clone: yes
update: yes
become: yes
become_user: "{{ deploy_user }}"
- name: Клонировать AnonBot
git:
repo: git@github.com:KerradKerridi/AnonBot.git
dest: "{{ project_root }}/bots/AnonBot"
clone: yes
update: yes
become: yes
become_user: "{{ deploy_user }}"
- name: Клонировать telegram-helper-bot
git:
repo: git@github.com:KerradKerridi/telegram-helper-bot.git
dest: "{{ project_root }}/bots/telegram-helper-bot"
clone: yes
update: yes
become: yes
become_user: "{{ deploy_user }}"
- name: Копировать .env для telegram-helper-bot со старого сервера
synchronize:
src: "ssh://{{ old_server }}/home/prod/bots/telegram-helper-bot/.env"
dest: "{{ project_root }}/bots/telegram-helper-bot/.env"
mode: pull
delegate_to: localhost
become: yes
become_user: "{{ deploy_user }}"
- name: Копировать БД для telegram-helper-bot
synchronize:
src: "ssh://{{ old_server }}/home/prod/bots/telegram-helper-bot/database/tg-bot-database.db"
dest: "{{ project_root }}/bots/telegram-helper-bot/database/"
mode: pull
delegate_to: localhost
become: yes
become_user: "{{ deploy_user }}"
- name: Копировать voice_users для telegram-helper-bot
synchronize:
src: "ssh://{{ old_server }}/home/prod/bots/telegram-helper-bot/voice_users/"
dest: "{{ project_root }}/bots/telegram-helper-bot/voice_users/"
mode: pull
delegate_to: localhost
become: yes
become_user: "{{ deploy_user }}"
- name: Копировать .env для AnonBot
synchronize:
src: "ssh://{{ old_server }}/home/prod/bots/AnonBot/.env"
dest: "{{ project_root }}/bots/AnonBot/.env"
mode: pull
delegate_to: localhost
become: yes
become_user: "{{ deploy_user }}"
- name: Копировать БД для AnonBot
synchronize:
src: "ssh://{{ old_server }}/home/prod/bots/AnonBot/database/anon_qna.db"
dest: "{{ project_root }}/bots/AnonBot/database/"
mode: pull
delegate_to: localhost
become: yes
become_user: "{{ deploy_user }}"
- name: Установить права на скопированные файлы
file:
path: "{{ item }}"
owner: "{{ deploy_user }}"
group: "{{ deploy_user }}"
mode: '0644'
loop:
- "{{ project_root }}/bots/telegram-helper-bot/.env"
- "{{ project_root }}/bots/telegram-helper-bot/database/tg-bot-database.db"
- "{{ project_root }}/bots/telegram-helper-bot/voice_users"
- "{{ project_root }}/bots/AnonBot/.env"
- "{{ project_root }}/bots/AnonBot/database/anon_qna.db"
become: yes
- name: Запустить ботов через make up
command: make up
args:
chdir: "{{ project_root }}"
become: yes
become_user: "{{ deploy_user }}"
# --- НОВОЕ: Проверка портов ---
- name: Пауза на 30 секунд — дать контейнерам запуститься
pause:
seconds: 30
- name: Проверить, что порт 8080 (Telegram Bot) открыт
wait_for:
port: 8080
host: "{{ ansible_host }}"
timeout: 30
state: started
delegate_to: localhost
- name: Проверить, что порт 8081 (AnonBot) открыт
wait_for:
port: 8081
host: "{{ ansible_host }}"
timeout: 30
state: started
delegate_to: localhost
- name: Проверить, что порт 9090 (Prometheus) открыт
wait_for:
port: 9090
host: "{{ ansible_host }}"
timeout: 30
state: started
delegate_to: localhost
- name: Проверить, что порт 3000 (Grafana) открыт
wait_for:
port: 3000
host: "{{ ansible_host }}"
timeout: 30
state: started
delegate_to: localhost
- name: Проверка запуска ботов завершена — всё работает 🟢
debug:
msg: "Все сервисы запущены и слушают нужные порты."
# handlers для перезагрузки сервисов
handlers:
- name: reload ssh
systemd:
name: ssh
state: reloaded
- name: restart ufw
ufw:
state: reloaded