Compare commits

..

11 Commits

Author SHA1 Message Date
Sergey Antropoff a79ce46457 fix: пересборка output/index.html при uninstall с LIMIT
Второй play перенесён на hysteria2_servers с run_once на localhost,
чтобы LIMIT не пропускал пересборку. Пустой index.html удаляется.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-01 13:31:40 +03:00
Sergey Antropoff 45f0682d8b Полная очистка при uninstall: VPS и output/<server>/
Скрипт --remove снимает только бинарник и systemd; Ansible дочищает конфиг,
пользователя, ufw, пакеты и всегда удаляет локальную папку экспорта.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-01 13:28:00 +03:00
Sergey Antropoff 27ae65edc5 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.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-01 13:19:47 +03:00
Sergey Antropoff 05994fceaf docs: update README for install script, update, uninstall and users
Document incremental export, full uninstall cleanup, vault wiring, Makefile commands and role structure.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-01 13:15:24 +03:00
Sergey Antropoff 5f09a26ef3 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:14 +03:00
Sergey Antropoff 3faf21fecb 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:55:52 +03:00
Sergey Antropoff d61a26557a 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:10 +03:00
Sergey Antropoff 2d44916893 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:06 +03:00
Sergey Antropoff 3ca7dde4b2 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:42:40 +03:00
Sergey Antropoff ad7846febe 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 e90e2bad8b Expand README: branch comparison, ACME auto-renewal, branch switching.
Unified documentation structure aligned with salamander branch.
2026-07-01 02:22:38 +03:00
21 changed files with 188 additions and 352 deletions
+91 -135
View File
@@ -1,16 +1,16 @@
# Hysteria2 Ansible — ветка **Salamander**
# Hysteria2 Ansible — ветка **main**
> **Ветка:** `salamander`
> **Режим:** **Salamander obfs** — запутывание пакетов для обхода DPI
> **Основная ветка:** [`main`](https://git.antropoff.ru/DevOpsTools/hysteria2/src/branch/main) — masquerade под HTTPS-сайт nginx
> **Ветка:** `main`
> **Режим:** **masquerade** — маскировка под HTTPS-сайт nginx
> **Альтернатива:** [`salamander`](https://git.antropoff.ru/DevOpsTools/hysteria2/src/branch/salamander) — обфускация Salamander для агрессивного DPI
Ansible-роль для установки [Hysteria 2](https://v2.hysteria.network/) на Debian/Ubuntu VPS с **Salamander obfs** — когда masquerade под «обычный сайт» недостаточен.
Ansible-роль для установки [Hysteria 2](https://v2.hysteria.network/) на Debian/Ubuntu VPS: Let's Encrypt, masquerade под nginx, несколько пользователей, экспорт URL/QR и HTML-каталог.
---
## Выбор ветки: `main` или `salamander`
| | **`main`** | **`salamander` (эта ветка)** |
| | **`main` (эта ветка)** | **`salamander`** |
|---|---|---|
| Маскировка | HTTPS-сайт nginx + Let's Encrypt | **Salamander obfs** — пакеты выглядят как шум |
| Порт 80/tcp | **Нужен** (ACME HTTP + masquerade) | **Не нужен** |
@@ -20,18 +20,19 @@ Ansible-роль для установки [Hysteria 2](https://v2.hysteria.netw
| URI клиента | `hysteria2://user:pass@domain:443` | + `obfs=salamander&obfs-password=...` |
| Лучше когда | Нужен «легитимный» сайт в браузере | Агрессивный DPI, блокировка QUIC fingerprint |
### Когда выбирать `main`
- нужен **нормальный HTTPS-сайт** при открытии домена в браузере;
- достаточно маскировки под nginx;
- хотите **минимум параметров** в URI клиента;
- провайдер не «палит» Hysteria/QUIC внутри TLS.
### Когда выбирать `salamander`
- masquerade из `main` **блокируют** или распознают по fingerprint;
- не нужен фейковый сайт в браузере;
- не нужен фейковый сайт;
- готовы хранить **дополнительный** obfs-пароль.
### Когда выбирать `main`
- нужен **нормальный HTTPS-сайт** при открытии домена;
- достаточно маскировки под nginx;
- хотите **минимум параметров** в URI клиента.
---
## Быстрый старт
@@ -39,7 +40,7 @@ Ansible-роль для установки [Hysteria 2](https://v2.hysteria.netw
```bash
git clone https://git.antropoff.ru/DevOpsTools/hysteria2.git
cd hysteria2
git checkout salamander
git checkout main
# macOS: установить Ansible (если ещё нет)
brew install ansible
@@ -69,7 +70,7 @@ make install # → output/index.html откроется в браузере
| `make check` | Проверить синтаксис playbook |
| `make ping` | Проверить SSH к VPS |
| `make status` | `systemctl status hysteria-server` |
| `make install` | Установка Salamander + экспорт URL/QR/HTML |
| `make install` | Установка masquerade + экспорт URL/QR/HTML |
| `make update` | Обновить бинарник и конфиг; экспорт только для новых/изменённых пользователей |
| `make export` | Только экспорт (URL, QR, HTML) без изменений на сервере |
| `make uninstall` | Полное удаление с VPS + `output/<server>/` + пересборка `output/index.html` |
@@ -80,12 +81,10 @@ make install # → output/index.html откроется в браузере
```bash
make install LIMIT=vps-de
make install LIMIT=vps-nl # только новый сервер — старые не трогаются
make update LIMIT=vps-nl
make export
make uninstall LIMIT=vps-de
make update EXTRA_VARS='hysteria2_force_export=true' # перевыпустить URL/QR для всех
make install EXTRA_VARS='hysteria2_force_export=true' # то же при install
make install EXTRA_VARS='hysteria2_open_browser=false'
make update EXTRA_VARS='hysteria2_wait_for_acme=false'
```
@@ -106,7 +105,7 @@ all:
ansible_port: 2222 # SSH-порт (если не 22)
ansible_user: root
ansible_password: "{{ vault_ssh_passwords['vps-de'] }}"
hysteria2_domain: vpn-de.example.com # для TLS/SNI и ACME
hysteria2_domain: vpn-de.example.com
hysteria2_users:
- my
- friend
@@ -142,7 +141,7 @@ vault_ssh_passwords:
---
## Как работает Salamander в этом проекте
## Как работает masquerade в этом проекте
### Сервер (`/etc/hysteria/config.yaml`)
@@ -150,7 +149,7 @@ vault_ssh_passwords:
listen: 0.0.0.0:443
acme:
type: tls # сертификат без порта 80
type: http
domains:
- vpn-de.example.com
email: admin@example.com
@@ -161,36 +160,38 @@ auth:
my: "..."
friend: "..."
obfs:
type: salamander
salamander:
password: "общий_obfs_пароль_сервера"
masquerade:
type: file
file:
dir: /var/www/masq
listenHTTP: :80
listenHTTPS: :443
forceHTTPS: true
```
### Сайт-заглушка
В `/var/www/masq/index.html` — официальная страница **Welcome to nginx!**
При открытии домена в браузере — валидный HTTPS-сайт с Let's Encrypt.
### Клиент (генерируется автоматически)
```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
hysteria2://my:password@vpn-de.example.com:443#my
```
Роль вызывает `hysteria share` — URI и QR уже содержат параметры Salamander.
Роль вызывает `hysteria share` — URI и QR формируются автоматически.
---
## Пароли
### VPN-пользователи (`userpass`)
## Пароли VPN-пользователей
1. **Vault (рекомендуется):**
@@ -216,59 +217,20 @@ hysteria2_user_passwords:
3. **Автогенерация** — Ansible `password` lookup, если пароль не задан ни в inventory/vault, ни в `output/<server>/server-info.yml`.
При `make update` / `make export`:
- **существующие** пользователи сохраняют пароли из `server-info.yml` (и URL/QR, если домен/порт/obfs не менялись);
- **существующие** пользователи сохраняют пароли из `server-info.yml` (и URL/QR, если домен/порт не менялись);
- **новые** получают автогенерацию и полный экспорт;
- **удалённые** из 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`.
```bash
make install EXTRA_VARS='hysteria2_force_export=true'
make update LIMIT=vps-de EXTRA_VARS='hysteria2_force_export=true'
```
### Добавить второй VPS
После `make install` на первом сервере можно добавить ещё один хост в `inventory/hosts.yml`.
**Без `LIMIT`** `make install` пройдёт по **всем** серверам из inventory. На уже установленном пароли и файлы URL/QR **не перегенерируются** (берутся из `output/<server>/server-info.yml`), если вы не меняли его `hysteria2_users`, домен или порт.
Чтобы **не трогать** уже работающий VPS и экспорт:
```bash
make install LIMIT=новый-сервер
```
`LIMIT` — имя нового хоста из inventory (например `vps-nl`).
Принудительно перевыпустить URL/QR для всех: `hysteria2_force_export: true``group_vars/all.yml` или `EXTRA_VARS`).
### Добавить / удалить пользователя
1. Отредактируйте `hysteria2_users` в `inventory/hosts.yml`.
1. Отредактируйте `hysteria2_users` в `inventory/hosts.yml` (добавьте имя или уберите).
2. Запустите `make update LIMIT=<хост>`.
Пароли и obfs существующих клиентов **не меняются** (из `server-info.yml`).
Новому пользователю генерируется пароль и создаются URL/QR с параметрами Salamander.
Удалённый пользователь пропадает из конфига и из `output/<server>/`.
Пароли существующих клиентов **не меняются** (берутся из `output/<server>/server-info.yml`).
Новому пользователю генерируется пароль и создаются URL/QR.
Удалённый пользователь пропадает из `/etc/hysteria/config.yaml` и из папки `output/<server>/`.
---
@@ -276,12 +238,12 @@ make install LIMIT=новый-сервер
Официальный скрипт `install_server.sh` хранится в `roles/hysteria2/files/`.
Перед `make install` / `make update` на **control node**:
Перед `make install` / `make update` на **control node** (ваш Mac):
1. Скачивается копия с https://get.hy2.sh/
2. Сравнивается SHA256 с локальным файлом в роли
3. При отличии — локальная копия обновляется
4. Скрипт копируется на VPS и запускается оттуда
4. Скрипт копируется на VPS и запускается оттуда (без `curl | bash` на сервере)
---
@@ -290,11 +252,11 @@ make install LIMIT=новый-сервер
| Компонент | Поведение |
|---|---|
| Бинарник `hysteria` | Обновляется (`install_server.sh --force`) |
| `/etc/hysteria/config.yaml` | Перекатывается (auth + obfs) |
| Пароли VPN / obfs | Сохраняются для существующей конфигурации |
| `/etc/hysteria/config.yaml` | Перекатывается под текущий inventory |
| Пароли VPN | Сохраняются для существующих пользователей |
| URL / QR | Только для новых, изменённых или при `hysteria2_force_export=true` |
| `apt upgrade` | **Не** выполняется |
| Ожидание ACME | **Не** выполняется |
| `apt upgrade` | **Не** выполняется (отключено в Makefile) |
| Ожидание ACME | **Не** выполняется (`hysteria2_wait_for_acme=false`) |
---
@@ -305,9 +267,10 @@ make install LIMIT=новый-сервер
- бинарник `/usr/local/bin/hysteria` и unit-файлы systemd;
- `/etc/hysteria/` (конфиг и ACME);
- `/var/lib/hysteria` и пользователь `hysteria`;
- `/var/www/masq` (сайт-заглушка, ветка **main**);
- symlink'и `multi-user.target.wants/hysteria-server*`;
- временные `/tmp/hysteria-client-*.yaml`;
- правила ufw: `443/tcp`, `443/udp` (порт из `hysteria2_listen_port`);
- правила ufw, добавленные при install;
- пакеты `curl`, `micro`, `qrencode`.
На **control node**:
@@ -324,11 +287,11 @@ make install LIMIT=новый-сервер
При блоке `acme:` в конфиге встроенный ACME-клиент Hysteria2 сам получает и **продлевает** сертификат Let's Encrypt (срок ~90 дней). Повторный `make install` или certbot для продления **не нужны** — процесс `hysteria-server` делает это сам.
**Условия для авто-продления (ветка `salamander`):**
**Условия для авто-продления (ветка `main`):**
- сервер **запущен** и доступен из интернета;
- домен указывает на IP VPS;
- порт **443/tcp** открыт (ACME TLS-ALPN challenge);
- порты **80/tcp** и **443/tcp** открыты (ACME HTTP challenge + masquerade);
- конфиг `acme` не удалён.
Проверка логов: `journalctl -u hysteria-server -f`
@@ -337,12 +300,11 @@ make install LIMIT=новый-сервер
## Firewall
По умолчанию открываются только порты Hysteria2:
По умолчанию открываются:
- **443/tcp**
- **443/udp**
**Порт 80 не используется** — в отличие от ветки `main`.
- **80/tcp** — ACME HTTP + masquerade HTTP
- **443/tcp** — HTTPS masquerade
- **443/udp** — Hysteria2
---
@@ -352,20 +314,19 @@ make install LIMIT=новый-сервер
output/
├── index.html ← все серверы (открывается в браузере)
├── vps-de/
│ ├── index.html ← страница сервера + obfs-пароль
│ ├── my.url ← URI с obfs=salamander
│ ├── index.html ← страница сервера
│ ├── my.url
│ ├── my.png ← QR PNG
│ ├── my.qr.txt ← QR ASCII
│ ├── my.txt
│ └── server-info.yml ← mode, obfs_password, users
│ └── server-info.yml
└── vps-nl/
└── ...
```
HTML-страницы показывают:
- режим **Salamander** и **obfs-password** с кнопкой копирования;
- пароль и URL каждого пользователя;
- пароль и URL каждого пользователя с **кнопкой копирования**;
- QR-коды;
- ссылки на файлы и страницы серверов.
@@ -391,37 +352,33 @@ ASCII QR — `hysteria share --qr` → `user.qr.txt`.
| Переменная | Где | Описание |
|---|---|---|
| `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_domain` | host | Домен с A-записью на IP |
| `hysteria2_users` | host | Список имён VPN-пользователей |
| `hysteria2_acme_email` | group | Email для Let's Encrypt |
| `hysteria2_user_passwords` | host/vault | Фиксированные пароли VPN (`vars.yml` + vault) |
| `hysteria2_password_length` | group | Длина автогенерируемого пароля (40) |
| `hysteria2_force_export` | group | Перегенерировать URL/QR для всех (`false` по умолчанию) |
| `hysteria2_output_dir` | group | Папка экспорта (`./output`) |
| `hysteria2_listen_port` | group | Порт (443) |
| `hysteria2_upgrade_system` | group | `apt upgrade` перед install |
| `hysteria2_configure_firewall` | group | Открыть порты в ufw |
| `hysteria2_output_name` | host | Подпапка экспорта (`inventory_hostname`) |
| `hysteria2_listen_port` | group | Порт Hysteria2 (443) |
| `hysteria2_upgrade_system` | group | `apt upgrade` перед install (`true`) |
| `hysteria2_configure_firewall` | group | Открыть порты в ufw (`true`) |
| `hysteria2_generate_qr_png` | group | PNG QR через `qrencode` |
| `hysteria2_wait_for_acme` | group | Пауза при первом ACME |
| `hysteria2_wait_for_acme` | group | Пауза при первом ACME (install) |
| `hysteria2_open_browser` | group | Открыть `output/index.html` после экспорта |
| `hysteria2_uninstall_rebuild_global_index` | group | Пересобрать `output/index.html` после uninstall (`true`) |
| `vault_ssh_passwords` | vault | SSH-пароли root |
| `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`.
Полный список defaults: `roles/hysteria2/defaults/main.yml`, `defaults/uninstall.yml`.
---
## Безопасность
- `output/` содержит пароли, obfs-ключи и URL — **не коммитить**`.gitignore`)
- `output/` содержит пароли и URL — **не коммитить**`.gitignore`)
- `inventory/hosts.yml`, `vault.yml`, `.vault_pass` — не коммитить
- После `make init` выполните `make vault-encrypt`
- Salamander **не делает** вас невидимым: IP VPS и UDP-поток всё ещё можно анализировать
---
@@ -429,9 +386,8 @@ ASCII QR — `hysteria share --qr` → `user.qr.txt`.
- **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 и др.)
- Домен с A-записью на IP сервера
- Порты **80/tcp** и **443/tcp+udp** доступны с интернета (ветка `main`)
- Для авто-открытия браузера: macOS (`open`) или Linux (`xdg-open`)
---
@@ -441,29 +397,29 @@ ASCII QR — `hysteria share --qr` → `user.qr.txt`.
```
roles/hysteria2/
├── defaults/
│ ├── main.yml
│ └── uninstall.yml
│ ├── main.yml ← основные переменные
│ └── uninstall.yml ← переменные удаления
├── files/
│ └── install_server.sh
│ └── install_server.sh ← официальный скрипт (синхронизация с get.hy2.sh)
├── tasks/
│ ├── main.yml
│ ├── main.yml ← порядок задач и теги
│ ├── validate.yml
│ ├── users.yml
│ ├── obfs.yml ← пароль Salamander obfs
│ ├── users.yml ← пароли (inventory / vault / server-info.yml)
│ ├── sync_install_script.yml
│ ├── install.yml
│ ├── configure.yml ← Salamander, без masquerade
│ ├── update.yml
│ ├── export_prepare.yml
│ ├── export.yml
│ ├── export_global.yml
│ ├── install.yml ← пакеты, бинарник
│ ├── configure.yml ← masquerade + ACME + ufw
│ ├── update.yml ← обновление бинарника
│ ├── export_prepare.yml ← инкрементальный экспорт
│ ├── export.yml ← URL, QR, HTML сервера
│ ├── export_global.yml ← общий output/index.html
│ ├── share_user.yml
│ ├── reuse_export_user.yml
│ └── uninstall.yml
└── templates/
├── config.yaml.j2 ← acme tls + obfs salamander
├── config.yaml.j2 ← acme http + masquerade file
├── client.yaml.j2
── export/
── masq/index.html.j2
└── export/ ← HTML-каталоги
```
---
@@ -472,15 +428,15 @@ roles/hysteria2/
```bash
git fetch origin
git checkout main # masquerade + nginx
git checkout salamander # Salamander obfs (эта ветка)
git checkout main # masquerade + nginx (эта ветка)
git checkout salamander # Salamander obfs
```
Конфиги на **уже установленном** сервере **не меняются** при переключении ветки в git.
Чтобы применить другой режим на VPS:
```bash
git checkout main # или salamander
git checkout salamander # или main
make install # перекатит конфиг сервера
# или
make update
+2 -5
View File
@@ -17,11 +17,8 @@ hysteria2_output_dir: "{{ playbook_dir }}/output"
# Открывать output/index.html в браузере после install/update/export
# hysteria2_open_browser: true
# Порт Hysteria2 (Salamander — достаточно открыть только его, 80/tcp не нужен)
# Порт Hysteria2
hysteria2_listen_port: 443
# Открывать порты в ufw ({{ hysteria2_listen_port }}/tcp и /udp)
# Открывать порты в ufw (80/tcp, 443/tcp, 443/udp)
hysteria2_configure_firewall: true
# Длина пароля Salamander obfs
# hysteria2_obfs_password_length: 32
@@ -4,6 +4,3 @@
# Проброс 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,8 +14,5 @@ vault_ssh_passwords:
# vault_hysteria2_user_passwords:
# vps-de:
# friend: "Aingae0Okit1eek4eeZahFohVei4akee"
# Опционально: пароль Salamander obfs (один на сервер)
# vault_hysteria2_obfs_passwords:
# vps-de: "cry_me_a_r1ver_salamander_obfs_pass"
# vps-nl: "another_obfs_password_32chars!!"
# vps-nl:
# alice: "CustomAlicePassword40chars................"
+12 -12
View File
@@ -1,8 +1,5 @@
---
# Режим развёртывания (ветка salamander)
hysteria2_mode: salamander
# Домен сервера (A-запись → IP VPS). Используется для TLS/SNI и ACME.
# Домен сервера (A-запись → IP VPS). Задаётся per-host в inventory.
hysteria2_domain: ""
# Email для ACME / Let's Encrypt
@@ -12,17 +9,14 @@ hysteria2_acme_email: ""
hysteria2_users: []
# Опционально: фиксированные пароли { username: password }
# Пароль обфускации Salamander (общий для сервера).
# Пусто — автогенерация на control node (Ansible password lookup) или загрузка из output/<server>/server-info.yml
hysteria2_obfs_password: ""
# Пустое значение или отсутствие ключа — автогенерация на control node (Ansible password lookup)
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
@@ -32,15 +26,20 @@ 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
# Локальный каталог для экспорта URL и QR (на control node)
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
# Перегенерировать URL/QR для всех пользователей (иначе — только новые/изменённые)
@@ -48,8 +47,9 @@ hysteria2_force_export: false
# --- uninstall (см. также defaults/uninstall.yml) ---
hysteria2_system_user: hysteria
hysteria2_uninstall_remove_masq: false
hysteria2_uninstall_remove_masq: true
hysteria2_uninstall_rebuild_global_index: true
hysteria2_uninstall_ufw_rules:
- "{{ hysteria2_listen_port }}/tcp"
- "{{ hysteria2_listen_port }}/udp"
- 80/tcp
- 443/tcp
- 443/udp
+5 -4
View File
@@ -2,10 +2,11 @@
# Системный пользователь Hysteria (создаётся install_server.sh)
hysteria2_system_user: hysteria
# --- uninstall (Salamander: без masq, порты listen_port/tcp+udp) ---
# --- uninstall ---
# install_server.sh --remove: бинарник + systemd; остальное — задачи uninstall.yml
hysteria2_uninstall_remove_masq: false
hysteria2_uninstall_remove_masq: true
hysteria2_uninstall_rebuild_global_index: true
hysteria2_uninstall_ufw_rules:
- "{{ hysteria2_listen_port }}/tcp"
- "{{ hysteria2_listen_port }}/udp"
- 80/tcp
- 443/tcp
- 443/udp
+1 -1
View File
@@ -2,7 +2,7 @@
galaxy_info:
role_name: hysteria2
author: inecs
description: Install Hysteria2 VPN server with Salamander obfs and export client URLs with QR codes
description: Install Hysteria2 VPN server with masquerade site and export client URLs with QR codes
license: MIT
min_ansible_version: "2.14"
platforms:
+20 -6
View File
@@ -1,11 +1,24 @@
---
- 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 Salamander server config
- name: Deploy Hysteria2 server config
ansible.builtin.template:
src: config.yaml.j2
dest: "{{ hysteria2_config_path }}"
@@ -29,11 +42,12 @@
failed_when: false
when: hysteria2_configure_firewall | bool
- name: Allow Hysteria2 port in ufw (Salamander — только {{ hysteria2_listen_port }})
- name: Allow HTTP and HTTPS in ufw
ansible.builtin.command: "ufw allow {{ item }}"
loop:
- "{{ hysteria2_listen_port }}/tcp"
- "{{ hysteria2_listen_port }}/udp"
- 80/tcp
- 443/tcp
- 443/udp
register: _hysteria2_ufw_allow
changed_when: "'Skipping' not in (_hysteria2_ufw_allow.stdout | default(''))"
failed_when: false
@@ -41,10 +55,10 @@
- hysteria2_configure_firewall | bool
- "'active' in (_hysteria2_ufw_status.stdout | default(''))"
- name: Wait for ACME TLS certificate (first start may take several minutes)
- name: Wait for ACME certificate (first start may take several minutes)
ansible.builtin.pause:
seconds: 30
prompt: "Ожидание получения ACME TLS-сертификата для {{ hysteria2_domain }}..."
prompt: "Ожидание получения ACME-сертификата для {{ hysteria2_domain }}..."
when: hysteria2_wait_for_acme | default(true) | bool
- name: Verify hysteria-server is running
-3
View File
@@ -43,10 +43,8 @@
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 }}
@@ -67,7 +65,6 @@
mode: "0644"
vars:
generated_at: "{{ now(utc=false, fmt='%Y-%m-%d %H:%M:%S') }}"
hysteria2_obfs_password: "{{ hysteria2_obfs_password }}"
delegate_to: localhost
become: false
-2
View File
@@ -33,8 +33,6 @@
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
-4
View File
@@ -7,10 +7,6 @@
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
@@ -1,58 +0,0 @@
---
- 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
-2
View File
@@ -34,8 +34,6 @@
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 }}
+7 -52
View File
@@ -14,19 +14,10 @@
dest: "{{ hysteria2_install_script_staging_dir }}/{{ hysteria2_install_script_name }}.remote"
mode: "0644"
force: true
timeout: 30
delegate_to: localhost
become: false
run_once: true
register: _hysteria2_remote_script
failed_when: false
- name: Record install script fetch result
ansible.builtin.set_fact:
_hysteria2_script_fetch_ok: "{{ not (_hysteria2_remote_script.failed | default(false)) }}"
delegate_to: localhost
become: false
run_once: true
- name: Stat local install script in role files
ansible.builtin.stat:
@@ -45,7 +36,6 @@
become: false
run_once: true
register: _hysteria2_remote_script_stat
when: _hysteria2_script_fetch_ok | bool
- name: Update bundled install script when official version is newer
ansible.builtin.copy:
@@ -55,55 +45,20 @@
delegate_to: localhost
become: false
run_once: true
when:
- _hysteria2_script_fetch_ok | bool
- >-
when: >-
not _hysteria2_local_script.stat.exists
or _hysteria2_local_script.stat.checksum
!= _hysteria2_remote_script_stat.stat.checksum
register: _hysteria2_script_updated
- name: Fail when bundled install script is missing and official fetch failed
ansible.builtin.fail:
msg: >-
Не удалось скачать {{ hysteria2_install_script_url }}
({{ _hysteria2_remote_script.msg | default('сеть недоступна') }})
и локальный roles/hysteria2/files/{{ hysteria2_install_script_name }} отсутствует.
delegate_to: localhost
become: false
run_once: true
when:
- not _hysteria2_script_fetch_ok | bool
- not _hysteria2_local_script.stat.exists
- name: Report install script sync skipped due to network error
- name: Report install script sync result
ansible.builtin.debug:
msg: >-
Пропуск синхронизации с {{ hysteria2_install_script_url }}:
{{ _hysteria2_remote_script.msg | default('сеть недоступна') }}.
Используется локальный roles/hysteria2/files/{{ hysteria2_install_script_name }}.
{{
'Официальный 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
when: not _hysteria2_script_fetch_ok | bool
- name: Report install script updated from official server
ansible.builtin.debug:
msg: Официальный install_server.sh обновлён в roles/hysteria2/files/
delegate_to: localhost
become: false
run_once: true
when:
- _hysteria2_script_fetch_ok | bool
- _hysteria2_script_updated.changed | default(false)
- name: Report install script already up to date
ansible.builtin.debug:
msg: >-
Локальный install_server.sh актуален (совпадает с {{ hysteria2_install_script_url }}).
delegate_to: localhost
become: false
run_once: true
when:
- _hysteria2_script_fetch_ok | bool
- not (_hysteria2_script_updated.changed | default(false))
+7 -1
View File
@@ -32,6 +32,12 @@
- "{{ hysteria2_config_path | dirname }}"
- "/var/lib/{{ hysteria2_system_user | default('hysteria') }}"
- name: Remove masquerade web directory
ansible.builtin.file:
path: "{{ hysteria2_masq_dir }}"
state: absent
when: hysteria2_uninstall_remove_masq | default(true) | bool
- name: Remove enabled hysteria-server systemd symlink
ansible.builtin.file:
path: /etc/systemd/system/multi-user.target.wants/hysteria-server.service
@@ -124,7 +130,7 @@
- name: Show uninstall result
ansible.builtin.debug:
msg: >-
Hysteria2 (Salamander) полностью удалён с {{ inventory_hostname }}.
Hysteria2 полностью удалён с {{ inventory_hostname }}.
Локальная папка {{ hysteria2_output_dir }}/{{ hysteria2_output_name }}/ удалена.
{% if hysteria2_uninstall_rebuild_global_index | default(true) | bool %}
{{ hysteria2_output_dir }}/index.html будет пересобран без этого сервера.
+1 -1
View File
@@ -7,7 +7,7 @@
- hysteria2_users | length > 0
fail_msg: |
Задайте для каждого хоста:
hysteria2_domain — домен с A-записью на IP сервера (используется для TLS/SNI)
hysteria2_domain — домен с A-записью на IP сервера
hysteria2_users — список имён пользователей, например [my, friend]
И в group_vars/all.yml:
hysteria2_acme_email — email для Let's Encrypt
-5
View File
@@ -1,8 +1,3 @@
server: {{ hysteria2_domain }}:{{ hysteria2_listen_port }}
auth: {{ hysteria2_current_user.name }}:{{ hysteria2_current_user.password }}
obfs:
type: salamander
salamander:
password: {{ hysteria2_obfs_password }}
+8 -5
View File
@@ -1,7 +1,7 @@
listen: 0.0.0.0:{{ hysteria2_listen_port }}
acme:
type: tls
type: http
domains:
- {{ hysteria2_domain }}
email: {{ hysteria2_acme_email }}
@@ -13,7 +13,10 @@ auth:
{{ user.name }}: "{{ user.password }}"
{% endfor %}
obfs:
type: salamander
salamander:
password: "{{ hysteria2_obfs_password }}"
masquerade:
type: file
file:
dir: {{ hysteria2_masq_dir }}
listenHTTP: :80
listenHTTPS: :{{ hysteria2_listen_port }}
forceHTTPS: true
@@ -160,17 +160,6 @@
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));
@@ -297,8 +286,8 @@
</head>
<body>
<header class="hero">
<h1>Hysteria2 · Salamander</h1>
<p>Общий каталог VPN-подключений с обфускацией Salamander</p>
<h1>Hysteria2</h1>
<p>Общий каталог VPN-подключений</p>
<div class="stats">
<div class="stat"><span>{{ hysteria2_global_servers | length }}</span> серверов</div>
<div class="stat"><span>{{ total_users }}</span> пользователей</div>
@@ -318,18 +307,6 @@
<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,15 +75,6 @@
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);
@@ -244,17 +235,6 @@
Домен: <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 %}
@@ -0,0 +1,27 @@
<!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>