backend/.github/workflows/cd.yml

91 lines
3 KiB
YAML

name: Deploy backend to prod (push-based)
on:
workflow_run:
workflows: ["Backend CI"]
types: [completed]
branches: [main]
concurrency:
group: prod-backend-deploy
cancel-in-progress: false
jobs:
deploy:
name: Build image, push and roll out via bastion
if: ${{ github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
steps:
- name: Checkout tested commit
uses: actions/checkout@v4
with:
ref: ${{ github.event.workflow_run.head_sha }}
- name: Build backend image
run: docker build -t danagble-be:latest .
- name: Setup SSH key and bastion config
env:
SSH_PRIVATE_KEY: ${{ secrets.PROD_SSH_KEY }}
run: |
set -euo pipefail
install -m 700 -d ~/.ssh
KEY="$(printf '%s' "$SSH_PRIVATE_KEY" | python3 -c '
import re, sys
s = sys.stdin.read()
s = re.sub(r"\\+n", "\n", s)
s = s.replace("-----BEGIN OPENSSH PRIVATE KEY-----", "")
s = s.replace("-----END OPENSSH PRIVATE KEY-----", "")
body = "".join(s.split())
sys.stdout.write("-----BEGIN OPENSSH PRIVATE KEY-----\n")
sys.stdout.write("\n".join(body[i:i + 64] for i in range(0, len(body), 64)))
sys.stdout.write("\n-----END OPENSSH PRIVATE KEY-----\n")
')"
printf '%s\n' "$KEY" | tr -d '\r' > ~/.ssh/id_ed25519
chmod 600 ~/.ssh/id_ed25519
ssh-keygen -lf ~/.ssh/id_ed25519
cat > ~/.ssh/config <<'EOF'
Host bastion
HostName 103.195.236.32
User root
IdentityFile ~/.ssh/id_ed25519
StrictHostKeyChecking accept-new
Host prod
HostName 100.109.54.207
User neurosus
IdentityFile ~/.ssh/id_ed25519
ProxyJump bastion
StrictHostKeyChecking accept-new
EOF
chmod 600 ~/.ssh/config
- name: Transfer compose and image
run: |
set -euo pipefail
tar -cf - docker-compose.prod.yml | ssh prod 'mkdir -p ~/danangble && tar -xf - -C ~/danangble'
docker save danagble-be:latest | ssh prod 'docker load'
- name: Roll out backend
run: |
set -euo pipefail
ssh prod '
set -euo pipefail
cd ~/danangble
test -f backend.env
docker compose -p danagble-backend -f docker-compose.prod.yml up -d
docker compose -p danagble-backend -f docker-compose.prod.yml ps
'
- name: Health check
run: |
ssh prod '
set -euo pipefail
for i in $(seq 1 30); do
health_status=$(docker inspect -f "{{.State.Health.Status}}" danagble-be 2>/dev/null || true)
[ "$health_status" = healthy ] && exit 0
[ "$health_status" = unhealthy ] && docker logs --tail 80 danagble-be && exit 1
sleep 2
done
docker logs --tail 80 danagble-be
exit 1
'