feat(netbird): automate admin setup, API token, setup key, and LAN route on rus-central
This commit is contained in:
1 parent
842a633916
commit
324327ee24
13 files changed
+515
-17
No files matched your search
+1
-1
@@ -1,6 +1,6 @@
|
||||
[defaults]
|
||||
inventory = inventories/prod/hosts.yml
|
||||
roles_path = roles
|
||||
roles_path = roles:ansible/roles
|
||||
retry_files_enabled = false
|
||||
stdout_callback = default
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ before=${3:-}
|
||||
after=${4:-}
|
||||
|
||||
case "$machine" in
|
||||
core-net | core-secrets | rus-central) ;;
|
||||
core-net | core-secrets | rus-central | opnsense) ;;
|
||||
*)
|
||||
echo "Неизвестная машина: $machine" >&2
|
||||
exit 2
|
||||
|
||||
@@ -9,7 +9,7 @@ before=${3:-}
|
||||
after=${4:-}
|
||||
|
||||
case "$machine" in
|
||||
core-net | core-secrets | rus-central) ;;
|
||||
core-net | core-secrets | rus-central | opnsense) ;;
|
||||
*)
|
||||
echo "Неизвестная машина: $machine" >&2
|
||||
exit 2
|
||||
@@ -30,6 +30,7 @@ TOKEN=$(infisical login \
|
||||
--client-id="${INFISICAL_CLIENT_ID}" \
|
||||
--client-secret="${INFISICAL_CLIENT_SECRET}" \
|
||||
--plain)
|
||||
export INFISICAL_TOKEN="${TOKEN}"
|
||||
|
||||
eval "$(infisical export --domain="${INFISICAL_DOMAIN}" --token="${TOKEN}" --env=prod --projectId="${INFISICAL_PROJECT_ID}" --path="/ci-cd" --format=dotenv-export --silent)"
|
||||
|
||||
@@ -73,6 +74,11 @@ case "$machine" in
|
||||
export NETBIRD_AUTH_SECRET="${NETBIRD_AUTH_SECRET:-}"
|
||||
export NETBIRD_DATASTORE_KEY="${NETBIRD_DATASTORE_KEY:-}"
|
||||
export NETBIRD_SESSION_KEY="${NETBIRD_SESSION_KEY:-}"
|
||||
export NETBIRD_ADMIN_EMAIL="${NETBIRD_ADMIN_EMAIL:-}"
|
||||
export NETBIRD_ADMIN_NAME="${NETBIRD_ADMIN_NAME:-}"
|
||||
export NETBIRD_ADMIN_PASSWORD="${NETBIRD_ADMIN_PASSWORD:-}"
|
||||
export NETBIRD_API_TOKEN="${NETBIRD_API_TOKEN:-}"
|
||||
export NETBIRD_SETUP_KEY="${NETBIRD_SETUP_KEY:-}"
|
||||
if [ -n "$input_email" ]; then
|
||||
NETBIRD_LETSENCRYPT_EMAIL="$input_email"
|
||||
fi
|
||||
@@ -80,6 +86,13 @@ case "$machine" in
|
||||
extra+=(-e "netbird_letsencrypt_email=${NETBIRD_LETSENCRYPT_EMAIL}")
|
||||
fi
|
||||
;;
|
||||
opnsense)
|
||||
eval "$(infisical export --domain="${INFISICAL_DOMAIN}" --token="${TOKEN}" --env=prod --projectId="${INFISICAL_PROJECT_ID}" --path="/services/netbird" --format=dotenv-export --silent)"
|
||||
eval "$(infisical export --domain="${INFISICAL_DOMAIN}" --token="${TOKEN}" --env=prod --projectId="${INFISICAL_PROJECT_ID}" --path="/services/opnsense" --format=dotenv-export --silent)"
|
||||
export NETBIRD_SETUP_KEY="${NETBIRD_SETUP_KEY:-}"
|
||||
export OPNSENSE_API_KEY="${OPNSENSE_API_KEY:-}"
|
||||
export OPNSENSE_API_SECRET="${OPNSENSE_API_SECRET:-}"
|
||||
;;
|
||||
esac
|
||||
|
||||
root=$(CDPATH= cd -- "$(dirname "$0")/../.." && pwd)
|
||||
|
||||
@@ -10,3 +10,6 @@ all:
|
||||
rus-central:
|
||||
ansible_host: 45.154.185.208
|
||||
ansible_user: root
|
||||
opnsense:
|
||||
ansible_host: 192.168.1.1
|
||||
ansible_connection: local
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
- name: Подготовить машину
|
||||
hosts: all
|
||||
hosts: all:!opnsense
|
||||
gather_facts: false
|
||||
roles:
|
||||
- role: host
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
- name: Маршрутизатор OPNsense
|
||||
hosts: opnsense
|
||||
gather_facts: false
|
||||
roles:
|
||||
- role: opnsense/netbird
|
||||
tags: [netbird]
|
||||
@@ -3,3 +3,4 @@
|
||||
- ansible.builtin.import_playbook: core-net.yml
|
||||
- ansible.builtin.import_playbook: core-secrets.yml
|
||||
- ansible.builtin.import_playbook: rus-central.yml
|
||||
- ansible.builtin.import_playbook: opnsense.yml
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
opnsense_host: "192.168.1.1"
|
||||
opnsense_api_key: "{{ lookup('env', 'OPNSENSE_API_KEY') }}"
|
||||
opnsense_api_secret: "{{ lookup('env', 'OPNSENSE_API_SECRET') }}"
|
||||
|
||||
opnsense_netbird_management_url: "https://central.gunihome.ru:443"
|
||||
netbird_setup_key: "{{ lookup('env', 'NETBIRD_SETUP_KEY') }}"
|
||||
|
||||
opnsense_netbird_wg_port: "51820"
|
||||
opnsense_netbird_ssh_enable: "1"
|
||||
@@ -0,0 +1,223 @@
|
||||
---
|
||||
- name: Проверить наличие обязательных секретов OPNsense и NetBird
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- opnsense_api_key is defined and opnsense_api_key | length > 0
|
||||
- opnsense_api_secret is defined and opnsense_api_secret | length > 0
|
||||
- netbird_setup_key is defined and netbird_setup_key | length > 0
|
||||
- opnsense_netbird_management_url is defined and opnsense_netbird_management_url | length > 0
|
||||
fail_msg: "Отсутствует один из обязательных секретов: OPNSENSE_API_KEY, OPNSENSE_API_SECRET или NETBIRD_SETUP_KEY."
|
||||
|
||||
- name: Проверить наличие плагина os-netbird в OPNsense
|
||||
ansible.builtin.uri:
|
||||
url: "https://{{ opnsense_host }}/api/netbird/settings/get"
|
||||
method: GET
|
||||
url_username: "{{ opnsense_api_key }}"
|
||||
url_password: "{{ opnsense_api_secret }}"
|
||||
force_basic_auth: true
|
||||
validate_certs: false
|
||||
status_code: [200, 404]
|
||||
register: opnsense_nb_check
|
||||
|
||||
- name: Установить плагин os-netbird (если отсутствует)
|
||||
ansible.builtin.uri:
|
||||
url: "https://{{ opnsense_host }}/api/core/firmware/install/os-netbird"
|
||||
method: POST
|
||||
url_username: "{{ opnsense_api_key }}"
|
||||
url_password: "{{ opnsense_api_secret }}"
|
||||
force_basic_auth: true
|
||||
validate_certs: false
|
||||
body_format: json
|
||||
body: {}
|
||||
status_code: [200]
|
||||
when: opnsense_nb_check.status == 404
|
||||
|
||||
- name: Дождаться появления API плагина os-netbird после установки
|
||||
ansible.builtin.uri:
|
||||
url: "https://{{ opnsense_host }}/api/netbird/settings/get"
|
||||
method: GET
|
||||
url_username: "{{ opnsense_api_key }}"
|
||||
url_password: "{{ opnsense_api_secret }}"
|
||||
force_basic_auth: true
|
||||
validate_certs: false
|
||||
status_code: [200]
|
||||
register: opnsense_nb_settings_wait
|
||||
retries: 30
|
||||
delay: 5
|
||||
until: opnsense_nb_settings_wait.status == 200
|
||||
when: opnsense_nb_check.status == 404
|
||||
|
||||
- name: Сформировать текущие настройки плагина os-netbird
|
||||
ansible.builtin.set_fact:
|
||||
opnsense_nb_current_settings: "{{ (opnsense_nb_settings_wait.json if opnsense_nb_check.status == 404 else opnsense_nb_check.json).settings }}"
|
||||
|
||||
- name: Применить настройки сервиса NetBird в OPNsense
|
||||
vars:
|
||||
need_settings_update: >-
|
||||
{{
|
||||
(opnsense_nb_current_settings.general.enable | string) != '1' or
|
||||
(opnsense_nb_current_settings.general.wireguardPort | string) != (opnsense_netbird_wg_port | string) or
|
||||
(opnsense_nb_current_settings.firewall.allowConfig | string) != '1' or
|
||||
(opnsense_nb_current_settings.firewall.blockInboundConnection | string) != '0' or
|
||||
(opnsense_nb_current_settings.ssh.enable | string) != (opnsense_netbird_ssh_enable | string) or
|
||||
(opnsense_nb_current_settings.dns.enable | string) != '1' or
|
||||
(opnsense_nb_current_settings.routing.accessLan | string) != '1' or
|
||||
(opnsense_nb_current_settings.routing.acceptClientRoutes | string) != '1' or
|
||||
(opnsense_nb_current_settings.routing.acceptServerRoutes | string) != '1'
|
||||
}}
|
||||
ansible.builtin.uri:
|
||||
url: "https://{{ opnsense_host }}/api/netbird/settings/set"
|
||||
method: POST
|
||||
url_username: "{{ opnsense_api_key }}"
|
||||
url_password: "{{ opnsense_api_secret }}"
|
||||
force_basic_auth: true
|
||||
validate_certs: false
|
||||
body_format: json
|
||||
body:
|
||||
settings:
|
||||
general:
|
||||
enable: "1"
|
||||
wireguardPort: "{{ opnsense_netbird_wg_port }}"
|
||||
firewall:
|
||||
allowConfig: "1"
|
||||
blockInboundConnection: "0"
|
||||
ssh:
|
||||
enable: "{{ opnsense_netbird_ssh_enable }}"
|
||||
dns:
|
||||
enable: "1"
|
||||
routing:
|
||||
accessLan: "1"
|
||||
acceptClientRoutes: "1"
|
||||
acceptServerRoutes: "1"
|
||||
postquantum:
|
||||
enableRosenpass: "0"
|
||||
rosenpassPermissive: "0"
|
||||
syslog:
|
||||
logLevel: "info"
|
||||
status_code: [200]
|
||||
register: opnsense_nb_settings_set
|
||||
when: need_settings_update
|
||||
changed_when: true
|
||||
|
||||
- name: Переконфигурировать сервис NetBird в OPNsense
|
||||
ansible.builtin.uri:
|
||||
url: "https://{{ opnsense_host }}/api/netbird/service/reconfigure"
|
||||
method: POST
|
||||
url_username: "{{ opnsense_api_key }}"
|
||||
url_password: "{{ opnsense_api_secret }}"
|
||||
force_basic_auth: true
|
||||
validate_certs: false
|
||||
body_format: json
|
||||
body: {}
|
||||
status_code: [200]
|
||||
when: opnsense_nb_settings_set is changed
|
||||
changed_when: true
|
||||
|
||||
- name: Проверить статус службы NetBird в OPNsense
|
||||
ansible.builtin.uri:
|
||||
url: "https://{{ opnsense_host }}/api/netbird/service/status"
|
||||
method: GET
|
||||
url_username: "{{ opnsense_api_key }}"
|
||||
url_password: "{{ opnsense_api_secret }}"
|
||||
force_basic_auth: true
|
||||
validate_certs: false
|
||||
status_code: [200]
|
||||
register: opnsense_nb_service_status
|
||||
|
||||
- name: Запустить службу NetBird в OPNsense (если остановлена)
|
||||
ansible.builtin.uri:
|
||||
url: "https://{{ opnsense_host }}/api/netbird/service/start"
|
||||
method: POST
|
||||
url_username: "{{ opnsense_api_key }}"
|
||||
url_password: "{{ opnsense_api_secret }}"
|
||||
force_basic_auth: true
|
||||
validate_certs: false
|
||||
body_format: json
|
||||
body: {}
|
||||
status_code: [200]
|
||||
when: (opnsense_nb_service_status.json.status | default('')) != 'running'
|
||||
changed_when: true
|
||||
|
||||
- name: Проверить текущее подключение NetBird в OPNsense
|
||||
ansible.builtin.uri:
|
||||
url: "https://{{ opnsense_host }}/api/netbird/status/status"
|
||||
method: GET
|
||||
url_username: "{{ opnsense_api_key }}"
|
||||
url_password: "{{ opnsense_api_secret }}"
|
||||
force_basic_auth: true
|
||||
validate_certs: false
|
||||
status_code: [200]
|
||||
register: opnsense_nb_status
|
||||
|
||||
- name: Задать параметры аутентификации NetBird (Management URL и Setup Key)
|
||||
vars:
|
||||
nb_connected: "{{ opnsense_nb_status.json.management.connected | default(false) | bool }}"
|
||||
nb_current_url: "{{ opnsense_nb_status.json.management.url | default('') }}"
|
||||
ansible.builtin.uri:
|
||||
url: "https://{{ opnsense_host }}/api/netbird/authentication/set"
|
||||
method: POST
|
||||
url_username: "{{ opnsense_api_key }}"
|
||||
url_password: "{{ opnsense_api_secret }}"
|
||||
force_basic_auth: true
|
||||
validate_certs: false
|
||||
body_format: json
|
||||
body:
|
||||
authentication:
|
||||
managementUrl: "{{ opnsense_netbird_management_url }}"
|
||||
setupKey: "{{ netbird_setup_key }}"
|
||||
status_code: [200]
|
||||
register: opnsense_nb_auth_set
|
||||
when: (not nb_connected) or (nb_current_url != opnsense_netbird_management_url)
|
||||
changed_when: true
|
||||
no_log: true
|
||||
|
||||
- name: Подключить OPNsense к координатору NetBird (authentication/up)
|
||||
ansible.builtin.uri:
|
||||
url: "https://{{ opnsense_host }}/api/netbird/authentication/up"
|
||||
method: POST
|
||||
url_username: "{{ opnsense_api_key }}"
|
||||
url_password: "{{ opnsense_api_secret }}"
|
||||
force_basic_auth: true
|
||||
validate_certs: false
|
||||
body_format: json
|
||||
body: {}
|
||||
status_code: [200]
|
||||
when: opnsense_nb_auth_set is changed
|
||||
changed_when: true
|
||||
|
||||
- name: Синхронизировать конфигурацию клиента NetBird в OPNsense
|
||||
ansible.builtin.uri:
|
||||
url: "https://{{ opnsense_host }}/api/netbird/settings/sync"
|
||||
method: GET
|
||||
url_username: "{{ opnsense_api_key }}"
|
||||
url_password: "{{ opnsense_api_secret }}"
|
||||
force_basic_auth: true
|
||||
validate_certs: false
|
||||
status_code: [200]
|
||||
when: opnsense_nb_settings_set is changed or opnsense_nb_auth_set is changed
|
||||
changed_when: true
|
||||
|
||||
- name: Дождаться перехода пира OPNsense в состояние connected на новом сервере
|
||||
ansible.builtin.uri:
|
||||
url: "https://{{ opnsense_host }}/api/netbird/status/status"
|
||||
method: GET
|
||||
url_username: "{{ opnsense_api_key }}"
|
||||
url_password: "{{ opnsense_api_secret }}"
|
||||
force_basic_auth: true
|
||||
validate_certs: false
|
||||
status_code: [200]
|
||||
register: opnsense_nb_final_status
|
||||
retries: 15
|
||||
delay: 4
|
||||
until:
|
||||
- (opnsense_nb_final_status.json.management.connected | default(false) | bool)
|
||||
- (opnsense_nb_final_status.json.management.url | default('')) == opnsense_netbird_management_url
|
||||
|
||||
- name: Итог подключения OPNsense к NetBird
|
||||
ansible.builtin.debug:
|
||||
msg:
|
||||
- "Management URL: {{ opnsense_nb_final_status.json.management.url }}"
|
||||
- "Connected: {{ opnsense_nb_final_status.json.management.connected }}"
|
||||
- "NetBird IP: {{ opnsense_nb_final_status.json.netbirdIp | default('N/A') }}"
|
||||
- "FQDN: {{ opnsense_nb_final_status.json.fqdn | default('N/A') }}"
|
||||
- "Networks: {{ opnsense_nb_final_status.json.networks | default([]) }}"
|
||||
@@ -10,3 +10,14 @@ netbird_letsencrypt_email: "{{ letsencrypt_email }}"
|
||||
netbird_auth_secret: "{{ lookup('env', 'NETBIRD_AUTH_SECRET') }}"
|
||||
netbird_datastore_key: "{{ lookup('env', 'NETBIRD_DATASTORE_KEY') }}"
|
||||
netbird_session_key: "{{ lookup('env', 'NETBIRD_SESSION_KEY') }}"
|
||||
|
||||
netbird_admin_email: "{{ lookup('env', 'NETBIRD_ADMIN_EMAIL') | default(letsencrypt_email, true) }}"
|
||||
netbird_admin_name: "{{ lookup('env', 'NETBIRD_ADMIN_NAME') | default('karpenok', true) }}"
|
||||
netbird_admin_password: "{{ lookup('env', 'NETBIRD_ADMIN_PASSWORD') }}"
|
||||
netbird_api_token: "{{ lookup('env', 'NETBIRD_API_TOKEN') }}"
|
||||
netbird_setup_key: "{{ lookup('env', 'NETBIRD_SETUP_KEY') }}"
|
||||
|
||||
netbird_router_group_name: "homelab-routers"
|
||||
netbird_setup_key_name: "homelab-routers-key"
|
||||
netbird_lan_network_id: "homelab-lan"
|
||||
netbird_lan_subnet: "192.168.1.0/24"
|
||||
@@ -95,6 +95,8 @@ services:
|
||||
container_name: netbird-server
|
||||
restart: unless-stopped
|
||||
networks: [netbird]
|
||||
environment:
|
||||
- NB_SETUP_PAT_ENABLED=true
|
||||
ports:
|
||||
- "3478:3478/udp"
|
||||
volumes:
|
||||
|
||||
@@ -5,9 +5,12 @@
|
||||
changed_when: "'added' in (ufw_rule.stdout | lower)"
|
||||
loop: "{{ netbird_ports }}"
|
||||
|
||||
- name: Поставить openssl
|
||||
- name: Поставить openssl, curl и jq
|
||||
ansible.builtin.apt:
|
||||
name: openssl
|
||||
name:
|
||||
- openssl
|
||||
- curl
|
||||
- jq
|
||||
state: present
|
||||
|
||||
- name: Создать каталог панели
|
||||
@@ -26,7 +29,10 @@
|
||||
- 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
|
||||
fail_msg: "Не задан домен NetBird (host_vars) или один из секретов NETBIRD_AUTH_SECRET, NETBIRD_DATASTORE_KEY, NETBIRD_SESSION_KEY, NETBIRD_LETSENCRYPT_EMAIL."
|
||||
- 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:
|
||||
@@ -83,17 +89,229 @@
|
||||
register: compose_ps
|
||||
changed_when: false
|
||||
|
||||
- name: Дождаться ответа панели
|
||||
- name: Дождаться ответа панели и API
|
||||
ansible.builtin.command: >
|
||||
curl -sk --resolve {{ netbird_domain }}:443:127.0.0.1
|
||||
-o /dev/null -w '%{http_code}'
|
||||
https://{{ netbird_domain }}/
|
||||
register: panel_http
|
||||
curl -fsSk --resolve {{ netbird_domain }}:443:127.0.0.1
|
||||
https://{{ netbird_domain }}/api/instance
|
||||
register: instance_status
|
||||
changed_when: false
|
||||
retries: 30
|
||||
delay: 10
|
||||
until: panel_http.stdout in ['200', '302']
|
||||
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_token=""
|
||||
|
||||
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
|
||||
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_token}" ]; then
|
||||
echo "Сервер уже инициализирован (setup_required=false), но действительный NETBIRD_API_TOKEN в Infisical отсутствует." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
users_json=$(curl "${CURL_OPTS[@]}" -H "Authorization: Token ${bootstrap_token}" "${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 "Authorization: Token ${bootstrap_token}" \
|
||||
-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 "Authorization: Token ${bootstrap_token}" "${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 "Authorization: Token ${bootstrap_token}" "${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 "Authorization: Token ${bootstrap_token}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "${pat_payload}")
|
||||
active_token=$(printf '%s' "${pat_resp}" | jq -r '.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: "{{ compose_ps.stdout_lines + ['Первый вход: https://' + netbird_domain + '/setup'] }}"
|
||||
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 }}"
|
||||
Reference in new issue
Block a user