Compare commits

...

12 Commits

Author SHA1 Message Date
Sergey Antropoff 83b47dbc30 fix: пересборка output/index.html при uninstall с LIMIT
Второй play перенесён на hysteria2_servers с run_once на localhost,
чтобы LIMIT не пропускал пересборку. Пустой index.html удаляется.
2026-07-01 13:31:28 +03:00
Sergey Antropoff 4b5a1ef51f Полная очистка при uninstall: VPS и output/<server>/
Скрипт --remove снимает только бинарник и systemd; Ansible дочищает конфиг,
пользователя, ufw, пакеты и всегда удаляет локальную папку экспорта.
2026-07-01 13:28:59 +03:00
Sergey Antropoff bdc316efac fix: run only uninstall tasks, not full role on make uninstall
Tagging the whole role with uninstall caused install/configure/update/export to run first. Use include_role tasks_from uninstall.yml; add safe defaults for uninstall variables.
2026-07-01 13:20:17 +03:00
Sergey Antropoff 01198b4f77 docs: update README for Salamander branch features
Mirror main documentation: install script sync, incremental update/export, uninstall, vault wiring, Makefile and role structure.
2026-07-01 13:16:38 +03:00
Sergey Antropoff 0745fdce2c feat: incremental user passwords and export on update
Preserve passwords from server-info.yml and vault; generate only for new users; remove deleted users from output; re-export URL/QR only when password, domain, port, obfs or files changed.
2026-07-01 13:06:33 +03:00
Sergey Antropoff 5e42d60778 feat: complete uninstall cleanup on server and local output
Remove binary, config, masq, system user, ufw rules, and apt packages from VPS; delete output/<server>/ by default and rebuild global index.html via localhost play.
2026-07-01 12:56:20 +03:00
Sergey Antropoff b9e622e5c2 feat: bundle and sync official Hysteria2 install script locally
Store install_server.sh in role files, compare SHA256 with get.hy2.sh on the control node before install/update, refresh the bundled copy when upstream changes, then copy and run it on VPS.
2026-07-01 12:00:37 +03:00
Sergey Antropoff 2f88108a8d fix: disable become on localhost play and drop deprecated facts
Use now() for export timestamps and ansible_facts['system'] for browser detection. Set become: false on the localhost play to avoid sudo on local fact gathering.
2026-07-01 11:56:18 +03:00
Sergey Antropoff 4242093ca1 fix: generate VPN passwords without pwgen, set EDITOR=nano
Use Ansible password lookup on the control node so install works before packages are installed on VPS and without pwgen on macOS. Export EDITOR=nano in Makefile for vault-edit.
2026-07-01 11:43:34 +03:00
Sergey Antropoff e3d3103dc2 fix: replace removed yaml callback with default + result_format
community.general.yaml was removed in collection 12.0; use ansible.builtin.default with result_format=yaml for Ansible 2.13+.
2026-07-01 11:09:08 +03:00
Sergey Antropoff 63b21d5df6 Align README with main branch: branches comparison, ACME renewal, switching.
Unified documentation structure across main and salamander branches.
2026-07-01 02:22:28 +03:00
Sergey Antropoff 0aec9e6e54 Add Salamander obfs branch: replace masquerade with packet obfuscation.
- ACME TLS challenge on 443 (no port 80 or nginx decoy)
- Auto-generate and persist obfs password per server
- Update client export, HTML catalog, and vault examples
- Document Salamander vs main and ACME auto-renewal in README
2026-07-01 02:17:22 +03:00
31 changed files with 2093 additions and 215 deletions
+4 -2
View File
@@ -5,6 +5,8 @@
SHELL := /bin/bash
.DEFAULT_GOAL := help
export EDITOR="nano"
ANSIBLE ?= ansible-playbook
ANSIBLE_ADHOC ?= ansible
INVENTORY ?= inventory/hosts.yml
@@ -46,7 +48,7 @@ help: ## Показать справку
@echo " make install"
@echo " make install LIMIT=vps-de"
@echo " make update LIMIT=vps-nl"
@echo " make uninstall LIMIT=vps-de EXTRA_VARS='hysteria2_uninstall_remove_local_output=true'"
@echo " make uninstall LIMIT=vps-de"
@echo ""
init: ## Создать inventory, group_vars и .vault_pass из примеров
@@ -83,7 +85,7 @@ update: check ## Обновить бинарник, перекатить кон
export: check ## Только перевыпустить URL и QR (без изменений на сервере)
$(ANSIBLE) playbook.yml --tags export $(ANSIBLE_OPTS)
uninstall: ## Удалить Hysteria2 с VPS
uninstall: ## Полностью удалить Hysteria2 с VPS (только uninstall, без install/update)
@echo "$(YELLOW)Будет выполнено удаление Hysteria2$(NC) $(if $(LIMIT),на $(LIMIT),на всех серверах)"
@read -p "Продолжить? [y/N] " c; [[ "$$c" =~ ^[Yy]$$ ]] || exit 1
$(ANSIBLE) playbook-uninstall.yml --tags uninstall $(ANSIBLE_OPTS)
+340 -58
View File
@@ -1,48 +1,97 @@
# Ansible-роль: Hysteria2 Server
# Hysteria2 Ansible — ветка **Salamander**
Ansible-роль для установки [Hysteria 2](https://v2.hysteria.network/) на Debian/Ubuntu VPS: ACME-сертификат, masquerade под nginx, несколько пользователей, экспорт URL/QR и HTML-каталог.
> **Ветка:** `salamander`
> **Режим:** **Salamander obfs** — запутывание пакетов для обхода DPI
> **Основная ветка:** [`main`](https://git.antropoff.ru/DevOpsTools/hysteria2/src/branch/main) — masquerade под HTTPS-сайт nginx
Ansible-роль для установки [Hysteria 2](https://v2.hysteria.network/) на Debian/Ubuntu VPS с **Salamander obfs** — когда masquerade под «обычный сайт» недостаточен.
---
## Выбор ветки: `main` или `salamander`
| | **`main`** | **`salamander` (эта ветка)** |
|---|---|---|
| Маскировка | HTTPS-сайт nginx + Let's Encrypt | **Salamander obfs** — пакеты выглядят как шум |
| Порт 80/tcp | **Нужен** (ACME HTTP + masquerade) | **Не нужен** |
| ACME | `type: http` | `type: tls` (TLS-ALPN на 443) |
| Сайт-заглушка | `/var/www/masq` (nginx welcome) | **Нет** |
| Obfs-пароль | — | **Обязателен** (один на сервер) |
| URI клиента | `hysteria2://user:pass@domain:443` | + `obfs=salamander&obfs-password=...` |
| Лучше когда | Нужен «легитимный» сайт в браузере | Агрессивный DPI, блокировка QUIC fingerprint |
### Когда выбирать `salamander`
- masquerade из `main` **блокируют** или распознают по fingerprint;
- не нужен фейковый сайт в браузере;
- готовы хранить **дополнительный** obfs-пароль.
### Когда выбирать `main`
- нужен **нормальный HTTPS-сайт** при открытии домена;
- достаточно маскировки под nginx;
- хотите **минимум параметров** в URI клиента.
---
## Быстрый старт
```bash
cd ~/Разработка/hysteria2
git clone https://git.antropoff.ru/DevOpsTools/hysteria2.git
cd hysteria2
git checkout salamander
make init # inventory, group_vars, vault, .vault_pass
# macOS: установить Ansible (если ещё нет)
brew install ansible
make init
# отредактировать:
# inventory/hosts.yml
# group_vars/all.yml
# group_vars/hysteria2_servers/vault.yml
# group_vars/hysteria2_servers/vars.yml (проброс vault → роль)
make vault-encrypt # зашифровать пароли VPS
make ping # проверить SSH
make install # установка → output/ → браузер откроется сам
make vault-encrypt
make ping
make install # → output/index.html откроется в браузере
```
После `make init` создаются локальные файлы из `.example` (не коммитятся). Пароль vault хранится в `.vault_pass`.
---
## Makefile
| Команда | Описание |
|---|---|
| `make help` | Справка |
| `make init` | Создать конфиги из `.example` |
| `make init` | Создать конфиги из `.example` и `.vault_pass` |
| `make check` | Проверить синтаксис playbook |
| `make ping` | Проверить SSH к VPS |
| `make status` | `systemctl status hysteria-server` |
| `make install` | Установка + экспорт + `output/index.html` + открытие в браузере |
| `make update` | Обновить бинарник, конфиг, перевыпустить экспорт |
| `make export` | Только экспорт URL/QR/HTML |
| `make uninstall` | Удалить Hysteria2 с VPS |
| `make vault-encrypt` | Зашифровать vault |
| `make vault-edit` | Редактировать vault |
### Примеры
| `make install` | Установка Salamander + экспорт URL/QR/HTML |
| `make update` | Обновить бинарник и конфиг; экспорт только для новых/изменённых пользователей |
| `make export` | Только экспорт (URL, QR, HTML) без изменений на сервере |
| `make uninstall` | Полное удаление с VPS + `output/<server>/` + пересборка `output/index.html` |
| `make vault-init` | Создать `.vault_pass`, включить `vault_password_file` в `ansible.cfg` |
| `make vault-encrypt` | Зашифровать `vault.yml` |
| `make vault-edit` | Редактировать vault (редактор **nano**, см. `EDITOR` в Makefile) |
| `make vault-view` | Показать расшифрованный vault |
```bash
make install LIMIT=vps-de
make update LIMIT=vps-nl
make export
make uninstall LIMIT=vps-de EXTRA_VARS='hysteria2_uninstall_remove_local_output=true'
make install EXTRA_VARS='hysteria2_open_browser=false' # без авто-открытия браузера
make uninstall LIMIT=vps-de
make update EXTRA_VARS='hysteria2_force_export=true' # перевыпустить URL/QR для всех
make install EXTRA_VARS='hysteria2_open_browser=false'
make update EXTRA_VARS='hysteria2_wait_for_acme=false'
```
`LIMIT` — имя хоста из `inventory/hosts.yml` (например `vps-de`).
---
## Inventory
```yaml
@@ -55,7 +104,7 @@ all:
ansible_port: 2222 # SSH-порт (если не 22)
ansible_user: root
ansible_password: "{{ vault_ssh_passwords['vps-de'] }}"
hysteria2_domain: vpn-de.example.com
hysteria2_domain: vpn-de.example.com # для TLS/SNI и ACME
hysteria2_users:
- my
- friend
@@ -70,7 +119,7 @@ all:
- bob
```
### SSH-подключение к VPS
### SSH (VPS)
| Параметр | Где | Описание |
|---|---|---|
@@ -78,7 +127,7 @@ all:
| `ansible_port` | inventory | SSH-порт (по умолчанию `22`) |
| `ansible_user` | inventory | Пользователь SSH (обычно `root`) |
| `ansible_password` | inventory + vault | Пароль из `vault_ssh_passwords` |
| `ansible_ssh_private_key_file` | inventory | Альтернатива паролю — SSH-ключ |
| `ansible_ssh_private_key_file` | inventory | Альтернатива — SSH-ключ |
```yaml
# group_vars/hysteria2_servers/vault.yml
@@ -89,9 +138,59 @@ vault_ssh_passwords:
Ключи в `vault_ssh_passwords` совпадают с **именами хостов** в inventory.
## Пароли VPN-пользователей
---
1. **Vault** (рекомендуется):
## Как работает Salamander в этом проекте
### Сервер (`/etc/hysteria/config.yaml`)
```yaml
listen: 0.0.0.0:443
acme:
type: tls # сертификат без порта 80
domains:
- vpn-de.example.com
email: admin@example.com
auth:
type: userpass
userpass:
my: "..."
friend: "..."
obfs:
type: salamander
salamander:
password: "общий_obfs_пароль_сервера"
```
### Клиент (генерируется автоматически)
```yaml
server: vpn-de.example.com:443
auth: my:password
obfs:
type: salamander
salamander:
password: общий_obfs_пароль_сервера
```
### URI (пример)
```
hysteria2://my:password@vpn-de.example.com:443?obfs=salamander&obfs-password=OBFS_PASS#my
```
Роль вызывает `hysteria share` — URI и QR уже содержат параметры Salamander.
---
## Пароли
### VPN-пользователи (`userpass`)
1. **Vault (рекомендуется):**
```yaml
vault_hysteria2_user_passwords:
@@ -99,54 +198,161 @@ vault_hysteria2_user_passwords:
friend: "Aingae0Okit1eek4eeZahFohVei4akee"
```
2. **Per-host в inventory**:
Подключается через `group_vars/hysteria2_servers/vars.yml`:
```yaml
hysteria2_user_passwords: "{{ vault_hysteria2_user_passwords[inventory_hostname] | default({}) }}"
```
2. **Per-host в inventory:**
```yaml
hysteria2_user_passwords:
friend: "custom-password"
```
3. **Автогенерация**`pwgen -s 40`, если пароль не задан.
3. **Автогенерация**Ansible `password` lookup, если пароль не задан ни в inventory/vault, ни в `output/<server>/server-info.yml`.
При `make update` пароли подтягиваются из `output/<server>/server-info.yml`, если не указаны в vault/inventory.
При `make update` / `make export`:
- **существующие** пользователи сохраняют пароли из `server-info.yml` (и URL/QR, если домен/порт/obfs не менялись);
- **новые** получают автогенерацию и полный экспорт;
- **удалённые** из inventory убираются из конфига Hysteria2 и из `output/<server>/`.
### Salamander obfs (один на сервер)
1. **Vault (рекомендуется):**
```yaml
vault_hysteria2_obfs_passwords:
vps-de: "cry_me_a_r1ver_salamander_obfs"
```
Подключается через `group_vars/hysteria2_servers/vars.yml`:
```yaml
hysteria2_obfs_password: "{{ vault_hysteria2_obfs_passwords[inventory_hostname] | default('') }}"
```
2. **Авто:** Ansible `password` lookup (`hysteria2_obfs_password_length`) при первой установке
3. **При update/export:** загружается из `output/<server>/server-info.yml` (как VPN-пароли)
> **Важно:** obfs-пароль на сервере и клиенте должен **совпадать**. При `make update` без vault пароль сохраняется из предыдущего экспорта.
Принудительно перевыпустить URL/QR для всех VPN-пользователей: `hysteria2_force_export: true`.
### Добавить / удалить пользователя
1. Отредактируйте `hysteria2_users` в `inventory/hosts.yml`.
2. Запустите `make update LIMIT=<хост>`.
Пароли и obfs существующих клиентов **не меняются** (из `server-info.yml`).
Новому пользователю генерируется пароль и создаются URL/QR с параметрами Salamander.
Удалённый пользователь пропадает из конфига и из `output/<server>/`.
---
## Установка бинарника Hysteria2
Официальный скрипт `install_server.sh` хранится в `roles/hysteria2/files/`.
Перед `make install` / `make update` на **control node**:
1. Скачивается копия с https://get.hy2.sh/
2. Сравнивается SHA256 с локальным файлом в роли
3. При отличии — локальная копия обновляется
4. Скрипт копируется на VPS и запускается оттуда
---
## `make update` — что меняется
| Компонент | Поведение |
|---|---|
| Бинарник `hysteria` | Обновляется (`install_server.sh --force`) |
| `/etc/hysteria/config.yaml` | Перекатывается (auth + obfs) |
| Пароли VPN / obfs | Сохраняются для существующей конфигурации |
| URL / QR | Только для новых, изменённых или при `hysteria2_force_export=true` |
| `apt upgrade` | **Не** выполняется |
| Ожидание ACME | **Не** выполняется |
---
## `make uninstall` — полная очистка
На **VPS** (официальный `install_server.sh --remove` + дочистка Ansible):
- бинарник `/usr/local/bin/hysteria` и unit-файлы systemd;
- `/etc/hysteria/` (конфиг и ACME);
- `/var/lib/hysteria` и пользователь `hysteria`;
- symlink'и `multi-user.target.wants/hysteria-server*`;
- временные `/tmp/hysteria-client-*.yaml`;
- правила ufw: `443/tcp`, `443/udp` (порт из `hysteria2_listen_port`);
- пакеты `curl`, `micro`, `qrencode`.
На **control node**:
- удаляется `output/<имя_сервера>/`;
- пересобирается общий `output/index.html` (сервер убирается из списка; при `LIMIT=...` тоже);
- если серверов не осталось — `output/index.html` удаляется.
---
## Let's Encrypt — обновление сертификата
**Да, Hysteria2 обновляет сертификат автоматически.**
При блоке `acme:` в конфиге встроенный ACME-клиент Hysteria2 сам получает и **продлевает** сертификат Let's Encrypt (срок ~90 дней). Повторный `make install` или certbot для продления **не нужны** — процесс `hysteria-server` делает это сам.
**Условия для авто-продления (ветка `salamander`):**
- сервер **запущен** и доступен из интернета;
- домен указывает на IP VPS;
- порт **443/tcp** открыт (ACME TLS-ALPN challenge);
- конфиг `acme` не удалён.
Проверка логов: `journalctl -u hysteria-server -f`
---
## Firewall
По умолчанию открываются только порты Hysteria2:
- **443/tcp**
- **443/udp**
**Порт 80 не используется** — в отличие от ветки `main`.
---
## Результат: папка `output/`
```
output/
├── index.html ← общий каталог всех серверов (открывается в браузере)
├── index.html ← все серверы (открывается в браузере)
├── vps-de/
│ ├── index.html ← страница сервера
│ ├── my.url
│ ├── index.html ← страница сервера + obfs-пароль
│ ├── my.url ← URI с obfs=salamander
│ ├── my.png ← QR PNG
│ ├── my.qr.txt ← QR ASCII
│ ├── my.txt
│ └── server-info.yml
│ └── server-info.yml ← mode, obfs_password, users
└── vps-nl/
└── ...
```
### HTML-страницы
HTML-страницы показывают:
**`output/index.html`** — общий каталог:
- все серверы и пользователи на одной странице
- навигация по серверам
- поля ссылки/пароля с кнопкой копирования
- QR-коды
- ссылки на файлы и страницы серверов
**`output/<server>/index.html`** — страница одного сервера (тот же стиль, все пользователи сервера).
- режим **Salamander** и **obfs-password** с кнопкой копирования;
- пароль и URL каждого пользователя;
- QR-коды;
- ссылки на файлы и страницы серверов.
После `make install`, `make update` и `make export` **`output/index.html` автоматически открывается в браузере** (macOS: `open`, Linux: `xdg-open`).
Отключить авто-открытие:
Отключить: `hysteria2_open_browser: false` в `group_vars/all.yml` или `EXTRA_VARS`.
```yaml
# group_vars/all.yml
hysteria2_open_browser: false
```
Или: `make install EXTRA_VARS='hysteria2_open_browser=false'`
---
## QR-коды
@@ -158,29 +364,105 @@ PNG генерируются средствами Ansible (без Python):
ASCII QR — `hysteria share --qr``user.qr.txt`.
---
## Переменные
| Переменная | Где | Описание |
|---|---|---|
| `hysteria2_domain` | host | Домен с A-записью на IP |
| `hysteria2_users` | host | Список имён VPN-пользователей |
| `hysteria2_acme_email` | group | Email для Let's Encrypt |
| `hysteria2_user_passwords` | host/vault | Свои пароли VPN |
| `hysteria2_output_dir` | group | Папка экспорта (по умолчанию `./output`) |
| `hysteria2_output_name` | host | Имя подпапки (по умолчанию `inventory_hostname`) |
| `hysteria2_mode` | defaults | `salamander` (информативно) |
| `hysteria2_domain` | host | Домен для TLS/SNI/ACME |
| `hysteria2_users` | host | VPN-пользователи |
| `hysteria2_acme_email` | group | Email Let's Encrypt |
| `hysteria2_user_passwords` | host/vault | Фиксированные пароли VPN |
| `hysteria2_password_length` | group | Длина автопароля VPN (40) |
| `hysteria2_force_export` | group | Перегенерировать URL/QR для всех (`false`) |
| `hysteria2_obfs_password` | host/vault | Пароль Salamander (или авто) |
| `hysteria2_obfs_password_length` | group | Длина автопароля obfs (32) |
| `hysteria2_output_dir` | group | Папка экспорта (`./output`) |
| `hysteria2_listen_port` | group | Порт (443) |
| `hysteria2_upgrade_system` | group | `apt upgrade` перед install |
| `hysteria2_configure_firewall` | group | Открыть порты в ufw |
| `hysteria2_generate_qr_png` | group | PNG QR через `qrencode` |
| `hysteria2_wait_for_acme` | group | Пауза при первом ACME |
| `hysteria2_open_browser` | group | Открыть `output/index.html` после экспорта |
| `hysteria2_uninstall_remove_local_output` | extra-vars | Удалить `output/<server>/` при uninstall |
| `hysteria2_uninstall_rebuild_global_index` | group | Пересобрать `output/index.html` после uninstall (`true`) |
| `vault_ssh_passwords` | vault | SSH-пароли root |
| `vault_hysteria2_user_passwords` | vault | VPN-пароли по серверам |
| `vault_hysteria2_obfs_passwords` | vault | obfs-пароли по серверам |
Полный список: `roles/hysteria2/defaults/main.yml`, `defaults/uninstall.yml`.
---
## Безопасность
- `output/` содержит пароли и URL — в `.gitignore`
- `output/` содержит пароли, obfs-ключи и URL — **не коммитить** (в `.gitignore`)
- `inventory/hosts.yml`, `vault.yml`, `.vault_pass` — не коммитить
- После `make init` выполните `make vault-encrypt`
- Salamander **не делает** вас невидимым: IP VPS и UDP-поток всё ещё можно анализировать
---
## Требования
- Ansible 2.14+
- Debian/Ubuntu VPS с sudo
- Домен с A-записью на IP сервера
- Для авто-открытия браузера: macOS или Linux с `xdg-open`
- **Control node:** macOS или Linux с Ansible **2.14+** (`brew install ansible` на Mac)
- **VPS:** Debian/Ubuntu с sudo
- Домен с A-записью на IP (для ACME TLS)
- Порт **443/tcp+udp** доступен с интернета
- Клиент Hysteria2 с поддержкой Salamander (Shadowrocket, NekoBox, Hiddify и др.)
- Для авто-открытия браузера: macOS (`open`) или Linux (`xdg-open`)
---
## Структура роли
```
roles/hysteria2/
├── defaults/
│ ├── main.yml
│ └── uninstall.yml
├── files/
│ └── install_server.sh
├── tasks/
│ ├── main.yml
│ ├── validate.yml
│ ├── users.yml
│ ├── obfs.yml ← пароль Salamander obfs
│ ├── sync_install_script.yml
│ ├── install.yml
│ ├── configure.yml ← Salamander, без masquerade
│ ├── update.yml
│ ├── export_prepare.yml
│ ├── export.yml
│ ├── export_global.yml
│ ├── share_user.yml
│ ├── reuse_export_user.yml
│ └── uninstall.yml
└── templates/
├── config.yaml.j2 ← acme tls + obfs salamander
├── client.yaml.j2
└── export/
```
---
## Переключение между ветками
```bash
git fetch origin
git checkout main # masquerade + nginx
git checkout salamander # Salamander obfs (эта ветка)
```
Конфиги на **уже установленном** сервере **не меняются** при переключении ветки в git.
Чтобы применить другой режим на VPS:
```bash
git checkout main # или salamander
make install # перекатит конфиг сервера
# или
make update
```
> Переключение режима **меняет** `/etc/hysteria/config.yaml` на сервере. Клиентские URI/QR нужно **перевыпустить** (`make export` или `make update`).
+2 -1
View File
@@ -3,7 +3,8 @@ inventory = inventory/hosts.yml
roles_path = roles
host_key_checking = False
retry_files_enabled = False
stdout_callback = yaml
stdout_callback = default
result_format = yaml
interpreter_python = auto_silent
[privilege_escalation]
+6 -3
View File
@@ -2,7 +2,7 @@
# Email для Let's Encrypt (ACME)
hysteria2_acme_email: admin@example.com
# Длина автогенерируемых паролей (pwgen)
# Длина автогенерируемых паролей VPN-пользователей
hysteria2_password_length: 40
# Обновлять систему перед установкой (apt update && apt upgrade)
@@ -17,8 +17,11 @@ hysteria2_output_dir: "{{ playbook_dir }}/output"
# Открывать output/index.html в браузере после install/update/export
# hysteria2_open_browser: true
# Порт Hysteria2
# Порт Hysteria2 (Salamander — достаточно открыть только его, 80/tcp не нужен)
hysteria2_listen_port: 443
# Открывать порты в ufw (80/tcp, 443/tcp, 443/udp)
# Открывать порты в ufw ({{ hysteria2_listen_port }}/tcp и /udp)
hysteria2_configure_firewall: true
# Длина пароля Salamander obfs
# hysteria2_obfs_password_length: 32
@@ -3,3 +3,7 @@
# Файл group_vars/hysteria2_servers/vault.yml должен быть зашифрован (make vault-encrypt).
# Проброс VPN-паролей из vault в переменные роли (опционально)
hysteria2_user_passwords: "{{ vault_hysteria2_user_passwords[inventory_hostname] | default({}) }}"
# Опционально: фиксированный пароль Salamander obfs для сервера
# hysteria2_obfs_password: "{{ vault_hysteria2_obfs_passwords[inventory_hostname] | default('') }}"
@@ -14,5 +14,8 @@ vault_ssh_passwords:
# vault_hysteria2_user_passwords:
# vps-de:
# friend: "Aingae0Okit1eek4eeZahFohVei4akee"
# vps-nl:
# alice: "CustomAlicePassword40chars................"
# Опционально: пароль Salamander obfs (один на сервер)
# vault_hysteria2_obfs_passwords:
# vps-de: "cry_me_a_r1ver_salamander_obfs_pass"
# vps-nl: "another_obfs_password_32chars!!"
+23 -2
View File
@@ -2,6 +2,27 @@
- name: Uninstall Hysteria2 servers
hosts: hysteria2_servers
gather_facts: false
roles:
- role: hysteria2
tags: [uninstall]
tasks:
- name: Run Hysteria2 uninstall tasks only
ansible.builtin.include_role:
name: hysteria2
tasks_from: uninstall.yml
- name: Rebuild global output index after uninstall
hosts: hysteria2_servers
gather_facts: false
tags: [uninstall]
tasks:
- name: Regenerate output/index.html without removed server
block:
- name: Run global export tasks
ansible.builtin.include_role:
name: hysteria2
tasks_from: export_global.yml
vars:
hysteria2_open_browser: false
run_once: true
delegate_to: localhost
become: false
when: hysteria2_uninstall_rebuild_global_index | default(true) | bool
+1
View File
@@ -9,6 +9,7 @@
hosts: localhost
connection: local
gather_facts: true
become: false
tags: [install, update, export]
tasks:
- name: Generate global index.html and open in browser
+25 -12
View File
@@ -1,5 +1,8 @@
---
# Домен сервера (A-запись → IP VPS). Задаётся per-host в inventory.
# Режим развёртывания (ветка salamander)
hysteria2_mode: salamander
# Домен сервера (A-запись → IP VPS). Используется для TLS/SNI и ACME.
hysteria2_domain: ""
# Email для ACME / Let's Encrypt
@@ -9,34 +12,44 @@ hysteria2_acme_email: ""
hysteria2_users: []
# Опционально: фиксированные пароли { username: password }
# Пустое значение или отсутствие ключа — автогенерация через pwgen
# Пароль обфускации Salamander (общий для сервера).
# Пусто — автогенерация на control node (Ansible password lookup) или загрузка из output/<server>/server-info.yml
hysteria2_obfs_password: ""
hysteria2_password_length: 40
hysteria2_obfs_password_length: 32
hysteria2_listen_port: 443
hysteria2_upgrade_system: true
hysteria2_configure_firewall: true
hysteria2_masq_dir: /var/www/masq
hysteria2_config_path: /etc/hysteria/config.yaml
hysteria2_service_name: hysteria-server
# Локальный каталог для экспорта URL и QR (на control node)
# Официальный install_server.sh: хранится в roles/hysteria2/files/, синхронизируется с get.hy2.sh
hysteria2_install_script_url: "https://get.hy2.sh/"
hysteria2_install_script_name: install_server.sh
hysteria2_install_script_staging_dir: "{{ playbook_dir }}/.cache/hysteria2"
hysteria2_install_script_remote_path: /tmp/hysteria2-install_server.sh
hysteria2_output_dir: "{{ playbook_dir }}/output"
hysteria2_output_name: "{{ inventory_hostname }}"
# Генерировать PNG QR-коды через qrencode (apt на VPS, fetch на control node)
hysteria2_generate_qr_png: true
hysteria2_qr_png_size: 6
hysteria2_qr_png_margin: 2
hysteria2_qr_png_error_correction: M
# Ждать ACME при первом запуске (отключите при update: make update)
hysteria2_wait_for_acme: true
# Открыть output/index.html в браузере после install/update/export
hysteria2_open_browser: true
# --- uninstall ---
hysteria2_uninstall_remove_config: true
hysteria2_uninstall_remove_masq: true
hysteria2_uninstall_remove_local_output: false
# Перегенерировать URL/QR для всех пользователей (иначе — только новые/изменённые)
hysteria2_force_export: false
# --- uninstall (см. также defaults/uninstall.yml) ---
hysteria2_system_user: hysteria
hysteria2_uninstall_remove_masq: false
hysteria2_uninstall_rebuild_global_index: true
hysteria2_uninstall_ufw_rules:
- "{{ hysteria2_listen_port }}/tcp"
- "{{ hysteria2_listen_port }}/udp"
+11
View File
@@ -0,0 +1,11 @@
---
# Системный пользователь Hysteria (создаётся install_server.sh)
hysteria2_system_user: hysteria
# --- uninstall (Salamander: без masq, порты listen_port/tcp+udp) ---
# install_server.sh --remove: бинарник + systemd; остальное — задачи uninstall.yml
hysteria2_uninstall_remove_masq: false
hysteria2_uninstall_rebuild_global_index: true
hysteria2_uninstall_ufw_rules:
- "{{ hysteria2_listen_port }}/tcp"
- "{{ hysteria2_listen_port }}/udp"
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -2,7 +2,7 @@
galaxy_info:
role_name: hysteria2
author: inecs
description: Install Hysteria2 VPN server with masquerade site and export client URLs with QR codes
description: Install Hysteria2 VPN server with Salamander obfs and export client URLs with QR codes
license: MIT
min_ansible_version: "2.14"
platforms:
+6 -20
View File
@@ -1,24 +1,11 @@
---
- name: Create masquerade web directory
ansible.builtin.file:
path: "{{ hysteria2_masq_dir }}"
state: directory
mode: "0755"
- name: Deploy masquerade index.html
ansible.builtin.template:
src: masq/index.html.j2
dest: "{{ hysteria2_masq_dir }}/index.html"
mode: "0644"
notify: Restart hysteria-server
- name: Remove default Hysteria config if present
ansible.builtin.file:
path: "{{ hysteria2_config_path }}"
state: absent
when: not ansible_check_mode
- name: Deploy Hysteria2 server config
- name: Deploy Hysteria2 Salamander server config
ansible.builtin.template:
src: config.yaml.j2
dest: "{{ hysteria2_config_path }}"
@@ -42,12 +29,11 @@
failed_when: false
when: hysteria2_configure_firewall | bool
- name: Allow HTTP and HTTPS in ufw
- name: Allow Hysteria2 port in ufw (Salamander — только {{ hysteria2_listen_port }})
ansible.builtin.command: "ufw allow {{ item }}"
loop:
- 80/tcp
- 443/tcp
- 443/udp
- "{{ hysteria2_listen_port }}/tcp"
- "{{ hysteria2_listen_port }}/udp"
register: _hysteria2_ufw_allow
changed_when: "'Skipping' not in (_hysteria2_ufw_allow.stdout | default(''))"
failed_when: false
@@ -55,10 +41,10 @@
- hysteria2_configure_firewall | bool
- "'active' in (_hysteria2_ufw_status.stdout | default(''))"
- name: Wait for ACME certificate (first start may take several minutes)
- name: Wait for ACME TLS certificate (first start may take several minutes)
ansible.builtin.pause:
seconds: 30
prompt: "Ожидание получения ACME-сертификата для {{ hysteria2_domain }}..."
prompt: "Ожидание получения ACME TLS-сертификата для {{ hysteria2_domain }}..."
when: hysteria2_wait_for_acme | default(true) | bool
- name: Verify hysteria-server is running
+23 -6
View File
@@ -11,16 +11,28 @@
ansible.builtin.set_fact:
hysteria2_export_users: []
- name: Prepare incremental export (remove deleted users, split new vs existing)
ansible.builtin.import_tasks: export_prepare.yml
- name: Install qrencode on server for PNG QR export
ansible.builtin.apt:
name: qrencode
state: present
update_cache: false
when: hysteria2_generate_qr_png | bool
when:
- hysteria2_generate_qr_png | bool
- hysteria2_users_for_export | default([]) | length > 0
- name: Build client share data for each user
- name: Reuse existing export data for unchanged users
ansible.builtin.include_tasks: reuse_export_user.yml
loop: "{{ hysteria2_users_for_reuse | default([]) }}"
loop_control:
loop_var: hysteria2_reuse_user
label: "{{ hysteria2_reuse_user.name }}"
- name: Build client share data for new or changed users
ansible.builtin.include_tasks: share_user.yml
loop: "{{ hysteria2_resolved_users }}"
loop: "{{ hysteria2_users_for_export | default([]) }}"
loop_control:
loop_var: hysteria2_current_user
label: "{{ hysteria2_current_user.name }}"
@@ -31,8 +43,10 @@
mode: "0600"
content: |
server: {{ hysteria2_output_name }}
mode: salamander
domain: {{ hysteria2_domain }}
port: {{ hysteria2_listen_port }}
obfs_password: "{{ hysteria2_obfs_password }}"
users:
{% for user in hysteria2_export_users %}
- name: {{ user.name }}
@@ -52,12 +66,15 @@
dest: "{{ hysteria2_output_dir }}/{{ hysteria2_output_name }}/index.html"
mode: "0644"
vars:
generated_at: "{{ ansible_date_time.date }} {{ ansible_date_time.time }}"
generated_at: "{{ now(utc=false, fmt='%Y-%m-%d %H:%M:%S') }}"
hysteria2_obfs_password: "{{ hysteria2_obfs_password }}"
delegate_to: localhost
become: false
- name: Show export location
ansible.builtin.debug:
msg: >-
Клиентские URL, QR и index.html сохранены в
{{ hysteria2_output_dir }}/{{ hysteria2_output_name }}/
Экспорт: {{ hysteria2_users_for_export | default([]) | length }} пользователь(ей) обновлено,
{{ hysteria2_users_for_reuse | default([]) | length }} без изменений,
{{ _hysteria2_removed_users | default([]) | length }} удалено.
Каталог: {{ hysteria2_output_dir }}/{{ hysteria2_output_name }}/
+13 -4
View File
@@ -33,6 +33,8 @@
name: "{{ _info.server }}"
domain: "{{ _info.domain }}"
port: "{{ _info.port }}"
mode: "{{ _info.mode | default('salamander') }}"
obfs_password: "{{ _info.obfs_password | default('') }}"
dir: "{{ item.item.path | dirname | basename }}"
users: "{{ _info.users }}"
become: false
@@ -49,18 +51,25 @@
dest: "{{ hysteria2_output_dir }}/index.html"
mode: "0644"
vars:
generated_at: "{{ ansible_date_time.date }} {{ ansible_date_time.time }}"
generated_at: "{{ now(utc=false, fmt='%Y-%m-%d %H:%M:%S') }}"
total_users: "{{ hysteria2_global_servers | map(attribute='users') | map('length') | sum }}"
when: hysteria2_global_servers | default([]) | length > 0
become: false
- name: Remove global HTML index when no servers remain
ansible.builtin.file:
path: "{{ hysteria2_output_dir }}/index.html"
state: absent
when: hysteria2_global_servers | default([]) | length == 0
become: false
- name: Open global index in default browser (macOS)
ansible.builtin.command:
cmd: open "{{ hysteria2_output_dir }}/index.html"
when:
- hysteria2_open_browser | bool
- hysteria2_global_servers | default([]) | length > 0
- ansible_system == 'Darwin'
- ansible_facts['system'] == 'Darwin'
changed_when: false
become: false
@@ -70,7 +79,7 @@
when:
- hysteria2_open_browser | bool
- hysteria2_global_servers | default([]) | length > 0
- ansible_system == 'Linux'
- ansible_facts['system'] == 'Linux'
changed_when: false
become: false
failed_when: false
@@ -85,6 +94,6 @@
- name: Skip global index when no servers exported
ansible.builtin.debug:
msg: "Глобальный index.html не создан — нет server-info.yml в {{ hysteria2_output_dir }}/"
msg: "Глобальный {{ hysteria2_output_dir }}/index.html удалён — нет server-info.yml в output/"
when: hysteria2_global_servers | default([]) | length == 0
become: false
+84
View File
@@ -0,0 +1,84 @@
---
- name: Determine removed users from previous export
ansible.builtin.set_fact:
_hysteria2_removed_users: >-
{{
(_hysteria2_saved_server_info.users | default([]) | map(attribute='name') | list)
| difference(hysteria2_resolved_users | map(attribute='name') | list)
}}
delegate_to: localhost
become: false
- name: Build list of export files to remove for deleted users
ansible.builtin.set_fact:
_hysteria2_removed_user_files: >-
{{
_hysteria2_removed_user_files | default([]) + [
hysteria2_output_dir ~ '/' ~ hysteria2_output_name ~ '/' ~ item.0 ~ item.1
]
}}
loop: "{{ _hysteria2_removed_users | default([]) | product(_hysteria2_user_export_suffixes) | list }}"
vars:
_hysteria2_user_export_suffixes:
- ".url"
- ".txt"
- ".qr.txt"
- ".png"
when: _hysteria2_removed_users | default([]) | length > 0
delegate_to: localhost
become: false
- name: Remove export files for deleted users
ansible.builtin.file:
path: "{{ item }}"
state: absent
loop: "{{ _hysteria2_removed_user_files | default([]) }}"
delegate_to: localhost
become: false
when: _hysteria2_removed_user_files | default([]) | length > 0
- name: Check local URL files for resolved users
ansible.builtin.stat:
path: "{{ hysteria2_output_dir }}/{{ hysteria2_output_name }}/{{ item.name }}.url"
loop: "{{ hysteria2_resolved_users }}"
register: _hysteria2_url_file_stats
delegate_to: localhost
become: false
- name: Split users into full export and reuse existing export data
ansible.builtin.set_fact:
hysteria2_users_for_export: "{{ hysteria2_users_for_export | default([]) + ([item] if _needs_export else []) }}"
hysteria2_users_for_reuse: "{{ hysteria2_users_for_reuse | default([]) + ([_reuse_entry] if not _needs_export else []) }}"
loop: "{{ hysteria2_resolved_users }}"
loop_control:
label: "{{ item.name }}"
vars:
_saved_user: >-
{{
(_hysteria2_saved_server_info.users | default([])
| selectattr('name', 'equalto', item.name)
| list | first) | default({}, true)
}}
_url_stat: >-
{{
((_hysteria2_url_file_stats.results
| selectattr('item.name', 'equalto', item.name)
| list | first).stat) | default({}, true)
}}
_needs_export: >-
{{
hysteria2_force_export | bool
or (_saved_user | length == 0)
or (item.password != (_saved_user.password | default('')))
or (hysteria2_domain != (_hysteria2_saved_server_info.domain | default('')))
or ((hysteria2_listen_port | string) != (_hysteria2_saved_server_info.port | default('') | string))
or ((hysteria2_obfs_password | default('')) != (_hysteria2_saved_server_info.obfs_password | default('')))
or not (_url_stat.exists | default(false))
}}
_reuse_entry:
name: "{{ item.name }}"
password: "{{ item.password }}"
url: "{{ _saved_user.url }}"
has_png: "{{ _saved_user.has_png | default(false) | bool }}"
delegate_to: localhost
become: false
+13 -6
View File
@@ -11,7 +11,7 @@
ansible.builtin.apt:
upgrade: dist
- name: Install curl, micro, pwgen and qrencode
- name: Install curl, micro and qrencode
ansible.builtin.apt:
name: "{{ _hysteria2_apt_packages }}"
state: present
@@ -19,15 +19,22 @@
vars:
_hysteria2_apt_packages: >-
{{
['curl', 'micro', 'pwgen']
['curl', 'micro']
+ (['qrencode'] if hysteria2_generate_qr_png | bool else [])
}}
- name: Sync official Hysteria2 install script on control node
ansible.builtin.import_tasks: sync_install_script.yml
- name: Copy Hysteria2 install script to server
ansible.builtin.copy:
src: "{{ hysteria2_install_script_name }}"
dest: "{{ hysteria2_install_script_remote_path }}"
mode: "0755"
- name: Install Hysteria2 via official script
ansible.builtin.shell:
cmd: bash <(curl -fsSL https://get.hy2.sh/)
executable: /bin/bash
args:
ansible.builtin.command:
cmd: "{{ hysteria2_install_script_remote_path }}"
creates: /usr/local/bin/hysteria
register: _hysteria2_install
+4
View File
@@ -7,6 +7,10 @@
ansible.builtin.import_tasks: users.yml
tags: [install, update, export]
- name: Resolve Salamander obfs password
ansible.builtin.import_tasks: obfs.yml
tags: [install, update, export]
- name: Install packages and Hysteria2 binary
ansible.builtin.import_tasks: install.yml
tags: [install]
+58
View File
@@ -0,0 +1,58 @@
---
- name: Check for saved Salamander password from previous install
ansible.builtin.stat:
path: "{{ hysteria2_output_dir }}/{{ hysteria2_output_name }}/server-info.yml"
register: _hysteria2_saved_info
delegate_to: localhost
become: false
tags:
- install
- update
- export
- name: Load saved Salamander obfs password
when: _hysteria2_saved_info.stat.exists
block:
- name: Read server-info.yml for obfs password
ansible.builtin.slurp:
path: "{{ hysteria2_output_dir }}/{{ hysteria2_output_name }}/server-info.yml"
register: _hysteria2_saved_info_raw
delegate_to: localhost
become: false
- name: Parse saved obfs password
ansible.builtin.set_fact:
_hysteria2_saved_obfs_password: "{{ (_hysteria2_saved_info_raw.content | b64decode | from_yaml).obfs_password | default('') }}"
delegate_to: localhost
become: false
tags:
- install
- update
- export
- name: Resolve Salamander obfs password
ansible.builtin.set_fact:
hysteria2_obfs_password: >-
{{
hysteria2_obfs_password
| default(_hysteria2_saved_obfs_password | default(''), true)
}}
tags:
- install
- update
- export
- name: Generate Salamander obfs password
ansible.builtin.set_fact:
hysteria2_obfs_password: >-
{{
lookup(
'password',
'/dev/null chars=ascii_letters,digits length=' ~ (hysteria2_obfs_password_length | string)
)
}}
when: hysteria2_obfs_password | length == 0
tags:
- install
- update
- export
@@ -0,0 +1,4 @@
---
- name: Register reused export data for HTML page
ansible.builtin.set_fact:
hysteria2_export_users: "{{ hysteria2_export_users | default([]) + [hysteria2_reuse_user] }}"
+2
View File
@@ -34,6 +34,8 @@
Domain: {{ hysteria2_domain }}:{{ hysteria2_listen_port }}
User: {{ hysteria2_current_user.name }}
Password: {{ hysteria2_current_user.password }}
Mode: salamander
Obfs password: {{ hysteria2_obfs_password }}
URL:
{{ _hysteria2_client_url }}
@@ -0,0 +1,64 @@
---
- name: Ensure staging directory for install script sync
ansible.builtin.file:
path: "{{ hysteria2_install_script_staging_dir }}"
state: directory
mode: "0700"
delegate_to: localhost
become: false
run_once: true
- name: Fetch official install script for version check
ansible.builtin.get_url:
url: "{{ hysteria2_install_script_url }}"
dest: "{{ hysteria2_install_script_staging_dir }}/{{ hysteria2_install_script_name }}.remote"
mode: "0644"
force: true
delegate_to: localhost
become: false
run_once: true
register: _hysteria2_remote_script
- name: Stat local install script in role files
ansible.builtin.stat:
path: "{{ role_path }}/files/{{ hysteria2_install_script_name }}"
checksum_algorithm: sha256
delegate_to: localhost
become: false
run_once: true
register: _hysteria2_local_script
- name: Stat remote install script from official server
ansible.builtin.stat:
path: "{{ hysteria2_install_script_staging_dir }}/{{ hysteria2_install_script_name }}.remote"
checksum_algorithm: sha256
delegate_to: localhost
become: false
run_once: true
register: _hysteria2_remote_script_stat
- name: Update bundled install script when official version is newer
ansible.builtin.copy:
src: "{{ hysteria2_install_script_staging_dir }}/{{ hysteria2_install_script_name }}.remote"
dest: "{{ role_path }}/files/{{ hysteria2_install_script_name }}"
mode: "0755"
delegate_to: localhost
become: false
run_once: true
when: >-
not _hysteria2_local_script.stat.exists
or _hysteria2_local_script.stat.checksum
!= _hysteria2_remote_script_stat.stat.checksum
register: _hysteria2_script_updated
- name: Report install script sync result
ansible.builtin.debug:
msg: >-
{{
'Официальный install_server.sh обновлён в roles/hysteria2/files/'
if (_hysteria2_script_updated.changed | default(false))
else 'Локальный install_server.sh актуален (совпадает с ' ~ hysteria2_install_script_url ~ ')'
}}
delegate_to: localhost
become: false
run_once: true
+108 -23
View File
@@ -1,46 +1,131 @@
---
- name: Stop and disable hysteria-server
- name: Stop and disable hysteria-server before removal
ansible.builtin.systemd:
name: "{{ hysteria2_service_name }}"
enabled: false
state: stopped
failed_when: false
- name: Remove Hysteria2 via official script
ansible.builtin.shell:
cmd: bash <(curl -fsSL https://get.hy2.sh/) --remove
executable: /bin/bash
- name: Copy Hysteria2 install script to server
ansible.builtin.copy:
src: "{{ hysteria2_install_script_name }}"
dest: "{{ hysteria2_install_script_remote_path }}"
mode: "0755"
- name: Remove Hysteria2 binary and systemd units via official script
ansible.builtin.command:
cmd: "{{ hysteria2_install_script_remote_path }} --remove"
register: _hysteria2_remove
changed_when: _hysteria2_remove.rc == 0
failed_when: false
- name: Remove Hysteria2 configuration directory
ansible.builtin.file:
path: "{{ hysteria2_config_path | dirname }}"
state: absent
when: hysteria2_uninstall_remove_config | bool
- name: Show official script removal output
ansible.builtin.debug:
msg: "{{ _hysteria2_remove.stdout_lines | default(['install_server.sh --remove: no output']) }}"
when: _hysteria2_remove.stdout_lines is defined
- name: Remove masquerade web directory
- name: Remove Hysteria2 configuration and ACME data
ansible.builtin.file:
path: "{{ hysteria2_masq_dir }}"
path: "{{ item }}"
state: absent
loop:
- "{{ hysteria2_config_path | dirname }}"
- "/var/lib/{{ hysteria2_system_user | default('hysteria') }}"
- name: Remove enabled hysteria-server systemd symlink
ansible.builtin.file:
path: /etc/systemd/system/multi-user.target.wants/hysteria-server.service
state: absent
failed_when: false
- name: Find enabled hysteria-server@ systemd symlinks
ansible.builtin.find:
paths: /etc/systemd/system/multi-user.target.wants
patterns: hysteria-server@*.service
file_type: file
register: _hysteria2_systemd_instance_wants
failed_when: false
- name: Remove enabled hysteria-server@ systemd symlinks
ansible.builtin.file:
path: "{{ item.path }}"
state: absent
loop: "{{ _hysteria2_systemd_instance_wants.files | default([]) }}"
failed_when: false
- name: Remove Hysteria system user and home directory
ansible.builtin.user:
name: "{{ hysteria2_system_user | default('hysteria') }}"
state: absent
remove: true
failed_when: false
- name: Find temporary Hysteria client configs on server
ansible.builtin.find:
paths: /tmp
patterns: hysteria-client-*.yaml
file_type: file
register: _hysteria2_tmp_client_configs
failed_when: false
- name: Remove temporary Hysteria client configs on server
ansible.builtin.file:
path: "{{ item.path }}"
state: absent
loop: "{{ _hysteria2_tmp_client_configs.files | default([]) }}"
failed_when: false
- name: Check if ufw is available and active
ansible.builtin.command: ufw status
register: _hysteria2_ufw_status
changed_when: false
failed_when: false
- name: Remove firewall rules added during install
ansible.builtin.command: "ufw delete allow {{ item }}"
loop: "{{ hysteria2_uninstall_ufw_rules }}"
register: _hysteria2_ufw_delete
changed_when: >-
_hysteria2_ufw_delete.rc == 0
and 'Could not delete' not in (_hysteria2_ufw_delete.stdout | default(''))
and 'Could not find' not in (_hysteria2_ufw_delete.stderr | default(''))
failed_when: false
when: "'active' in (_hysteria2_ufw_status.stdout | default(''))"
- name: Remove packages installed for Hysteria2
ansible.builtin.apt:
name: "{{ _hysteria2_apt_packages }}"
state: absent
purge: true
autoremove: true
vars:
_hysteria2_apt_packages: >-
{{
['curl', 'micro']
+ (['qrencode'] if hysteria2_generate_qr_png | default(true) | bool else [])
}}
- name: Remove copied install script from server
ansible.builtin.file:
path: "{{ hysteria2_install_script_remote_path }}"
state: absent
when: hysteria2_uninstall_remove_masq | bool
- name: Reload systemd after uninstall
ansible.builtin.systemd:
daemon_reload: true
- name: Show uninstall result
ansible.builtin.debug:
msg: >-
Hysteria2 удалён с {{ inventory_hostname }}.
{% if not hysteria2_uninstall_remove_local_output | bool %}
Локальные URL/QR в {{ hysteria2_output_dir }}/{{ hysteria2_output_name }}/ сохранены.
{% endif %}
- name: Remove local exported client files
- name: Remove local output directory for this server
ansible.builtin.file:
path: "{{ hysteria2_output_dir }}/{{ hysteria2_output_name }}"
state: absent
delegate_to: localhost
become: false
when: hysteria2_uninstall_remove_local_output | bool
- name: Show uninstall result
ansible.builtin.debug:
msg: >-
Hysteria2 (Salamander) полностью удалён с {{ inventory_hostname }}.
Локальная папка {{ hysteria2_output_dir }}/{{ hysteria2_output_name }}/ удалена.
{% if hysteria2_uninstall_rebuild_global_index | default(true) | bool %}
{{ hysteria2_output_dir }}/index.html будет пересобран без этого сервера.
{% endif %}
+11 -3
View File
@@ -1,8 +1,16 @@
---
- name: Sync official Hysteria2 install script on control node
ansible.builtin.import_tasks: sync_install_script.yml
- name: Copy Hysteria2 install script to server
ansible.builtin.copy:
src: "{{ hysteria2_install_script_name }}"
dest: "{{ hysteria2_install_script_remote_path }}"
mode: "0755"
- name: Update Hysteria2 binary via official script
ansible.builtin.shell:
cmd: bash <(curl -fsSL https://get.hy2.sh/)
executable: /bin/bash
ansible.builtin.command:
cmd: "{{ hysteria2_install_script_remote_path }} --force"
register: _hysteria2_update
notify: Restart hysteria-server
+51 -30
View File
@@ -10,6 +10,16 @@
- update
- export
- name: Initialize empty saved export metadata
ansible.builtin.set_fact:
_hysteria2_saved_passwords: {}
_hysteria2_saved_server_info: {}
when: not _hysteria2_saved_info.stat.exists
tags:
- install
- update
- export
- name: Load saved user passwords from local export
when: _hysteria2_saved_info.stat.exists
block:
@@ -20,8 +30,9 @@
delegate_to: localhost
become: false
- name: Parse saved passwords into lookup dict
- name: Parse saved export metadata
ansible.builtin.set_fact:
_hysteria2_saved_server_info: "{{ _hysteria2_saved_info_raw.content | b64decode | from_yaml }}"
_hysteria2_saved_passwords: >-
{{
dict(
@@ -33,12 +44,14 @@
)
)
}}
delegate_to: localhost
become: false
tags:
- install
- update
- export
- name: Resolve user list with optional fixed passwords
- name: Resolve user list with passwords from inventory, vault and previous export
ansible.builtin.set_fact:
hysteria2_resolved_users: "{{ hysteria2_resolved_users | default([]) + [ _entry ] }}"
vars:
@@ -46,8 +59,26 @@
_password: >-
{{
(
item.password if item is mapping
) | default('', true)
item.password
if item is mapping and (item.password | default('') | length > 0)
else none
)
| default(
hysteria2_user_passwords[_username]
if (
hysteria2_user_passwords is defined
and (hysteria2_user_passwords[_username] | default('') | length > 0)
)
else none,
true
)
| default(
_hysteria2_saved_passwords[_username]
if (_hysteria2_saved_passwords[_username] | default('') | length > 0)
else none,
true
)
| default('', true)
}}
_entry:
name: "{{ _username }}"
@@ -60,16 +91,24 @@
- update
- export
- name: Generate missing user passwords with pwgen
ansible.builtin.command:
cmd: "pwgen -s {{ hysteria2_password_length }} 1"
register: _hysteria2_pwgen
changed_when: false
when: item.password | length == 0
- name: Generate missing user passwords
ansible.builtin.set_fact:
_hysteria2_users_with_passwords: "{{ _hysteria2_users_with_passwords | default([]) + [ _entry ] }}"
vars:
_entry:
name: "{{ item.name }}"
password: >-
{{
lookup(
'password',
'/dev/null chars=ascii_letters,digits length=' ~ (hysteria2_password_length | string)
)
if item.password | length == 0
else item.password
}}
loop: "{{ hysteria2_resolved_users }}"
loop_control:
label: "{{ item.name }}"
index_var: _hysteria2_user_idx
tags:
- install
- update
@@ -77,25 +116,7 @@
- name: Apply generated passwords
ansible.builtin.set_fact:
hysteria2_resolved_users: "{{ hysteria2_resolved_users | default([]) + [ _entry ] }}"
vars:
_generated: >-
{{
_hysteria2_pwgen.results[_hysteria2_user_idx].stdout | default('')
if (
item.password | length == 0
and not (_hysteria2_pwgen.results[_hysteria2_user_idx].skipped | default(false))
)
else item.password
}}
_entry:
name: "{{ item.name }}"
password: "{{ _generated }}"
loop: "{{ hysteria2_resolved_users }}"
loop_control:
label: "{{ item.name }}"
index_var: _hysteria2_user_idx
when: _hysteria2_pwgen is defined
hysteria2_resolved_users: "{{ _hysteria2_users_with_passwords }}"
tags:
- install
- update
+1 -1
View File
@@ -7,7 +7,7 @@
- hysteria2_users | length > 0
fail_msg: |
Задайте для каждого хоста:
hysteria2_domain — домен с A-записью на IP сервера
hysteria2_domain — домен с A-записью на IP сервера (используется для TLS/SNI)
hysteria2_users — список имён пользователей, например [my, friend]
И в group_vars/all.yml:
hysteria2_acme_email — email для Let's Encrypt
+5
View File
@@ -1,3 +1,8 @@
server: {{ hysteria2_domain }}:{{ hysteria2_listen_port }}
auth: {{ hysteria2_current_user.name }}:{{ hysteria2_current_user.password }}
obfs:
type: salamander
salamander:
password: {{ hysteria2_obfs_password }}
+5 -8
View File
@@ -1,7 +1,7 @@
listen: 0.0.0.0:{{ hysteria2_listen_port }}
acme:
type: http
type: tls
domains:
- {{ hysteria2_domain }}
email: {{ hysteria2_acme_email }}
@@ -13,10 +13,7 @@ auth:
{{ user.name }}: "{{ user.password }}"
{% endfor %}
masquerade:
type: file
file:
dir: {{ hysteria2_masq_dir }}
listenHTTP: :80
listenHTTPS: :{{ hysteria2_listen_port }}
forceHTTPS: true
obfs:
type: salamander
salamander:
password: "{{ hysteria2_obfs_password }}"
@@ -160,6 +160,17 @@
font-weight: 600;
}
.server-link:hover { background: var(--accent-soft); border-color: var(--accent); }
.badge-salamander {
display: inline-block;
margin-top: 0.35rem;
padding: 0.2rem 0.6rem;
border-radius: 999px;
font-size: 0.72rem;
font-weight: 700;
background: var(--accent-soft-2);
color: var(--accent-2);
}
.server-obfs { margin-top: 0.75rem; width: 100%; }
.users-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
@@ -286,8 +297,8 @@
</head>
<body>
<header class="hero">
<h1>Hysteria2</h1>
<p>Общий каталог VPN-подключений</p>
<h1>Hysteria2 · Salamander</h1>
<p>Общий каталог VPN-подключений с обфускацией Salamander</p>
<div class="stats">
<div class="stat"><span>{{ hysteria2_global_servers | length }}</span> серверов</div>
<div class="stat"><span>{{ total_users }}</span> пользователей</div>
@@ -307,6 +318,18 @@
<div>
<h2>{{ server.name | e }}</h2>
<p class="domain">{{ server.domain | e }}:{{ server.port }}</p>
<span class="badge-salamander">Salamander</span>
{% if server.obfs_password | default('') | length > 0 %}
<div class="field server-obfs">
<label for="obfs-{{ server.dir | e }}">Пароль обфускации</label>
<div class="input-row">
<input type="text" id="obfs-{{ server.dir | e }}" value="{{ server.obfs_password | e }}" readonly>
<button type="button" class="btn-copy" onclick="copyField('obfs-{{ server.dir | e }}', this)" title="Копировать obfs-password" aria-label="Копировать obfs-password">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
</button>
</div>
</div>
{% endif %}
</div>
<a class="server-link" href="{{ server.dir | e }}/index.html">Страница сервера →</a>
</div>
@@ -75,6 +75,15 @@
font-size: 0.8rem;
font-weight: 600;
}
.badge-salamander {
margin-left: 0.35rem;
background: rgba(163, 113, 247, 0.18);
color: #a371f7;
}
.server-obfs {
margin-top: 1.25rem;
max-width: 100%;
}
.user-card {
background: var(--bg-card);
border: 1px solid var(--border);
@@ -235,6 +244,17 @@
Домен: <strong>{{ hysteria2_domain }}:{{ hysteria2_listen_port }}</strong>
</p>
<span class="badge">{{ hysteria2_export_users | length }} {{ 'пользователь' if hysteria2_export_users | length == 1 else 'пользователей' }}</span>
<span class="badge badge-salamander">Salamander</span>
<div class="field server-obfs">
<label for="obfs-server">Пароль обфускации (Salamander)</label>
<div class="input-row">
<input type="text" id="obfs-server" value="{{ hysteria2_obfs_password | e }}" readonly>
<button type="button" class="btn-copy" onclick="copyField('obfs-server', this)" title="Копировать obfs-password" aria-label="Копировать obfs-password">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
</button>
</div>
</div>
</header>
{% for user in hysteria2_export_users %}
@@ -1,27 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, nginx is successfully installed and working.
Further configuration is required for the web server, reverse proxy,
API gateway, load balancer, content cache, or other features.</p>
<p>For online documentation and support please refer to
<a href="https://nginx.org/">nginx.org</a>.<br/>
To engage with the community please visit
<a href="https://community.nginx.org/">community.nginx.org</a>.<br/>
For enterprise grade support, professional services, additional
security features and capabilities please refer to
<a href="https://f5.com/nginx">f5.com/nginx</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>