chore: build
This commit is contained in:
Executable
+148
@@ -0,0 +1,148 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
# ── Charger les IDs créés par setup-portabase.sh ─────────────
|
||||
source /home/ubuntu/docker/s3-backup/portabase-ids.env
|
||||
|
||||
BASE="http://10.0.0.4"
|
||||
H="x-api-key: $API_KEY"
|
||||
BDD_HOST="10.0.0.5"
|
||||
SSH_KEY="/root/.ssh/key_bdd_redis" # clé SSH vers bdd-redis-prod
|
||||
|
||||
echo "[1/4] Attente de connexion de l'agent..."
|
||||
echo " Déploiement de l'agent sur bdd-redis-prod ($BDD_HOST)..."
|
||||
|
||||
ssh -o StrictHostKeyChecking=no -i "$SSH_KEY" root@"$BDD_HOST" << AGENT_EOF
|
||||
# Installer Docker si absent
|
||||
if ! command -v docker &>/dev/null; then
|
||||
echo " Installation de Docker..."
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq ca-certificates curl gnupg lsb-release
|
||||
install -m 0755 -d /etc/apt/keyrings
|
||||
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
|
||||
echo "deb [arch=\$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \$(lsb_release -cs) stable" > /etc/apt/sources.list.d/docker.list
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq docker-ce docker-ce-cli containerd.io docker-compose-plugin
|
||||
systemctl enable --now docker
|
||||
fi
|
||||
|
||||
mkdir -p /opt/portabase-agent
|
||||
cd /opt/portabase-agent
|
||||
|
||||
cat > docker-compose.yml << 'COMPOSE'
|
||||
services:
|
||||
portabase-agent:
|
||||
image: portabase/agent:latest
|
||||
container_name: portabase-agent
|
||||
restart: always
|
||||
network_mode: host
|
||||
env_file: .env
|
||||
environment:
|
||||
- TZ=Europe/Paris
|
||||
- DATABASES_CONFIG_FILE=config.toml
|
||||
volumes:
|
||||
- ./databases.toml:/config/config.toml:ro
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
- agent-data:/data
|
||||
- agent-tmp:/tmp
|
||||
|
||||
volumes:
|
||||
agent-data:
|
||||
agent-tmp:
|
||||
COMPOSE
|
||||
|
||||
cat > .env << ENVEOF
|
||||
EDGE_KEY=$EDGE_KEY
|
||||
ENVEOF
|
||||
chmod 600 .env
|
||||
|
||||
cat > databases.toml << 'TOML'
|
||||
[[databases]]
|
||||
name = "Production PostgreSQL - gestion_commande_db"
|
||||
database = "gestion_commande_db"
|
||||
type = "postgresql"
|
||||
username = "admin_gestion_commande_db"
|
||||
password = "1SWDxH20rV7K2Uc2PNlwCaCxfVZEtKomF0CK9OMh"
|
||||
port = 5432
|
||||
host = "127.0.0.1"
|
||||
generated_id = "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
|
||||
[[databases]]
|
||||
name = "Production Redis"
|
||||
type = "redis"
|
||||
password = "k6UYX9RtuXJVV1HUeefbSukMcSwjvVgRsh2qJGPh"
|
||||
port = 6379
|
||||
host = "127.0.0.1"
|
||||
generated_id = "b2c3d4e5-f6a7-8901-bcde-f12345678901"
|
||||
TOML
|
||||
|
||||
docker compose pull -q
|
||||
docker compose up -d
|
||||
echo " Agent démarré"
|
||||
AGENT_EOF
|
||||
|
||||
echo "[2/4] Attente que l'agent se connecte au dashboard..."
|
||||
for i in $(seq 1 30); do
|
||||
LAST=$(curl -sf "$BASE/api/v1/agents/$AGENT_ID" -H "$H" | python3 -c "import sys,json; print(json.load(sys.stdin).get('lastContact',''))" 2>/dev/null || true)
|
||||
if [ -n "$LAST" ] && [ "$LAST" != "None" ] && [ "$LAST" != "null" ]; then
|
||||
echo " Agent connecté (lastContact=$LAST)"
|
||||
break
|
||||
fi
|
||||
sleep 5
|
||||
done
|
||||
|
||||
echo "[3/4] Récupération des bases détectées..."
|
||||
sleep 10
|
||||
DBS=$(curl -sf "$BASE/api/v1/databases" -H "$H")
|
||||
echo "$DBS" | python3 -c "
|
||||
import sys, json
|
||||
dbs = json.load(sys.stdin)
|
||||
if isinstance(dbs, list):
|
||||
for db in dbs:
|
||||
print(f\" - {db.get('name','?')} (id={db['id']}, type={db.get('type','?')})\")
|
||||
elif isinstance(dbs, dict) and 'data' in dbs:
|
||||
for db in dbs['data']:
|
||||
print(f\" - {db.get('name','?')} (id={db['id']}, type={db.get('type','?')})\")
|
||||
else:
|
||||
print(' Format inattendu:', json.dumps(dbs)[:200])
|
||||
"
|
||||
|
||||
# Récupérer les IDs des bases PostgreSQL
|
||||
PG_DB_ID=$(echo "$DBS" | python3 -c "
|
||||
import sys, json
|
||||
dbs = json.load(sys.stdin)
|
||||
if isinstance(dbs, dict) and 'data' in dbs: dbs = dbs['data']
|
||||
for db in dbs:
|
||||
if db.get('type') == 'postgresql':
|
||||
print(db['id'])
|
||||
break
|
||||
" 2>/dev/null || true)
|
||||
|
||||
echo "[4/4] Configuration du schedule de backup..."
|
||||
|
||||
if [ -n "$PG_DB_ID" ]; then
|
||||
# Attacher la DB au projet
|
||||
curl -sf -X PATCH "$BASE/api/v1/databases/$PG_DB_ID" \
|
||||
-H "$H" -H "Content-Type: application/json" \
|
||||
-d "{\"projectId\":\"$PROJECT_ID\"}" > /dev/null
|
||||
echo " PostgreSQL attaché au projet"
|
||||
|
||||
# Configurer le backup quotidien (tous les jours à 02:00 et 02:15 pour 15min d'intervalle)
|
||||
# cron: toutes les 15 min = */15 * * * * mais le user veut "tous les jours avec 15 min d'intervalle"
|
||||
# = une backup par jour, pas toutes les 15 min. Donc cron = 0 2 * * * (02h00 chaque jour)
|
||||
curl -sf -X PUT "$BASE/api/v1/databases/$PG_DB_ID/backup-policy" \
|
||||
-H "$H" -H "Content-Type: application/json" \
|
||||
-d '{"cron":"0 2 * * *","retentionCount":30}' > /dev/null
|
||||
echo " Schedule: backup quotidien à 02h00, rétention 30 jours"
|
||||
else
|
||||
echo " ERREUR: base PostgreSQL non trouvée. Vérifier dans l'UI."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "============================================"
|
||||
echo " Configuration terminée !"
|
||||
echo " Dashboard : $BASE"
|
||||
echo " Agent : connecté depuis bdd-redis-prod"
|
||||
echo " Backup : quotidien à 02h00 UTC"
|
||||
echo " Rétention : 30 derniers backups"
|
||||
echo "============================================"
|
||||
Executable
+189
@@ -0,0 +1,189 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
BASE="http://10.0.0.4"
|
||||
AGENT_ID="1f687170-8730-439d-82e6-dc23be878046"
|
||||
PROJECT_ID="30dbbcc0-6f98-41b8-9a1d-12f0a1cc95e3"
|
||||
ORG_ID="470f4039-8448-43c4-8aa5-0259e36a5f46"
|
||||
|
||||
# Load API key from env
|
||||
source /home/ubuntu/docker/s3-backup/.env.api
|
||||
H="x-api-key: $API_KEY"
|
||||
ORIGIN="Origin: $BASE"
|
||||
|
||||
echo "=== [1/5] Attach agent to organization ==="
|
||||
curl -s -w "\nHTTP %{http_code}\n" -X POST "$BASE/api/v1/organizations/$ORG_ID/agents" \
|
||||
-H "$H" -H "$ORIGIN" -H "Content-Type: application/json" \
|
||||
-d "{\"agentId\":\"$AGENT_ID\"}"
|
||||
|
||||
echo ""
|
||||
echo "=== [2/5] Get Edge Key ==="
|
||||
EDGE_RESP=$(curl -sf "$BASE/api/v1/agents/$AGENT_ID/key" -H "$H" -H "$ORIGIN")
|
||||
echo "Raw response: $EDGE_RESP"
|
||||
|
||||
EDGE_KEY=$(echo "$EDGE_RESP" | python3 -c "
|
||||
import sys, json
|
||||
d = json.load(sys.stdin)
|
||||
if 'data' in d:
|
||||
print(d['data'].get('edgeKey',''))
|
||||
elif 'edgeKey' in d:
|
||||
print(d['edgeKey'])
|
||||
else:
|
||||
print('')
|
||||
" 2>/dev/null || true)
|
||||
|
||||
if [ -z "$EDGE_KEY" ]; then
|
||||
echo "ERROR: Could not get EDGE_KEY"
|
||||
echo "Response was: $EDGE_RESP"
|
||||
exit 1
|
||||
fi
|
||||
echo "EDGE_KEY=$EDGE_KEY"
|
||||
|
||||
echo ""
|
||||
echo "=== [3/5] Save IDs ==="
|
||||
cat > /home/ubuntu/docker/s3-backup/portabase-ids.env << EOF
|
||||
API_KEY=$API_KEY
|
||||
ORG_ID=$ORG_ID
|
||||
AGENT_ID=$AGENT_ID
|
||||
PROJECT_ID=$PROJECT_ID
|
||||
EDGE_KEY=$EDGE_KEY
|
||||
EOF
|
||||
chmod 600 /home/ubuntu/docker/s3-backup/portabase-ids.env
|
||||
echo " Saved to portabase-ids.env"
|
||||
|
||||
echo ""
|
||||
echo "=== [4/5] Deploy agent on bdd-redis-prod ==="
|
||||
BDD_HOST="10.0.0.5"
|
||||
SSH_KEY="/root/.ssh/key_bdd_redis"
|
||||
|
||||
ssh -o StrictHostKeyChecking=no -i "$SSH_KEY" root@"$BDD_HOST" bash -s -- "$EDGE_KEY" << 'AGENT_EOF'
|
||||
EDGE_KEY="$1"
|
||||
|
||||
if ! command -v docker &>/dev/null; then
|
||||
echo " Installing Docker..."
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq ca-certificates curl gnupg lsb-release
|
||||
install -m 0755 -d /etc/apt/keyrings
|
||||
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
|
||||
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" > /etc/apt/sources.list.d/docker.list
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq docker-ce docker-ce-cli containerd.io docker-compose-plugin
|
||||
systemctl enable --now docker
|
||||
fi
|
||||
|
||||
mkdir -p /opt/portabase-agent
|
||||
cd /opt/portabase-agent
|
||||
|
||||
cat > docker-compose.yml << 'COMPOSE'
|
||||
services:
|
||||
portabase-agent:
|
||||
image: portabase/agent:latest
|
||||
container_name: portabase-agent
|
||||
restart: always
|
||||
network_mode: host
|
||||
env_file: .env
|
||||
environment:
|
||||
- TZ=Europe/Paris
|
||||
- DATABASES_CONFIG_FILE=config.toml
|
||||
volumes:
|
||||
- ./databases.toml:/config/config.toml:ro
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
- agent-data:/data
|
||||
- agent-tmp:/tmp
|
||||
|
||||
volumes:
|
||||
agent-data:
|
||||
agent-tmp:
|
||||
COMPOSE
|
||||
|
||||
cat > .env << ENVEOF
|
||||
EDGE_KEY=$EDGE_KEY
|
||||
ENVEOF
|
||||
chmod 600 .env
|
||||
|
||||
cat > databases.toml << 'TOML'
|
||||
[[databases]]
|
||||
name = "Production PostgreSQL - gestion_commande_db"
|
||||
database = "gestion_commande_db"
|
||||
type = "postgresql"
|
||||
username = "admin_gestion_commande_db"
|
||||
password = "1SWDxH20rV7K2Uc2PNlwCaCxfVZEtKomF0CK9OMh"
|
||||
port = 5432
|
||||
host = "127.0.0.1"
|
||||
generated_id = "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
||||
|
||||
[[databases]]
|
||||
name = "Production Redis"
|
||||
type = "redis"
|
||||
password = "k6UYX9RtuXJVV1HUeefbSukMcSwjvVgRsh2qJGPh"
|
||||
port = 6379
|
||||
host = "127.0.0.1"
|
||||
generated_id = "b2c3d4e5-f6a7-8901-bcde-f12345678901"
|
||||
TOML
|
||||
|
||||
docker compose pull -q 2>/dev/null || true
|
||||
docker compose up -d
|
||||
echo " Agent started"
|
||||
AGENT_EOF
|
||||
|
||||
echo ""
|
||||
echo "=== [5/5] Wait for agent connection & configure backup ==="
|
||||
echo " Waiting for agent to connect..."
|
||||
for i in $(seq 1 30); do
|
||||
AGENT_RESP=$(curl -sf "$BASE/api/v1/agents/$AGENT_ID" -H "$H" -H "$ORIGIN" 2>/dev/null || true)
|
||||
LAST=$(echo "$AGENT_RESP" | python3 -c "
|
||||
import sys, json
|
||||
d = json.load(sys.stdin)
|
||||
if 'data' in d: d = d['data']
|
||||
print(d.get('lastContact',''))
|
||||
" 2>/dev/null || true)
|
||||
if [ -n "$LAST" ] && [ "$LAST" != "None" ] && [ "$LAST" != "null" ]; then
|
||||
echo " Agent connected (lastContact=$LAST)"
|
||||
break
|
||||
fi
|
||||
echo " Waiting... ($i/30)"
|
||||
sleep 5
|
||||
done
|
||||
|
||||
echo " Waiting for database detection..."
|
||||
sleep 15
|
||||
|
||||
DBS=$(curl -sf "$BASE/api/v1/databases" -H "$H" -H "$ORIGIN" 2>/dev/null || echo '{}')
|
||||
echo " Databases response: $DBS"
|
||||
|
||||
PG_DB_ID=$(echo "$DBS" | python3 -c "
|
||||
import sys, json
|
||||
d = json.load(sys.stdin)
|
||||
dbs = d.get('data', d) if isinstance(d, dict) else d
|
||||
if isinstance(dbs, list):
|
||||
for db in dbs:
|
||||
if db.get('type') == 'postgresql':
|
||||
print(db['id'])
|
||||
break
|
||||
" 2>/dev/null || true)
|
||||
|
||||
if [ -n "$PG_DB_ID" ]; then
|
||||
echo " PostgreSQL detected: $PG_DB_ID"
|
||||
|
||||
curl -sf -X PATCH "$BASE/api/v1/databases/$PG_DB_ID" \
|
||||
-H "$H" -H "$ORIGIN" -H "Content-Type: application/json" \
|
||||
-d "{\"projectId\":\"$PROJECT_ID\"}" > /dev/null 2>&1 || true
|
||||
echo " PostgreSQL attached to project"
|
||||
|
||||
curl -sf -X PUT "$BASE/api/v1/databases/$PG_DB_ID/backup-policy" \
|
||||
-H "$H" -H "$ORIGIN" -H "Content-Type: application/json" \
|
||||
-d '{"cron":"0 2 * * *","retentionCount":30}' > /dev/null 2>&1 || true
|
||||
echo " Schedule: daily backup at 02:00, retention 30"
|
||||
else
|
||||
echo " WARNING: PostgreSQL database not found via API"
|
||||
echo " You may need to configure backup schedule manually in the UI"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "============================================"
|
||||
echo " Portabase setup complete!"
|
||||
echo " Dashboard : $BASE"
|
||||
echo " Agent : bdd-redis-prod (10.0.0.5)"
|
||||
echo " Backup : daily at 02:00 UTC"
|
||||
echo " Retention : 30 backups"
|
||||
echo "============================================"
|
||||
@@ -0,0 +1,175 @@
|
||||
---
|
||||
# ============================================================
|
||||
# Portabase – Dashboard (backup-mln) + Agent (bdd-redis-prod)
|
||||
# ============================================================
|
||||
#
|
||||
# Étape 1 – Déployer le dashboard :
|
||||
# ansible-playbook -i inventory/host.ini infra/playbook-portabase.yml --tags dashboard
|
||||
#
|
||||
# Étape 2 – Ouvrir http://10.0.0.4:8887, créer un compte admin,
|
||||
# puis Organisation > Settings > Agents > créer un agent,
|
||||
# copier l'Edge Key
|
||||
#
|
||||
# Étape 3 – Déployer l'agent :
|
||||
# ansible-playbook -i inventory/host.ini infra/playbook-portabase.yml --tags agent \
|
||||
# -e portabase_edge_key="<EDGE_KEY>"
|
||||
#
|
||||
# Étape 4 – Dans l'UI, ajouter les bases via l'agent (ou laisser
|
||||
# le fichier databases.toml déployé automatiquement)
|
||||
# ============================================================
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# PLAY 1 : Dashboard sur backup-mln
|
||||
# ════════════════════════════════════════════════════════════
|
||||
- name: Déployer Portabase Dashboard
|
||||
hosts: backup-mln
|
||||
become: true
|
||||
gather_facts: true
|
||||
|
||||
vars:
|
||||
portabase_dir: /home/ubuntu/docker/s3-backup
|
||||
portabase_port: 8887
|
||||
docker_dir: ../monitoring/s3-backup
|
||||
docker_compose: ../monitoring/s3-backup/docker-compose.yml
|
||||
|
||||
tasks:
|
||||
- name: Déployer docker-compose.yml du dashboard
|
||||
ansible.builtin.copy:
|
||||
src: "{{ docker_dir }}"
|
||||
dest: "{{ portabase_dir }}"
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0640"
|
||||
notify: Redémarrer Portabase
|
||||
tags: [dashboard]
|
||||
|
||||
- name: Démarrer Portabase Dashboard
|
||||
ansible.builtin.command: docker compose up -d
|
||||
args:
|
||||
chdir: "{{ portabase_dir }}"
|
||||
tags: [dashboard]
|
||||
|
||||
- name: Attendre que le dashboard soit prêt
|
||||
ansible.builtin.uri:
|
||||
url: "http://127.0.0.1:{{ portabase_port }}/api/health"
|
||||
status_code: 200
|
||||
register: health
|
||||
retries: 15
|
||||
delay: 5
|
||||
until: health.status == 200
|
||||
tags: [dashboard]
|
||||
|
||||
- name: Afficher l'URL du dashboard
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
Dashboard Portabase accessible sur http://{{ vpn_ip }}:{{ portabase_port }}
|
||||
— Créer un agent dans l'UI et copier l'Edge Key pour l'étape suivante.
|
||||
tags: [dashboard]
|
||||
|
||||
handlers:
|
||||
- name: Redémarrer Portabase
|
||||
ansible.builtin.command: docker compose up -d --force-recreate
|
||||
args:
|
||||
chdir: "{{ docker_dir }}"
|
||||
tags: [dashboard]
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# PLAY 2 : Agent sur bdd-redis-prod
|
||||
# ════════════════════════════════════════════════════════════
|
||||
- name: Déployer Portabase Agent
|
||||
hosts: bdd-redis-prod
|
||||
become: true
|
||||
gather_facts: true
|
||||
|
||||
vars:
|
||||
agent_dir: /opt/portabase-agent
|
||||
docker_dir: ../monitoring/bdd-redis-prod-agent
|
||||
docker_compose: ../monitoring/bdd-redis-prod-agent/docker-compose.yml
|
||||
|
||||
|
||||
tasks:
|
||||
- name: Vérifier que portabase_edge_key est fourni
|
||||
ansible.builtin.fail:
|
||||
msg: >-
|
||||
Variable 'portabase_edge_key' requise.
|
||||
Relancez avec : -e portabase_edge_key="<EDGE_KEY>"
|
||||
when: portabase_edge_key is not defined or portabase_edge_key == ""
|
||||
tags: [agent]
|
||||
|
||||
# ── Docker (si absent) ──────────────────────────────────
|
||||
- name: Vérifier si Docker est installé
|
||||
ansible.builtin.command: docker --version
|
||||
register: docker_check
|
||||
changed_when: false
|
||||
failed_when: false
|
||||
tags: [agent]
|
||||
|
||||
- name: Créer le répertoire de l'agent
|
||||
ansible.builtin.file:
|
||||
path: "{{ agent_dir }}"
|
||||
state: directory
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0750"
|
||||
tags: [agent]
|
||||
|
||||
- name: Déployer docker-compose.yml de l'agent
|
||||
ansible.builtin.copy:
|
||||
src: "{{ docker_compose }}"
|
||||
dest: "{{ agent_dir }}/docker-compose.yml"
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0640"
|
||||
notify: Redémarrer l'agent
|
||||
tags: [agent]
|
||||
|
||||
- name: Déployer la configuration des bases de données
|
||||
ansible.builtin.template:
|
||||
src: ../templates/databases.toml
|
||||
dest: "{{ agent_dir }}/databases.toml"
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0600"
|
||||
notify: Redémarrer l'agent
|
||||
tags: [agent]
|
||||
|
||||
- name: Déployer la CA interne Portabase (certificat auto-signé du dashboard)
|
||||
ansible.builtin.copy:
|
||||
src: "{{ docker_dir }}/portabase-ca.pem"
|
||||
dest: "{{ agent_dir }}/portabase-ca.pem"
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0644"
|
||||
notify: Redémarrer l'agent
|
||||
tags: [agent]
|
||||
|
||||
- name: Déployer l'Edge Key de l'agent
|
||||
ansible.builtin.copy:
|
||||
content: "EDGE_KEY={{ portabase_edge_key }}\n"
|
||||
dest: "{{ agent_dir }}/.env"
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0600"
|
||||
notify: Redémarrer l'agent
|
||||
tags: [agent]
|
||||
|
||||
- name: Démarrer l'agent Portabase
|
||||
ansible.builtin.command: docker compose up -d
|
||||
args:
|
||||
chdir: "{{ agent_dir }}"
|
||||
tags: [agent]
|
||||
|
||||
- name: Afficher le statut
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
Agent Portabase déployé sur {{ inventory_hostname }}.
|
||||
Il se connecte au dashboard via l'Edge Key et poll toutes les 5s.
|
||||
La base {{ db_name }} (PostgreSQL) est configurée.
|
||||
tags: [agent]
|
||||
|
||||
handlers:
|
||||
- name: Redémarrer l'agent
|
||||
ansible.builtin.command: docker compose up -d --force-recreate
|
||||
args:
|
||||
chdir: "{{ agent_dir }}"
|
||||
tags: [agent]
|
||||
@@ -0,0 +1,83 @@
|
||||
---
|
||||
# Renouvellement automatique du certificat Let's Encrypt de s3-uber
|
||||
# (uber-stup.club + gitea/ota/rustfs/s3.uber-stup.club, cert partage par le
|
||||
# conteneur nginx s3_nginx).
|
||||
#
|
||||
# Problemes corriges :
|
||||
# - certbot etait configure avec l'authenticator "nginx" (nginx sur l'hote),
|
||||
# or nginx tourne dans Docker et occupe deja le port 80 : le renouvellement
|
||||
# echouait systematiquement ("bind() to 0.0.0.0:80 failed").
|
||||
# - le conteneur sert une COPIE des certs (/home/ubuntu/docker/nginx/certs),
|
||||
# jamais mise a jour depuis /etc/letsencrypt/live.
|
||||
#
|
||||
# Solution : authenticator "standalone" + hooks certbot
|
||||
# pre : arrete s3_nginx (libere le port 80)
|
||||
# deploy : copie fullchain/privkey dans le dossier monte par nginx
|
||||
# post : redemarre s3_nginx (execute meme si le renouvellement echoue)
|
||||
# Coupure ~15 s des services derriere s3_nginx a chaque renouvellement (tous les
|
||||
# ~60 jours, en pleine nuit via certbot.timer).
|
||||
|
||||
- name: Renouvellement automatique du certificat s3-uber
|
||||
hosts: s3-uber
|
||||
become: true
|
||||
gather_facts: false
|
||||
|
||||
vars:
|
||||
nginx_container: s3_nginx
|
||||
nginx_certs_dir: /home/ubuntu/docker/nginx/certs
|
||||
cert_owner: ubuntu
|
||||
cert_group: docker
|
||||
|
||||
tasks:
|
||||
- name: Creer les dossiers de hooks certbot
|
||||
ansible.builtin.file:
|
||||
path: "/etc/letsencrypt/renewal-hooks/{{ item }}"
|
||||
state: directory
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0755"
|
||||
loop: [pre, deploy, post]
|
||||
|
||||
- name: Hook pre - arreter nginx pour liberer le port 80
|
||||
ansible.builtin.copy:
|
||||
dest: /etc/letsencrypt/renewal-hooks/pre/stop-nginx.sh
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0755"
|
||||
content: |
|
||||
#!/bin/bash
|
||||
docker stop {{ nginx_container }}
|
||||
|
||||
- name: Hook deploy - copier le cert renouvele pour nginx
|
||||
ansible.builtin.copy:
|
||||
dest: /etc/letsencrypt/renewal-hooks/deploy/copy-to-nginx.sh
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0755"
|
||||
content: |
|
||||
#!/bin/bash
|
||||
set -e
|
||||
install -o {{ cert_owner }} -g {{ cert_group }} -m 0644 "$RENEWED_LINEAGE/fullchain.pem" {{ nginx_certs_dir }}/fullchain.pem
|
||||
install -o {{ cert_owner }} -g {{ cert_group }} -m 0640 "$RENEWED_LINEAGE/privkey.pem" {{ nginx_certs_dir }}/privkey.pem
|
||||
|
||||
- name: Hook post - redemarrer nginx (meme si le renouvellement echoue)
|
||||
ansible.builtin.copy:
|
||||
dest: /etc/letsencrypt/renewal-hooks/post/start-nginx.sh
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0755"
|
||||
content: |
|
||||
#!/bin/bash
|
||||
docker start {{ nginx_container }}
|
||||
|
||||
- name: Passer l'authenticator certbot en standalone
|
||||
ansible.builtin.lineinfile:
|
||||
path: /etc/letsencrypt/renewal/uber-stup.club.conf
|
||||
regexp: "^authenticator\\s*="
|
||||
line: "authenticator = standalone"
|
||||
|
||||
- name: Retirer l'installer nginx (nginx n'est plus sur l'hote)
|
||||
ansible.builtin.lineinfile:
|
||||
path: /etc/letsencrypt/renewal/uber-stup.club.conf
|
||||
regexp: "^installer\\s*="
|
||||
line: "installer = None"
|
||||
Executable
+99
@@ -0,0 +1,99 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
BASE="http://10.0.0.4"
|
||||
SESSION_COOKIE=""
|
||||
API_KEY=""
|
||||
|
||||
# ── 1. Login et création API key ─────────────────────────────
|
||||
echo "[1/7] Login..."
|
||||
RESP=$(curl -sf -D- -X POST "$BASE/api/auth/sign-in/email" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"email":"admin@portabase.local","password":"Admin@Portabase2026!"}')
|
||||
|
||||
SESSION_COOKIE=$(echo "$RESP" | grep -oP 'better-auth\.session_token=[^;]+')
|
||||
echo " Session OK"
|
||||
|
||||
echo "[2/7] Création API key..."
|
||||
KEY_RESP=$(curl -sf -X POST "$BASE/api/auth/api-key/create" \
|
||||
-b "$SESSION_COOKIE" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"name":"automation","expiresIn":null}')
|
||||
|
||||
API_KEY=$(echo "$KEY_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('key',''))" 2>/dev/null || true)
|
||||
|
||||
if [ -z "$API_KEY" ]; then
|
||||
echo " Endpoint api-key/create indisponible, insertion directe en DB..."
|
||||
API_KEY="pb_$(openssl rand -hex 24)"
|
||||
HASHED=$(echo -n "$API_KEY" | sha256sum | awk '{print $1}')
|
||||
PREFIX=$(echo "$API_KEY" | cut -c1-7)
|
||||
START=$(echo "$API_KEY" | cut -c1-10)
|
||||
USER_ID=$(docker exec portabase-pg psql -U portabase -d portabase -tAc "SELECT id FROM \"user\" WHERE role='superadmin' LIMIT 1;")
|
||||
|
||||
docker exec portabase-pg psql -U portabase -d portabase -c "
|
||||
INSERT INTO apikey (id, name, start, prefix, key, reference_id, enabled, rate_limit_enabled, request_count, remaining, created_at, updated_at)
|
||||
VALUES (gen_random_uuid(), 'automation', '$START', '$PREFIX', '$HASHED', '$USER_ID', true, false, 0, NULL, NOW(), NOW());"
|
||||
echo " API key créée en DB"
|
||||
fi
|
||||
|
||||
echo " API_KEY=$API_KEY"
|
||||
H="x-api-key: $API_KEY"
|
||||
|
||||
# ── 2. Organisation ──────────────────────────────────────────
|
||||
echo "[3/7] Création organisation..."
|
||||
ORG=$(curl -sf -X POST "$BASE/api/v1/organizations" \
|
||||
-H "$H" -H "Content-Type: application/json" \
|
||||
-d '{"name":"Production","description":"Backup infrastructure"}')
|
||||
ORG_ID=$(echo "$ORG" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")
|
||||
echo " org_id=$ORG_ID"
|
||||
|
||||
# ── 3. Agent ─────────────────────────────────────────────────
|
||||
echo "[4/7] Création agent..."
|
||||
AGENT=$(curl -sf -X POST "$BASE/api/v1/agents" \
|
||||
-H "$H" -H "Content-Type: application/json" \
|
||||
-d '{"name":"bdd-redis-prod","description":"PostgreSQL + Redis on 10.0.0.5"}')
|
||||
AGENT_ID=$(echo "$AGENT" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")
|
||||
echo " agent_id=$AGENT_ID"
|
||||
|
||||
# Attacher l'agent à l'organisation
|
||||
curl -sf -X POST "$BASE/api/v1/organizations/$ORG_ID/agents" \
|
||||
-H "$H" -H "Content-Type: application/json" \
|
||||
-d "{\"agentId\":\"$AGENT_ID\"}" > /dev/null
|
||||
echo " Agent attaché à l'organisation"
|
||||
|
||||
# Récupérer l'Edge Key
|
||||
EDGE_KEY=$(curl -sf "$BASE/api/v1/agents/$AGENT_ID/key" -H "$H" | python3 -c "import sys,json; print(json.load(sys.stdin)['edgeKey'])")
|
||||
echo " EDGE_KEY=$EDGE_KEY"
|
||||
|
||||
# ── 4. Projet ────────────────────────────────────────────────
|
||||
echo "[5/7] Création projet..."
|
||||
PROJECT=$(curl -sf -X POST "$BASE/api/v1/organizations/$ORG_ID/projects" \
|
||||
-H "$H" -H "Content-Type: application/json" \
|
||||
-d '{"name":"Backup DB Prod","description":"Sauvegarde quotidienne PostgreSQL + Redis"}')
|
||||
PROJECT_ID=$(echo "$PROJECT" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")
|
||||
echo " project_id=$PROJECT_ID"
|
||||
|
||||
# ── 5. Sauvegarder les infos ─────────────────────────────────
|
||||
echo "[6/7] Sauvegarde des identifiants..."
|
||||
cat > /home/ubuntu/docker/s3-backup/portabase-ids.env << EOF
|
||||
API_KEY=$API_KEY
|
||||
ORG_ID=$ORG_ID
|
||||
AGENT_ID=$AGENT_ID
|
||||
PROJECT_ID=$PROJECT_ID
|
||||
EDGE_KEY=$EDGE_KEY
|
||||
EOF
|
||||
chmod 600 /home/ubuntu/docker/s3-backup/portabase-ids.env
|
||||
|
||||
echo "[7/7] Résumé"
|
||||
echo "============================================"
|
||||
echo " Dashboard : $BASE"
|
||||
echo " API Key : $API_KEY"
|
||||
echo " Org ID : $ORG_ID"
|
||||
echo " Agent ID : $AGENT_ID"
|
||||
echo " Project ID : $PROJECT_ID"
|
||||
echo " Edge Key : $EDGE_KEY"
|
||||
echo ""
|
||||
echo " IDs sauvegardés dans : /home/ubuntu/docker/s3-backup/portabase-ids.env"
|
||||
echo ""
|
||||
echo " Prochaine étape : déployer l'agent sur bdd-redis-prod avec cette EDGE_KEY"
|
||||
echo "============================================"
|
||||
Reference in New Issue
Block a user