356 lines
15 KiB
YAML
356 lines
15 KiB
YAML
---
|
|
- name: Разрешить порты панели
|
|
ansible.builtin.command: ufw allow {{ item }}
|
|
register: ufw_rule
|
|
changed_when: "'added' in (ufw_rule.stdout | lower)"
|
|
loop: "{{ netbird_ports }}"
|
|
|
|
- name: Поставить openssl, curl и jq
|
|
ansible.builtin.apt:
|
|
name:
|
|
- openssl
|
|
- curl
|
|
- jq
|
|
state: present
|
|
|
|
- name: Создать каталог панели
|
|
ansible.builtin.file:
|
|
path: "{{ netbird_dir }}"
|
|
state: directory
|
|
owner: root
|
|
group: root
|
|
mode: "0700"
|
|
|
|
- name: Проверить наличие обязательных секретов NetBird
|
|
ansible.builtin.assert:
|
|
that:
|
|
- netbird_domain is defined and netbird_domain | length > 3
|
|
- netbird_auth_secret is defined and netbird_auth_secret | length > 0
|
|
- netbird_datastore_key is defined and netbird_datastore_key | length > 0
|
|
- netbird_session_key is defined and netbird_session_key | length > 0
|
|
- netbird_letsencrypt_email is defined and netbird_letsencrypt_email | length > 3
|
|
- netbird_admin_email is defined and netbird_admin_email | length > 3
|
|
- netbird_admin_name is defined and netbird_admin_name | length > 0
|
|
- netbird_admin_password is defined and netbird_admin_password | length >= 8
|
|
fail_msg: "Не задан домен NetBird (host_vars) или один из секретов NETBIRD_AUTH_SECRET, NETBIRD_DATASTORE_KEY, NETBIRD_SESSION_KEY, NETBIRD_LETSENCRYPT_EMAIL, NETBIRD_ADMIN_EMAIL, NETBIRD_ADMIN_NAME, NETBIRD_ADMIN_PASSWORD (мин. 8 символов)."
|
|
|
|
- name: Записать .env
|
|
ansible.builtin.template:
|
|
src: env.j2
|
|
dest: "{{ netbird_dir }}/.env"
|
|
owner: root
|
|
group: root
|
|
mode: "0600"
|
|
no_log: true
|
|
notify: Перезапустить NetBird
|
|
|
|
- name: Положить манифест панели
|
|
ansible.builtin.copy:
|
|
src: compose.yaml
|
|
dest: "{{ netbird_dir }}/compose.yaml"
|
|
owner: root
|
|
group: root
|
|
mode: "0644"
|
|
notify: Перезапустить NetBird
|
|
|
|
- name: Собрать dashboard.env
|
|
ansible.builtin.template:
|
|
src: dashboard.env.j2
|
|
dest: "{{ netbird_dir }}/dashboard.env"
|
|
owner: root
|
|
group: root
|
|
mode: "0644"
|
|
notify: Перезапустить NetBird
|
|
|
|
- name: Собрать config.yaml
|
|
ansible.builtin.template:
|
|
src: config.yaml.j2
|
|
dest: "{{ netbird_dir }}/config.yaml"
|
|
owner: root
|
|
group: root
|
|
mode: "0600"
|
|
no_log: true
|
|
notify: Перезапустить NetBird
|
|
|
|
- name: Применить изменения конфигурации
|
|
ansible.builtin.meta: flush_handlers
|
|
|
|
- name: Убедиться, что панель запущена
|
|
ansible.builtin.command: docker compose up -d
|
|
args:
|
|
chdir: "{{ netbird_dir }}"
|
|
register: compose_up
|
|
changed_when: "'Started' in compose_up.stderr or 'Created' in compose_up.stderr or 'Recreated' in compose_up.stderr"
|
|
|
|
- name: Показать состояние контейнеров
|
|
ansible.builtin.command: docker compose ps
|
|
args:
|
|
chdir: "{{ netbird_dir }}"
|
|
register: compose_ps
|
|
changed_when: false
|
|
|
|
- name: Дождаться ответа панели и API
|
|
ansible.builtin.command: >
|
|
curl -fsSk --resolve {{ netbird_domain }}:443:127.0.0.1
|
|
https://{{ netbird_domain }}/api/instance
|
|
register: instance_status
|
|
changed_when: false
|
|
retries: 30
|
|
delay: 5
|
|
until: instance_status.rc == 0 and ('setup_required' in instance_status.stdout)
|
|
|
|
- name: Инициализировать NetBird API (администратор, токен, группа, маршрут и ключ установки)
|
|
ansible.builtin.shell: |
|
|
set -euo pipefail
|
|
|
|
API_BASE="https://{{ netbird_domain }}/api"
|
|
CURL_OPTS=(-fsSk --resolve "{{ netbird_domain }}:443:127.0.0.1")
|
|
|
|
admin_created=0
|
|
token_updated=0
|
|
setup_key_updated=0
|
|
route_created=0
|
|
|
|
setup_req=$(curl "${CURL_OPTS[@]}" "${API_BASE}/instance" | jq -r '.setup_required')
|
|
bootstrap_auth_header=""
|
|
|
|
if [ "${setup_req}" = "true" ]; then
|
|
setup_payload=$(jq -n \
|
|
--arg email "$NB_ADMIN_EMAIL" \
|
|
--arg password "$NB_ADMIN_PASSWORD" \
|
|
--arg name "$NB_ADMIN_NAME" \
|
|
'{email: $email, password: $password, name: $name, create_pat: true}')
|
|
setup_resp=$(curl "${CURL_OPTS[@]}" -X POST "${API_BASE}/setup" \
|
|
-H "Content-Type: application/json" \
|
|
-d "${setup_payload}")
|
|
bootstrap_token=$(printf '%s' "${setup_resp}" | jq -r '.personal_access_token // empty')
|
|
if [ -z "${bootstrap_token}" ]; then
|
|
echo "Не удалось получить personal_access_token из /api/setup" >&2
|
|
exit 1
|
|
fi
|
|
bootstrap_auth_header="Authorization: Token ${bootstrap_token}"
|
|
admin_created=1
|
|
fi
|
|
|
|
active_token="${NB_API_TOKEN:-}"
|
|
token_valid=0
|
|
if [ -n "${active_token}" ]; then
|
|
http_code=$(curl -sSk --resolve "{{ netbird_domain }}:443:127.0.0.1" -o /dev/null -w '%{http_code}' \
|
|
-H "Authorization: Token ${active_token}" "${API_BASE}/users" || true)
|
|
if [ "${http_code}" = "200" ]; then
|
|
token_valid=1
|
|
fi
|
|
fi
|
|
|
|
if [ "${token_valid}" -eq 0 ]; then
|
|
if [ -z "${bootstrap_auth_header}" ]; then
|
|
verifier="dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
|
|
challenge="E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
|
|
redirect_uri="https://{{ netbird_domain }}/nb-auth"
|
|
auth_url="https://{{ netbird_domain }}/oauth2/auth?client_id=netbird-dashboard&redirect_uri=${redirect_uri}&response_type=code&scope=openid+profile+email+groups&code_challenge=${challenge}&code_challenge_method=S256&state=ansible"
|
|
|
|
login_page=$(curl -sLk --resolve "{{ netbird_domain }}:443:127.0.0.1" "${auth_url}")
|
|
login_action=$(printf '%s' "${login_page}" | grep -oE 'action="[^"]+"' | head -n 1 | cut -d'"' -f2 | sed 's/&/\&/g')
|
|
if [ -z "${login_action}" ]; then
|
|
echo "Не удалось получить форму входа OAuth2 для выпуска токена" >&2
|
|
exit 1
|
|
fi
|
|
|
|
redir_loc=$(curl -sSk --resolve "{{ netbird_domain }}:443:127.0.0.1" -o /dev/null -w '%{redirect_url}' \
|
|
-X POST "https://{{ netbird_domain }}${login_action}" \
|
|
--data-urlencode "login=${NB_ADMIN_EMAIL}" \
|
|
--data-urlencode "password=${NB_ADMIN_PASSWORD}")
|
|
|
|
if printf '%s' "${redir_loc}" | grep -q '/oauth2/approval'; then
|
|
redir_loc=$(curl -sSk --resolve "{{ netbird_domain }}:443:127.0.0.1" -o /dev/null -w '%{redirect_url}' "${redir_loc}")
|
|
fi
|
|
|
|
auth_code=$(printf '%s' "${redir_loc}" | sed -n 's/.*[?&]code=\([^&]*\).*/\1/p')
|
|
if [ -z "${auth_code}" ]; then
|
|
echo "Не удалось получить authorization code через OAuth2 (проверьте NETBIRD_ADMIN_EMAIL / NETBIRD_ADMIN_PASSWORD)" >&2
|
|
exit 1
|
|
fi
|
|
|
|
token_resp=$(curl "${CURL_OPTS[@]}" -X POST "https://{{ netbird_domain }}/oauth2/token" \
|
|
--data-urlencode "grant_type=authorization_code" \
|
|
--data-urlencode "client_id=netbird-dashboard" \
|
|
--data-urlencode "redirect_uri=${redirect_uri}" \
|
|
--data-urlencode "code=${auth_code}" \
|
|
--data-urlencode "code_verifier=${verifier}")
|
|
jwt_token=$(printf '%s' "${token_resp}" | jq -r '.access_token // .id_token // empty')
|
|
if [ -z "${jwt_token}" ]; then
|
|
echo "Не удалось обменять authorization code на JWT токен" >&2
|
|
exit 1
|
|
fi
|
|
bootstrap_auth_header="Authorization: Bearer ${jwt_token}"
|
|
fi
|
|
|
|
users_json=$(curl "${CURL_OPTS[@]}" -H "${bootstrap_auth_header}" "${API_BASE}/users")
|
|
svc_user_id=$(printf '%s' "${users_json}" | jq -r '.[] | select(.is_service_user == true and .name == "infra-automation") | .id' | head -n 1)
|
|
|
|
if [ -z "${svc_user_id}" ]; then
|
|
user_payload=$(jq -n '{name: "infra-automation", role: "admin", auto_groups: [], is_service_user: true}')
|
|
svc_user_resp=$(curl "${CURL_OPTS[@]}" -X POST "${API_BASE}/users" \
|
|
-H "${bootstrap_auth_header}" \
|
|
-H "Content-Type: application/json" \
|
|
-d "${user_payload}")
|
|
svc_user_id=$(printf '%s' "${svc_user_resp}" | jq -r '.id')
|
|
fi
|
|
|
|
old_tokens=$(curl "${CURL_OPTS[@]}" -H "${bootstrap_auth_header}" "${API_BASE}/users/${svc_user_id}/tokens" || echo "[]")
|
|
for old_tid in $(printf '%s' "${old_tokens}" | jq -r '.[] | select(.name == "infisical-ci-token") | .id'); do
|
|
curl "${CURL_OPTS[@]}" -X DELETE -H "${bootstrap_auth_header}" "${API_BASE}/users/${svc_user_id}/tokens/${old_tid}" >/dev/null || true
|
|
done
|
|
|
|
pat_payload=$(jq -n '{name: "infisical-ci-token", expires_in: 365}')
|
|
pat_resp=$(curl "${CURL_OPTS[@]}" -X POST "${API_BASE}/users/${svc_user_id}/tokens" \
|
|
-H "${bootstrap_auth_header}" \
|
|
-H "Content-Type: application/json" \
|
|
-d "${pat_payload}")
|
|
active_token=$(printf '%s' "${pat_resp}" | jq -r '.plain_token // .plain_text // empty')
|
|
if [ -z "${active_token}" ]; then
|
|
echo "Не удалось выпустить сервисный токен через /api/users/${svc_user_id}/tokens" >&2
|
|
exit 1
|
|
fi
|
|
token_updated=1
|
|
fi
|
|
|
|
groups_json=$(curl "${CURL_OPTS[@]}" -H "Authorization: Token ${active_token}" "${API_BASE}/groups")
|
|
all_group_id=$(printf '%s' "${groups_json}" | jq -r '.[] | select(.name == "All") | .id' | head -n 1)
|
|
router_group_id=$(printf '%s' "${groups_json}" | jq -r --arg g "$NB_ROUTER_GROUP" '.[] | select(.name == $g) | .id' | head -n 1)
|
|
|
|
if [ -z "${router_group_id}" ]; then
|
|
grp_payload=$(jq -n --arg name "$NB_ROUTER_GROUP" '{name: $name, peers: []}')
|
|
grp_resp=$(curl "${CURL_OPTS[@]}" -X POST "${API_BASE}/groups" \
|
|
-H "Authorization: Token ${active_token}" \
|
|
-H "Content-Type: application/json" \
|
|
-d "${grp_payload}")
|
|
router_group_id=$(printf '%s' "${grp_resp}" | jq -r '.id')
|
|
fi
|
|
|
|
routes_json=$(curl "${CURL_OPTS[@]}" -H "Authorization: Token ${active_token}" "${API_BASE}/routes")
|
|
existing_route_id=$(printf '%s' "${routes_json}" | jq -r --arg nid "$NB_LAN_NET_ID" --arg net "$NB_LAN_SUBNET" '.[] | select(.network_id == $nid or .network == $net) | .id' | head -n 1)
|
|
|
|
if [ -z "${existing_route_id}" ]; then
|
|
route_payload=$(jq -n \
|
|
--arg desc "Homelab LAN (${NB_LAN_SUBNET} via OPNsense)" \
|
|
--arg nid "$NB_LAN_NET_ID" \
|
|
--arg net "$NB_LAN_SUBNET" \
|
|
--arg rg "$router_group_id" \
|
|
--arg ag "$all_group_id" \
|
|
'{
|
|
description: $desc,
|
|
network_id: $nid,
|
|
enabled: true,
|
|
peer_groups: [$rg],
|
|
network: $net,
|
|
metric: 100,
|
|
masquerade: true,
|
|
groups: [$ag],
|
|
keep_route: true
|
|
}')
|
|
curl "${CURL_OPTS[@]}" -X POST "${API_BASE}/routes" \
|
|
-H "Authorization: Token ${active_token}" \
|
|
-H "Content-Type: application/json" \
|
|
-d "${route_payload}" >/dev/null
|
|
route_created=1
|
|
fi
|
|
|
|
active_setup_key="${NB_SETUP_KEY:-}"
|
|
keys_json=$(curl "${CURL_OPTS[@]}" -H "Authorization: Token ${active_token}" "${API_BASE}/setup-keys")
|
|
valid_key_id=$(printf '%s' "${keys_json}" | jq -r --arg kname "$NB_SETUP_KEY_NAME" '.[] | select(.name == $kname and .valid == true and .revoked == false) | .id' | head -n 1)
|
|
|
|
if [ -z "${active_setup_key}" ] || [ -z "${valid_key_id}" ]; then
|
|
for old_kid in $(printf '%s' "${keys_json}" | jq -r --arg kname "$NB_SETUP_KEY_NAME" '.[] | select(.name == $kname) | .id'); do
|
|
curl "${CURL_OPTS[@]}" -X DELETE -H "Authorization: Token ${active_token}" "${API_BASE}/setup-keys/${old_kid}" >/dev/null || true
|
|
done
|
|
key_payload=$(jq -n \
|
|
--arg name "$NB_SETUP_KEY_NAME" \
|
|
--arg rg "$router_group_id" \
|
|
'{
|
|
name: $name,
|
|
type: "reusable",
|
|
expires_in: 31536000,
|
|
revoked: false,
|
|
auto_groups: [$rg],
|
|
usage_limit: 0,
|
|
ephemeral: false
|
|
}')
|
|
key_resp=$(curl "${CURL_OPTS[@]}" -X POST "${API_BASE}/setup-keys" \
|
|
-H "Authorization: Token ${active_token}" \
|
|
-H "Content-Type: application/json" \
|
|
-d "${key_payload}")
|
|
active_setup_key=$(printf '%s' "${key_resp}" | jq -r '.key // empty')
|
|
if [ -z "${active_setup_key}" ]; then
|
|
echo "Не удалось создать ключ установки через /api/setup-keys" >&2
|
|
exit 1
|
|
fi
|
|
setup_key_updated=1
|
|
fi
|
|
|
|
jq -n \
|
|
--arg api_token "${active_token}" \
|
|
--arg setup_key "${active_setup_key}" \
|
|
--argjson admin_created "${admin_created}" \
|
|
--argjson token_updated "${token_updated}" \
|
|
--argjson setup_key_updated "${setup_key_updated}" \
|
|
--argjson route_created "${route_created}" \
|
|
'{
|
|
api_token: $api_token,
|
|
setup_key: $setup_key,
|
|
admin_created: ($admin_created == 1),
|
|
token_updated: ($token_updated == 1),
|
|
setup_key_updated: ($setup_key_updated == 1),
|
|
route_created: ($route_created == 1),
|
|
changed: (($admin_created + $token_updated + $setup_key_updated + $route_created) > 0)
|
|
}'
|
|
args:
|
|
executable: /bin/bash
|
|
environment:
|
|
NB_ADMIN_EMAIL: "{{ netbird_admin_email }}"
|
|
NB_ADMIN_NAME: "{{ netbird_admin_name }}"
|
|
NB_ADMIN_PASSWORD: "{{ netbird_admin_password }}"
|
|
NB_API_TOKEN: "{{ netbird_api_token }}"
|
|
NB_SETUP_KEY: "{{ netbird_setup_key }}"
|
|
NB_ROUTER_GROUP: "{{ netbird_router_group_name }}"
|
|
NB_SETUP_KEY_NAME: "{{ netbird_setup_key_name }}"
|
|
NB_LAN_NET_ID: "{{ netbird_lan_network_id }}"
|
|
NB_LAN_SUBNET: "{{ netbird_lan_subnet }}"
|
|
register: netbird_bootstrap_raw
|
|
changed_when: (netbird_bootstrap_raw.stdout | from_json).changed
|
|
no_log: true
|
|
|
|
- name: Сохранить сгенерированные ключи NetBird в Infisical
|
|
ansible.builtin.shell: |
|
|
set -euo pipefail
|
|
infisical secrets set \
|
|
--domain="${INFISICAL_DOMAIN}" \
|
|
--token="${INFISICAL_TOKEN}" \
|
|
--env=prod \
|
|
--projectId="${INFISICAL_PROJECT_ID}" \
|
|
--path="/services/netbird" \
|
|
"NETBIRD_API_TOKEN=${NEW_API_TOKEN}" \
|
|
"NETBIRD_SETUP_KEY=${NEW_SETUP_KEY}" \
|
|
--silent
|
|
args:
|
|
executable: /bin/bash
|
|
delegate_to: localhost
|
|
become: false
|
|
environment:
|
|
NEW_API_TOKEN: "{{ (netbird_bootstrap_raw.stdout | from_json).api_token }}"
|
|
NEW_SETUP_KEY: "{{ (netbird_bootstrap_raw.stdout | from_json).setup_key }}"
|
|
when: (netbird_bootstrap_raw.stdout | from_json).token_updated or (netbird_bootstrap_raw.stdout | from_json).setup_key_updated
|
|
changed_when: true
|
|
no_log: true
|
|
|
|
- name: Итог установки
|
|
vars:
|
|
nb_state: "{{ netbird_bootstrap_raw.stdout | from_json }}"
|
|
ansible.builtin.debug:
|
|
msg:
|
|
- "Панель: https://{{ netbird_domain }}"
|
|
- "Суперпользователь создан в этом прогоне: {{ nb_state.admin_created }}"
|
|
- "API-токен обновлен в Infisical: {{ nb_state.token_updated }}"
|
|
- "Setup-ключ обновлен в Infisical: {{ nb_state.setup_key_updated }}"
|
|
- "Маршрут {{ netbird_lan_subnet }} создан в этом прогоне: {{ nb_state.route_created }}"
|