Files
sonar-test-nest3/.gitea/workflows/deploy-humanitec.yml
Scaffolder 4ad66fd688
All checks were successful
Build and Publish TechDocs / build-and-publish (push) Successful in 1m9s
initial commit
Change-Id: Ieef4347967c992d99068a9713b252fd625499445
2026-05-11 13:00:06 +00:00

247 lines
12 KiB
YAML

name: Deploy to Humanitec
on:
workflow_run:
workflows: ["Build and Push to ACR"]
types:
- completed
branches: [ dev, staging, prod ]
workflow_dispatch:
inputs:
environment:
description: 'Target environment'
required: true
default: 'dev'
type: choice
options:
- dev
- staging
- prod
concurrency:
group: -deploy-humanitec
cancel-in-progress: true
env:
APP_ID: sonar-test-nest3
PROJECT_ID: domain-demo-apps
AZURE_FEDERATED_TOKEN_FILE: /var/run/secrets/azure/tokens/azure-identity-token
DEFAULT_ENV_ID: dev
ENV_PREFIX:
jobs:
deploy:
name: Deploy to Humanitec
runs-on: ubuntu-latest
if: >-
(github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success') ||
(github.event_name == 'workflow_dispatch' && github.ref != 'refs/heads/main')
permissions:
contents: read
id-token: write
steps:
- name: Checkout code
uses: actions/checkout@v4
# No `ref:` override — Gitea's act_runner mangles inline expressions in
# `with:` inputs. For workflow_run events this checks out main (the
# default branch), which is correct: score.yaml and other platform files
# live on main. The image SHA is resolved separately below.
- name: Install CLI tools
run: |
# jq (needed for github API call)
command -v jq &>/dev/null || (apt-get update -qq && apt-get install -y -qq jq)
# hctl (Humanitec Platform Orchestrator v2 CLI)
HCTL_VERSION=$(curl -s https://api.github.com/repos/humanitec/hctl/releases/latest | jq -r '.tag_name')
curl -fLO "https://github.com/humanitec/hctl/releases/download/${HCTL_VERSION}/hctl_${HCTL_VERSION#v}_linux_amd64.tar.gz"
tar -xzf "hctl_${HCTL_VERSION#v}_linux_amd64.tar.gz"
install -m 755 hctl /usr/local/bin/hctl
hctl --version
echo "✓ Tools installed"
- name: Install Azure CLI
run: command -v az &>/dev/null || curl -sL https://aka.ms/InstallAzureCLIDeb | bash
- name: Azure login (OIDC)
run: |
az login \
--service-principal \
--username "$AZURE_CLIENT_ID" \
--tenant "$AZURE_TENANT_ID" \
--federated-token "$(cat $AZURE_FEDERATED_TOKEN_FILE)"
echo "✓ Azure login successful"
- name: Get image reference
id: image
run: |
ACR_LOGIN_SERVER=$(az acr list --query "[0].loginServer" -o tsv)
# Read the dev-branch SHA from the event payload. Using $GITHUB_EVENT_PATH
# avoids act_runner expression mangling in with: inputs. The checkout
# above is on main (platform files); we still need the dev SHA for the
# image tag that was built and pushed by build-push.yml.
SHA=$(python3 -c "import json,os; e=json.load(open(os.environ['GITHUB_EVENT_PATH'])); print(e.get('workflow_run',{}).get('head_sha') or '')" 2>/dev/null || true)
if [ -z "$SHA" ]; then SHA=$(git rev-parse HEAD); fi
echo "IMAGE_FULL=${ACR_LOGIN_SERVER}/sonar-test-nest3:${SHA}" >> $GITHUB_ENV
echo "✓ Image: ${ACR_LOGIN_SERVER}/sonar-test-nest3:${SHA}"
- name: Set environment
id: set-env
run: |
if [ "${{ gitea.event_name }}" = "workflow_dispatch" ]; then
ENV_ID="${{ gitea.event.inputs.environment }}"
else
# Derive from the branch that triggered the upstream build-push run.
# workflow_run.head_branch carries 'dev', 'staging', or 'prod'.
# Prefix with ENV_PREFIX to get system-scoped env IDs when deploying
# into a domain project (e.g. order-mgmt-dev instead of dev).
BRANCH="${{ github.event.workflow_run.head_branch }}"
case "$BRANCH" in
staging) ENV_ID="${ENV_PREFIX}staging" ;;
prod) ENV_ID="${ENV_PREFIX}prod" ;;
*) ENV_ID="$DEFAULT_ENV_ID" ;;
esac
fi
ENV_ID="${ENV_ID:-${ENV_PREFIX}dev}"
echo "ENV_ID=$ENV_ID" >> $GITHUB_OUTPUT
echo "ENV_ID=$ENV_ID" >> $GITHUB_ENV
echo "✓ Target environment: $ENV_ID"
- name: Get Humanitec credentials from Key Vault
run: |
HUMANITEC_TOKEN=$(az keyvault secret show \
--vault-name "bstage-cjot-dev-core-kv" \
--name "humanitec-api-token-v2" \
--query "value" -o tsv)
[ -z "$HUMANITEC_TOKEN" ] && echo "❌ Failed to retrieve HUMANITEC_TOKEN" && exit 1
echo "HUMANITEC_AUTH_TOKEN=$HUMANITEC_TOKEN" >> $GITHUB_ENV
HUMANITEC_ORG=$(az keyvault secret show \
--vault-name "bstage-cjot-dev-core-kv" \
--name "humanitec-org-id" \
--query "value" -o tsv)
[ -z "$HUMANITEC_ORG" ] && echo "❌ Failed to retrieve HUMANITEC_ORG" && exit 1
echo "HUMANITEC_ORG=$HUMANITEC_ORG" >> $GITHUB_ENV
echo "✓ Credentials retrieved"
- name: Deploy via Humanitec Score
run: |
# Pre-flight: wait for any prior deployment to finish before calling hctl.
# hctl refuses to start a new deployment while one is still executing.
echo "Pre-flight: checking for in-progress deployments..."
PREFLIGHT_WAITED=0
while [ $PREFLIGHT_WAITED -lt 300 ]; do
PREFLIGHT_STATUS=$(curl -sf \
-H "Authorization: Bearer $HUMANITEC_AUTH_TOKEN" \
"https://api.humanitec.dev/orgs/$HUMANITEC_ORG/last-deployments?env_id=$ENV_ID&project_id=$PROJECT_ID&state_change_only=true" \
| jq -r '.items[0].status // "none"' 2>/dev/null || echo "none")
if [ "$PREFLIGHT_STATUS" != "in progress" ] && [ "$PREFLIGHT_STATUS" != "pending" ] && [ "$PREFLIGHT_STATUS" != "executing" ]; then
echo "Pre-flight passed (status=$PREFLIGHT_STATUS). Proceeding."
break
fi
echo " Prior deployment still running ($PREFLIGHT_WAITED s elapsed, status=$PREFLIGHT_STATUS)..."
sleep 15
PREFLIGHT_WAITED=$((PREFLIGHT_WAITED + 15))
done
# First deploy — provisions all resources. On a brand-new Humanitec project the
# dns-k8s-ingress Terraform module runs before the K8s Service exists, so the
# ingress backend port falls back to 3000. A second deploy (below) corrects it
# once the Service is up, which is essential for apps not running on port 3000.
HCTL_EXIT=0
timeout 300 hctl score deploy "$PROJECT_ID" "$ENV_ID" score.yaml \
--no-prompt \
--default-image "$IMAGE_FULL" || HCTL_EXIT=$?
if [ "$HCTL_EXIT" -eq 0 ]; then
echo "✓ First deployment complete to $ENV_ID"
elif [ "$HCTL_EXIT" -eq 124 ]; then
echo "✓ First deployment submitted (polling timed out — waiting for K8s to settle)"
else
echo "✗ hctl failed with exit code $HCTL_EXIT"
exit $HCTL_EXIT
fi
# Poll Humanitec API until the first deployment is no longer in-progress before
# re-deploying. A flat sleep is unreliable — Terraform DNS modules can take 4-6 min.
echo "Waiting for first deployment to finish (polling Humanitec API)..."
MAX_WAIT=360
WAITED=0
while [ $WAITED -lt $MAX_WAIT ]; do
DEPLOY_STATUS=$(curl -sf \
-H "Authorization: Bearer $HUMANITEC_AUTH_TOKEN" \
"https://api.humanitec.dev/orgs/$HUMANITEC_ORG/last-deployments?env_id=$ENV_ID&project_id=$PROJECT_ID&state_change_only=true" \
| jq -r '.items[0].status // "unknown"' 2>/dev/null || echo "unknown")
if [ "$DEPLOY_STATUS" != "in progress" ] && [ "$DEPLOY_STATUS" != "pending" ] && [ "$DEPLOY_STATUS" != "executing" ]; then
echo "First deployment finished with status: $DEPLOY_STATUS"
break
fi
echo " Still running ($WAITED s elapsed, status=$DEPLOY_STATUS)..."
sleep 15
WAITED=$((WAITED + 15))
done
if [ $WAITED -ge $MAX_WAIT ]; then
echo "Warning: first deployment still running after $MAX_WAIT s — proceeding anyway"
fi
# Second deploy — dns module now reads the real K8s Service port, fixing the
# ingress backend. This is a no-op for apps already routed correctly (e.g. port 3000).
HCTL_EXIT2=0
timeout 120 hctl score deploy "$PROJECT_ID" "$ENV_ID" score.yaml \
--no-prompt \
--default-image "$IMAGE_FULL" || HCTL_EXIT2=$?
if [ "$HCTL_EXIT2" -eq 0 ]; then
echo "✓ Deployment finalised to $ENV_ID"
elif [ "$HCTL_EXIT2" -eq 124 ]; then
echo "✓ Second deployment submitted (polling timed out)"
else
echo "✗ Second hctl deploy failed with exit code $HCTL_EXIT2"
exit $HCTL_EXIT2
fi
- name: Deployment Summary
run: |
DEPLOY_URL="https://console.humanitec.dev/orgs/${HUMANITEC_ORG}/projects/$APP_ID"
echo "### 🚀 Deployment Complete" >> $GITHUB_STEP_SUMMARY
echo "| | |" >> $GITHUB_STEP_SUMMARY
echo "|---|---|" >> $GITHUB_STEP_SUMMARY
echo "| **Service** | $APP_ID |" >> $GITHUB_STEP_SUMMARY
echo "| **Environment** | $ENV_ID |" >> $GITHUB_STEP_SUMMARY
echo "| **Image** | $IMAGE_FULL |" >> $GITHUB_STEP_SUMMARY
echo "| **Humanitec** | [$DEPLOY_URL]($DEPLOY_URL) |" >> $GITHUB_STEP_SUMMARY
- name: OTel traffic warmup (dev only)
if: env.ENV_ID == 'dev'
run: |
SERVICE=$(grep '^service:' .platform/config.yaml | sed 's/^service: //' | tr -d ' \r')
HEALTH_PATH=$(grep '^health_path:' .platform/config.yaml | sed 's/^health_path: //' | tr -d ' \r')
HEALTH_PATH="${HEALTH_PATH:-/health}"
APP_URL="https://${SERVICE}.kyndemo.live"
echo "Waiting for ${APP_URL}${HEALTH_PATH} to be live (up to 120s)..."
HTTP_CODE="000"
DEADLINE=$(($(date +%s) + 120))
while [ $(date +%s) -lt $DEADLINE ]; do
HTTP_CODE=$(curl -sk -o /dev/null -w "%{http_code}" --max-time 5 "${APP_URL}${HEALTH_PATH}" || echo "000")
[ "$HTTP_CODE" = "200" ] && echo "✓ App live at ${APP_URL}" && break
echo " waiting... (HTTP $HTTP_CODE)"; sleep 5
done
if [ "$HTTP_CODE" != "200" ]; then
echo "App did not come live within 120s — skipping OTel warmup"
exit 0
fi
# Send a burst of requests across common paths to generate OTel spans/metrics.
# All runtimes expose /health; the remaining paths are best-effort (404s still
# produce spans and are counted by the OTel HTTP instrumentation).
echo "Sending traffic burst (50 requests) to generate OTel telemetry..."
PATHS=("${HEALTH_PATH}" "/" "/api" "/api/status" "/api/health" "${HEALTH_PATH}" "/" "/api")
SUCCESS=0; TOTAL=0
for i in $(seq 1 7); do
for RPATH in "${PATHS[@]}"; do
CODE=$(curl -sk -o /dev/null -w "%{http_code}" --max-time 5 "${APP_URL}${RPATH}" || echo "000")
TOTAL=$((TOTAL + 1))
case "$CODE" in 2*|3*) SUCCESS=$((SUCCESS + 1)) ;; esac
done
sleep 1
done
echo "✓ Warmup complete: ${SUCCESS}/${TOTAL} 2xx/3xx — OTel spans visible in Grafana within ~30s"
echo "| **OTel warmup** | ${SUCCESS}/${TOTAL} requests → ${APP_URL} |" >> $GITHUB_STEP_SUMMARY