Software Engineer Encyclopedia
0%
Domain 08 · DevOps, Cloud & Production Engineering · Topic 8.2

CI/CD للمطور .NET: من Commit إلى Release قابل للرجوع

CI/CD — Practical Delivery Pipelines with GitHub Actions

CI وContinuous Delivery/Deployment وbuild/test/publish pipelines وGitHub Actions وconfiguration/secrets/OIDC وdeployment strategies وrollback وdatabase migrations وDORA metrics.

  • Advanced
  • ~21 min read
  • 12 sections
  • 8 code examples
  • 1 diagrams
  • 5 questions
  • Priority L2 · Important
  • GitHub Actions · .NET 10 · Docker BuildKit

المتطلبات قبل ما تبدأ

تطبيق backend جاهز للنشر (المجالات 03–05).

01

CI و CD: ليه نأتمتة التسليم؟

Make every change reproducible and verifiable
Deep dive

Continuous Integration (CI) معناها دمج تغييرات صغيرة باستمرار مع build/tests/quality checks آلية. Continuous Delivery معناها أن كل تغيير يمر pipeline ويصبح release candidate جاهزًا للنشر، لكن production approval قد يكون يدويًا. Continuous Deployment معناها أن التغييرات التي تجتاز gates تنشر production تلقائيًا. المصطلحات تتداخل في بعض المؤسسات؛ المهم تعرف مستوى الأتمتة والـ approval boundaries.

Pipeline الجيدة لا تكتفي بـ dotnet build. هي تحقق reproducible restore، compile، unit/integration tests، static analysis، dependency/security scanning، container build، artifact publishing، deployment، smoke tests و rollback/roll-forward strategy. كل gate يجب أن يمنع نوع failure معروف، وليس مجرد زيادة عدد الخطوات.

Build once, promote same artifact: لا تبني image مختلفة لـ Dev و Staging و Production. ابنِ artifact واحدًا، سجّل immutable digest/version، ثم غيّر runtime configuration/environment. هذا يجعل ما تم اختباره هو نفسه ما نُشر.

02

Pipeline من commit لـ production

Delivery pipeline
Basics
PRBuild + testlint, scan, evalsArtifactimage@sha256StagingCanary5% + SLOProdOIDC to the cloud (no long-lived secrets) · migrations expand→contract · auto-rollback on SLO burn
Build once, promote the same artifact; gates decide, not people's memory
03

Pipeline Stages: Restore → Build → Test → Package

Fast feedback and trustworthy artifacts
Deep dive

رتب checks من الأرخص إلى الأغلى غالبًا: formatting/analyzers، restore/build، unit tests، component/integration tests، security scans، image build/scan، deployment smoke tests. لا تجعل expensive end-to-end tests تمنع feedback سريع على syntax error. لكن لا تخفِ failure في خطوة اختيارية إذا كانت شرطًا للإصدار.

YAMLGitHub Actions CI for a .NET solution
name: ci
on:
  pull_request:
  push:
    branches: [ main ]

permissions:
  contents: read

jobs:
  build-test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '10.0.x'
      - name: Restore
        run: dotnet restore MyShop.sln
      - name: Build
        run: dotnet build MyShop.sln -c Release --no-restore
      - name: Test
        run: dotnet test MyShop.sln -c Release --no-build --logger "trx;LogFileName=test-results.trx"

الـ action major tag مثل @v4 أسهل لكن أقل ثباتًا من pinning إلى full commit SHA؛ في supply-chain sensitive workflows، pin SHA مع Dependabot/Renovate updates. أضف artifact upload للتقارير، و cache NuGet بحذر: cache performance optimization وليس source of truth. لا تجعل cache يخفي restore errors.

GitHub Actions لـ ‎.NET: Pipeline قابلة للتكرار

CI pipeline يجب أن تبدأ من clean checkout، وتستخدم SDK محددًا عبر global.json، وتستعيد dependencies، وتبني Release، وتشغل unit/integration tests، ثم تنتج artifact واحدًا معروفًا. لا تجعل deployment يعيد build بكود مختلف؛ الأفضل promote نفس artifact الذي اجتاز الاختبارات. ثبّت actions على commit SHA في بيئات production الحساسة، وراجع permissions لكل job.

YAMLMinimal .NET CI workflow
name: dotnet-ci
on:
  push:
    branches: [ main ]
  pull_request:

permissions:
  contents: read

jobs:
  build-test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '8.0.x'
      - run: dotnet restore MyShop.sln
      - run: dotnet build MyShop.sln -c Release --no-restore
      - run: dotnet test MyShop.sln -c Release --no-build
      - run: dotnet publish src/MyShop.Api/MyShop.Api.csproj -c Release -o ./publish
      - uses: actions/upload-artifact@v4
        with:
          name: myshop-api
          path: ./publish

هذا نموذج تعليمي يحتاج تعديل paths و solution و test projects حسب repository. في الواقع أضف test reports و coverage، dependency vulnerability scan، secret scan، container scan، artifact retention، و concurrency cancellation للـ PR. لا تضع secrets في YAML أو echo commands؛ استخدم OIDC عند deploy إلى cloud بدل client secret طويل العمر متى أمكن.

GitHub Actions Pipeline لـ ‎.NET API

الـ pipeline تنتج artifact واحدًا معروفًا ثم تروّجه بين البيئات بدل إعادة build لكل environment. غيّر أسماء solution و test project ومسار API حسب مشروعك. افصل build/test عن deployment، واحمِ production deployment بـ Environment approval.

YAML.github/workflows/dotnet-ci.yml
name: dotnet-ci
on:
  pull_request:
  push:
    branches: [main]
permissions:
  contents: read
concurrency:
  group: api-${{ github.ref }}
  cancel-in-progress: true
jobs:
  build-test-publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-dotnet@v4
        with:
          dotnet-version: 8.0.x
      - run: dotnet restore MyShop.sln
      - run: dotnet build MyShop.sln -c Release --no-restore
      - run: dotnet test MyShop.sln -c Release --no-build
      - run: dotnet publish src/MyShop.Api/MyShop.Api.csproj -c Release -o ./publish
      - uses: actions/upload-artifact@v4
        with:
          name: api-publish
          path: publish/
          if-no-files-found: error
          retention-days: 7

تأكد أن test project داخل solution وأن build configuration متطابق. أضف integration tests مع SQL Server service container لو محتاج DB، واستخدم قاعدة disposable. ارفع TRX reports لتظهر نتائج الاختبارات في CI.

للنشر إلى Azure فضّل OIDC federated credentials مع azure/login بدل secret طويل العمر. عيّن id-token: write في job النشر فقط، واحتفظ بأقل permissions ممكنة. لا تمنح cloud credentials ل job ينفذ كود Pull Request غير موثوق.

GitHub Actions: Pipeline كاملة لـ ‎.NET مع Artifact و OIDC Deploy Gate

القاعدة الأساسية: ابنِ artifact مرة واحدة، اختبرها، ثم روّج نفس artifact بين environments بدل إعادة build لكل environment. استخدم permissions أقل ما يمكن، وافصل CI عن deployment، واجعل production environment تتطلب approvals. OIDC أفضل من تخزين long-lived Azure client secret عندما يكون مدعومًا.

YAMLGitHub Actions — .NET build, test, artifact and gated Azure deploy
name: orders-api-ci-cd

on:
  pull_request:
  push:
    branches: [main]

permissions:
  contents: read

concurrency:
  group: orders-api-${{ github.ref }}
  cancel-in-progress: true

jobs:
  build-test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '8.0.x'
      - name: Restore
        run: dotnet restore MyShop.sln
      - name: Build
        run: dotnet build MyShop.sln --configuration Release --no-restore
      - name: Test
        run: dotnet test MyShop.sln --configuration Release --no-build --logger "trx;LogFileName=tests.trx"
      - name: Publish
        run: dotnet publish src/MyShop.Api/MyShop.Api.csproj -c Release --no-restore -o ./publish
      - uses: actions/upload-artifact@v4
        with:
          name: orders-api-${{ github.sha }}
          path: publish/
          if-no-files-found: error
          retention-days: 14

  deploy-production:
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    needs: build-test
    runs-on: ubuntu-latest
    environment: production
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/download-artifact@v4
        with:
          name: orders-api-${{ github.sha }}
          path: ./publish
      - uses: azure/login@v2
        with:
          client-id: ${{ vars.AZURE_CLIENT_ID }}
          tenant-id: ${{ vars.AZURE_TENANT_ID }}
          subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
      - name: Deploy package
        run: |
          cd publish
          zip -r ../app.zip .
          az webapp deploy \
            --resource-group "$AZURE_RESOURCE_GROUP" \
            --name "$AZURE_WEBAPP_NAME" \
            --src-path ../app.zip \
            --type zip
        env:
          AZURE_RESOURCE_GROUP: ${{ vars.AZURE_RESOURCE_GROUP }}
          AZURE_WEBAPP_NAME: ${{ vars.AZURE_WEBAPP_NAME }}
      - name: Smoke test
        run: curl --fail --retry 8 --retry-delay 5 "$APP_HEALTH_URL"
        env:
          APP_HEALTH_URL: ${{ vars.APP_HEALTH_URL }}

هذا template يحتاج تعديل paths و solution names و Azure federated credential و resource names قبل التشغيل. تأكد أن az webapp deploy package format يناسب إعداد App Service ونوع التطبيق. لا تضع id-token: write في job build إذا لا يحتاجه. أضف artifact checksum/SBOM/signing حسب supply-chain policy، واحتفظ بسجل commit + artifact digest + deployment ID.

Release gates التي لا يجب تخطيها

  • PR: format/lint، unit tests، integration tests مع dependencies مؤقتة، dependency/security scan.
  • قبل production: approval، migration compatibility check، backup/restore readiness، smoke test، ومراقبة error rate/latency.
  • بعد النشر: تحقق من health و business transaction، ثم راقب فترة stabilization.
  • Rollback: أعد التطبيق إلى artifact السابق؛ لا ترجع schema تلقائيًا إذا migration غير backward-compatible.

Pipeline Design: من Commit إلى Artifact موثوق

CI يدمج التغييرات باستمرار ويعطي feedback سريعًا؛ CD يوصل artifact إلى بيئة قابلة للنشر أو ينشره تلقائيًا حسب سياسة المؤسسة. pipeline جيدة لها مراحل واضحة: restore، format/analyzers، build، unit tests، integration tests، security/dependency scan، package، publish artifact، deploy، smoke test. لا تجعل كل مرحلة تعتمد على نجاح يدوي غير مسجل.

قسّم الاختبارات حسب التكلفة: unit سريع لكل pull request؛ integration tests على dependencies حقيقية أو containers؛ end-to-end أقل عددًا لأنها أبطأ وأكثر هشاشة. استخدم caching للـ NuGet packages لكن لا تجعل cache مصدر الحقيقة. احفظ test results و coverage و SBOM و image digest مع artifact. افصل permissions: job الذي يبني من fork لا يحصل على production secrets.

YAMLGitHub Actions: .NET build and test gate
name: dotnet-ci
on:
  pull_request:
  push:
    branches: [ main ]
permissions:
  contents: read
jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '8.0.x'
      - run: dotnet restore MySolution.sln
      - run: dotnet format MySolution.sln --verify-no-changes
      - run: dotnet build MySolution.sln -c Release --no-restore
      - run: dotnet test MySolution.sln -c Release --no-build --logger trx

الإصدارات أعلاه أمثلة؛ في supply-chain hardened pipeline ثبّت actions إلى full commit SHA وراجع updates. أضف integration job و artifact publishing حسب solution. لا تضع secrets في PR من forks، ولا تجعل test step يطبع connection strings أو tokens.

Test Pyramid و Flaky Tests و Pipeline Feedback

Unit tests يجب تكون deterministic وسريعة ولا تعتمد على clock/network/shared DB. استخدم injected clock و fake dependencies. Integration tests تختبر boundaries حقيقية وتعمل isolation للبيانات. E2E قليلة وتغطي user journeys عالية المخاطر. Flaky tests تستهلك الثقة؛ سجل failure diagnostics، امنع shared mutable fixtures، وتجنب sleeps الثابتة واستبدلها polling bounded مع timeout.

رتب المراحل لتقديم feedback مبكر: formatting/static checks، compile، fast unit tests، ثم integration/security scans، ثم packaging/deployment. لكن لا تؤخر critical security checks إلى ما بعد production. استخدم parallel jobs عند استقلالها، مع resource limits حتى لا تضغط database test environment. قِس pipeline duration و failure rate كجزء من developer experience.

04

GitHub Actions: Workflow و Jobs و Steps و Artifacts

Understand the execution model
Deep dive

Workflow YAML يحتوي events triggers و jobs. كل job يعمل في runner مستقل غالبًا؛ workspace/artifacts لا تنتقل تلقائيًا بين jobs. Steps داخل job تشارك filesystem، لكن كل step process جديد. استخدم artifacts لنقل build output بين jobs، و caches لتسريع dependencies، و outputs لتمرير metadata صغيرة. لا تستخدم artifacts لتخزين secrets.

حدد permissions بأقل scope مطلوب. افصل build job عن deploy job، واجعل deploy يحتاج environment approval في production. استخدم concurrency groups لمنع deployment متزامن لنفس environment. لا تستخدم pull_request_target بلا فهم؛ event قد يعمل بصلاحيات repository عالية مع untrusted PR content.

YAMLEnvironment-gated deployment skeleton
jobs:
  deploy-production:
    needs: build-test
    runs-on: ubuntu-latest
    environment: production
    permissions:
      contents: read
      id-token: write
    concurrency:
      group: production-deployment
      cancel-in-progress: false
    steps:
      - name: Authenticate to cloud with OIDC
        run: echo "Configure provider-specific OIDC login here"
      - name: Deploy immutable artifact
        run: echo "Deploy image digest produced by the build job"

الخطوات الأخيرة placeholders وليست deploy command جاهزًا؛ Azure/GCP/AWS لها login/deploy actions مختلفة. لا تنس أن OIDC trust policy في cloud يجب تقيد repo/branch/environment/subject claims، وإلا قد يتحول id-token:write إلى privilege واسع.

05

Secrets في Pipeline و OIDC بدل Long-Lived Credentials

Reduce credential exposure
Deep dive

Secrets قد تظهر بالخطأ عبر echo، debug logs، process args، artifacts، Docker layers أو test output. لا تضع secret في YAML literal أو repository variable غير محمي. استخدم GitHub encrypted secrets أو environment secrets كحل أولي، لكن الأفضل للـ cloud authentication هو OIDC federation عندما provider يدعمها: GitHub يصدر short-lived identity token، والـ cloud يتحقق من claims ويمنح credentials قصيرة العمر.

Least privilege: deploy identity لا تحتاج Owner على subscription؛ امنحها role محدد على resource group/app. افصل identity للـ staging عن production. راجع branch protection، required reviewers، environment approvals، allowed actions و runner isolation. لا تستخدم self-hosted runner مشتركًا مع untrusted PRs إذا كان يحتفظ credentials أو network access داخلي.

Approvals و Environments و Secret Scoping

اربط production environment بحماية branch و required reviewers و deployment protection rules. استخدم identity منفصلة لكل environment؛ staging لا تحتاج صلاحية حذف production resources. اجعل credentials قصيرة العمر ومقيدة بال repo/branch/environment، وامنح job فقط الصلاحيات التي يحتاجها. لا تسمح ل workflow من fork أن يقرأ deployment secrets.

اكتب release manifest يتضمن commit SHA و image digest و migration version و feature flags المهمة. عند incident تستطيع تحديد ما تم نشره بدقة. راجع permissions لكل workflow token، ولا تستخدم write-all افتراضيًا. pipeline نفسها تحتاج code review و dependency pinning و audit logs مثل التطبيق تمامًا.

06

Deployment Strategies: Rolling و Blue-Green و Canary

Control blast radius
Deep dive

Rolling deployment يحدث instances تدريجيًا؛ بسيط لكن يتطلب backward-compatible changes أثناء coexistence. Blue-Green يشغل environment جديدة بجانب القديمة ثم يبدل traffic؛ rollback سريع نسبيًا لكن يحتاج capacity مضاعفة ومزامنة state. Canary يرسل نسبة صغيرة من traffic للإصدار الجديد ويراقب metrics قبل التوسع؛ يقلل blast radius لكنه يحتاج routing/telemetry موثوقين.

Feature flags تفصل code deployment عن feature release. flag قد تكون boolean أو targeting rules، لكن flags القديمة تتحول technical debt. عيّن owner و expiry date وخطة إزالة. لا تستخدم feature flag كبديل authorization أو security control؛ كل request يجب يمر server policy.

Deployment Strategies: Rolling و Blue-Green و Canary

Rolling: استبدال instances تدريجيًا؛ يحتاج backward compatibility بين النسخ القديمة والجديدة أثناء الانتقال. Blue-Green: بيئتان، تنشر في الخاملة ثم تحول traffic؛ rollback سريع لكن تكلفة الموارد أعلى وتحتاج state/schema compatibility. Canary: نسبة صغيرة من traffic للنسخة الجديدة ثم توسع تدريجي وفق metrics؛ تحتاج routing و observability وقدرة rollback تلقائي.

لا تختَر deployment strategy بالاسم فقط. اسأل: هل الجلسات sticky؟ هل هناك background workers؟ هل migrations backward-compatible؟ هل الرسائل قد تعالجها نسختان؟ هل feature flags تفصل نشر الكود عن تفعيل behavior؟ Deployment آمن يعني تقليل blast radius ومراقبة success metrics، لا مجرد نجاح command.

TextSafe progressive rollout
1. Deploy new version with feature disabled.
2. Run smoke tests and verify readiness.
3. Send 5% traffic to the new version.
4. Compare error rate, latency and business outcomes.
5. Increase to 25%, 50%, then 100% if healthy.
6. Keep previous artifact available for rollback.
7. Remove old version only after compatibility window.

حدد abort thresholds مسبقًا مثل ارتفاع 5xx أو p95 latency أو payment failure rate، مع baseline واقعي. لا تستخدم CPU وحده للحكم على نجاح release. في canary لا تجمع بيانات مستخدمين بشكل يخرق الخصوصية؛ احترم sampling و data retention.

Environment Promotion و Configuration Drift

افصل artifact عن environment configuration. نفس container image digest يمر Development/Staging/Production، بينما connection strings و feature flags و resource endpoints تأتي من configuration/secret store وقت التشغيل. لا تعِد build مع كل environment. استخدم deployment manifest أو Helm values/Terraform variables منفصلة مع مراجعة.

Config drift يحدث عندما تعديل يدوي في portal لا ينعكس في IaC أو deployment code. عرّف source of truth، نفذ drift detection، وامنع manual edits أو وثّق break-glass process يعيد التغيير إلى Git. افصل production approval عن صلاحية merge، وسجل من نشر ومتى وبأي artifact.

07

Database Migrations في Pipeline

Expand-and-contract, not blind startup migration
Deep dive

أخطر جزء في deployment أحيانًا database schema. لو الإصدار الجديد يتطلب column جديدًا بينما instances القديمة ما زالت تعمل، migration destructive قد تكسر rollback أو requests in-flight. استخدم expand-and-contract: أضف schema backward-compatible أولًا، انشر app تدعم القديم والجديد، انقل البيانات تدريجيًا، ثم في release لاحق احذف القديم بعد التأكد.

لا تجعل كل API instance تنفذ Database.Migrate() عند startup في production cluster؛ عدة instances قد تتنافس، و application identity قد تمتلك DDL privileges غير لازمة. الأفضل migration job منفصل بصلاحيات محدودة، review للـ SQL script، backup/restore plan، lock/timeout strategy، و post-migration validation. EF Core يمكن أن يولد idempotent migration scripts حسب workflow؛ راجع docs للإصدار المستخدم.

BashGenerate an idempotent EF Core migration script
dotnet ef migrations script --idempotent \
  --project MyShop.Infrastructure \
  --startup-project MyShop.Api \
  --output artifacts/migrations.sql

راجع generated SQL قبل production. Idempotent لا تعني risk-free ولا تعني أن migration سريعة أو online. إضافة NOT NULL column مع default على جدول ضخم قد تكون مكلفة حسب engine/version. اختبر على حجم بيانات مماثل، وقس lock duration، وخطط rollback أو roll-forward.

Database Migrations في CI/CD: Expand ثم Contract

المشكلة الكلاسيكية: التطبيق الجديد يتوقع column جديدة، لكن instances القديمة ما زالت تعمل؛ أو migration تحذف column قبل أن تتوقف النسخة القديمة. الحل غالبًا expand-contract: أضف schema متوافقة أولًا، انشر كودًا يقرأ/يكتب الجديد مع fallback أو dual-write محسوب، املأ البيانات تدريجيًا، ثم بعد انتهاء فترة التوافق احذف القديم في release لاحق.

تجنب migration طويلة تحبس table أثناء deployment. استخدم online/index operations حيث يدعم provider، batch backfill، lock timeout، ومراقبة transaction log/replication lag. لا تشغل migration بالتوازي من كل replica عند startup؛ استخدم dedicated migration job أو deployment stage واحدة مع lock مناسب. خذ backup واختبر restore وخطة rollback قبل destructive changes.

SQLExpand-contract example
-- Release A: additive and backward-compatible
ALTER TABLE dbo.Customers ADD DisplayNameV2 nvarchar(200) NULL;

-- Backfill in bounded batches; monitor locks and log growth.
UPDATE TOP (500) dbo.Customers
SET DisplayNameV2 = DisplayName
WHERE DisplayNameV2 IS NULL;

-- Release B: application reads new column, still tolerates old rows.
-- Release C: after all old app versions are gone, enforce NOT NULL / remove old column.

الـ SQL مثال conceptual؛ لا تنفذ backfill ضخمًا في transaction واحدة دون قياس. استخدم deterministic batching ومؤشرًا مناسبًا. Migration rollback لا تعني دائمًا استرجاع data بعد حذفها؛ أحيانًا forward-fix أكثر أمانًا. وثّق data migration منفصلة عن schema migration.

08

Rollback و Roll-Forward و Smoke Tests

A release is not complete until health is verified
Deep dive

Rollback code لا يعني rollback database تلقائيًا. لو migration حذفت column أو غيرت semantics، image القديمة قد لا تعمل. لذلك backward-compatible schema changes تقلل الحاجة إلى database rollback. أحيانًا roll-forward hotfix أكثر أمانًا من محاولة downgrade. احتفظ بالإصدار السابق image digest، config version، migration history و deployment metadata.

بعد deployment نفذ smoke tests: readiness endpoint، authentication flow، أهم API path، database connectivity، message broker/cache حسب dependency. راقب error rate/latency/traffic/saturation. لو metrics تجاوزت thresholds، أوقف rollout أو ارجع traffic. لا تعتبر HTTP 200 من root endpoint إثبات أن business workflow سليم.

Deployment و Smoke Test و Rollback

الـ deployment مش آخر خطوة. راجع artifact/version و configuration، نفّذ migration متوافقة، انشر، انتظر readiness، نفّذ smoke tests، ثم راقب error rate و latency. احتفظ بمعرّف النسخة السابقة وخطة rollback مجرّبة.

  1. Pre-deploy: راجع changelog و migration وتأكد من توافق schema بين النسخة القديمة والجديدة (expand/contract).
  2. Deploy: استخدم rolling أو blue/green أو canary حسب المنصة، ولا تنشر كل instances دفعة واحدة عند ارتفاع المخاطر.
  3. Verify: افحص /health/ready ثم endpoint وظيفي آمن. health check وحده لا يثبت صحة business journey.
  4. Observe: قارن 5xx و p95 latency و dependency failures و queue lag بخط الأساس.
  5. Rollback: أعد التطبيق إلى artifact سابق إذا تجاوزت مؤشرات الفشل threshold متفقًا عليه.

لا تفترض أن rollback للـ application يعكس database schema. صمّم migrations بحيث تعمل النسختان القديمة والجديدة معًا خلال نافذة النشر، ثم احذف الأعمدة القديمة في release لاحق. أحيانًا forward-fix أو restore مخطط أفضل من عكس migration عشوائيًا.

اكتب runbook يحدد owner و dashboards و alert links و rollback steps والشرط الذي يوقف rollout. نفّذ rollback drill في staging؛ الخطة التي لم تُجرّب مجرد افتراض.

Rollback ليس زرًا سحريًا: Data و Message Compatibility

حتى لو رجعت image القديمة، database قد أصبحت على schema أحدث، والرسائل في queue قد أُنتجت بالنسخة الجديدة. لذلك backward compatibility تشمل database schema و event/message contracts و cache keys و distributed locks. استخدم versioned message envelopes، consumers تتجاهل unknown optional fields، و deploy order يضمن أن consumers الجديدة تقبل messages القديمة والجديدة قبل producers الجديدة.

في rollback plan حدد ما إذا كان rollback code فقط، أم forward fix، أم data repair. لا تحذف عمودًا في نفس release الذي تتوقف فيه عن كتابته إذا كانت النسخة القديمة قد تعود. لا تغير معنى enum value موجودة. اختبر rollback في staging ببيانات قريبة من production، وسجل شروط إيقافه.

Post-Deploy Verification و Release Evidence

بعد deploy، انتظر readiness مستقرة ثم نفذ smoke tests على endpoints حرجة. قارن error rate و p95 latency و dependency failures و business conversion قبل/بعد. سجّل artifact digest و commit و migration version و deployment actor. لو verification فشلت، أوقف rollout وابدأ rollback/mitigation حسب runbook. لا تكتفِ بأن orchestrator أعلن rollout complete.

احتفظ بالأدلة: test reports، SBOM، scan results، signature/provenance، approvals، deployment logs، و post-deploy metrics. هذا يساعد incident response و audit و supply-chain review. لا تخزن secrets ضمن artifacts أو reports. راجع retention و access controls لهذه الأدلة.

Pipeline Failure Drills: اختبر الـ Recovery مش الـ Happy Path فقط

نفّذ drills: dependency restore يفشل، test timeout، registry unavailable، secret expired، deployment يتوقف بعد نصف replicas، migration تفشل بعد إضافة column، smoke test يرجع 500، و rollback artifact غير متاح. لكل drill وثّق detection، safe stop، retry policy، owner، والـ recovery evidence. لا تجعل pipeline تعيد محاولة كل شيء بلا حدود؛ بعض الفشل deterministic ويحتاج تدخلًا.

احفظ logs و artifacts حتى تستطيع إعادة بناء ما حدث، لكن لا تحفظ secrets. راجع race conditions في concurrent deployments إلى نفس environment؛ استخدم deployment concurrency lock أو environment queue. لا تسمح release قديمة أن تنشر بعد release أحدث بسبب job متأخرة.

09

DORA Metrics: قياس Delivery بدون Gaming

Use metrics to improve the system
Practical

DORA metrics الشائعة تشمل deployment frequency، lead time for changes، change failure rate، و time to restore service؛ بعض أطر القياس الحديثة تضيف reliability dimension وتعيد تعريف التفاصيل. الهدف قياس قدرة الفريق على تقديم تغييرات صغيرة آمنة والتعافي، وليس ترتيب الأفراد أو زيادة deployments بلا قيمة.

لا تحسن metric على حساب جودة المنتج: deployment frequency وحدها قد تشجع releases صغيرة بلا اختبارات، و lead time قد يدفع لتجاوز review. اربط القياس بمخرجات المستخدم و incident severity و rework. قارن الفريق بنفسه عبر الزمن مع سياق workload وليس benchmarks سطحية.

قياس صحة CI/CD: Deployment Frequency و Change Failure Rate

قِس delivery system بمجموعة مؤشرات متوازنة: deployment frequency، lead time for changes، change failure rate، time to restore service. لا تستخدم metric منفردة كهدف يضغط الفريق لإطلاق تغييرات صغيرة بلا جودة. اربطها ب incident data و rollback و hotfixes، وفسرها حسب service criticality. الهدف تقليل زمن feedback وتقليل مخاطر التغيير، لا سباق عدد deployments.

اجعل deployment event يسجل commit SHA و artifact digest و environment و approver و timestamp. اربط ذلك بالـ traces/errors حتى تستطيع الإجابة: هل بدأ regression بعد release معين؟ استخدم automated rollback فقط عندما signal موثوق و threshold واضح؛ وإلا قد تسبب oscillation. نفذ game day للـ rollback نفسه.

10

Pipeline Security و Supply Chain

The build system is production infrastructure
Deep dive

CI pipeline تملك صلاحيات وقد تنتج artifact يدخل production؛ لذلك هي target أمني. قلل permissions، pin actions، راجع third-party actions، امنع secrets من PR forks، افصل untrusted test execution عن deploy credentials، استخدم dependency review و SBOM/image scanning، ووقع artifacts عند الحاجة. راجع provenance: أي commit بنى image؟ أي workflow؟ أي dependencies؟ وأي digest تم نشره؟

لا تستخدم latest كـ release identity. سجل commit SHA، semantic version، image digest، build metadata و deployment environment. اجعل logs لا تحتوي tokens أو connection strings. Runner ephemeral أفضل من runner دائم يحتفظ ببقايا أسرار أو ملفات من job سابق.

Supply Chain Security: Dependencies و Secrets و Provenance

pipeline تملك صلاحية الوصول إلى source و registry وربما cloud؛ لذلك compromise فيها يساوي compromise للمنتج. استخدم least privilege، short-lived OIDC credentials بدل long-lived cloud keys حيث أمكن، secret masking، branch protection، required reviews، dependency pinning، artifact signing، SBOM، vulnerability scanning، و separation بين build و deploy identities.

لا تعتبر scanner بلا findings ضمانًا للأمان؛ راجع exploitability و reachability و patch policy. ضع exception موثقًا له owner و expiry، لا suppress دائمًا. افحص container base image والـ NuGet dependencies و GitHub Actions. لا تطبع environment dump في failure logs. احمِ cache من poisoning بين untrusted PR و trusted release.

Pipeline Ownership و Change Management

عيّن owner للـ workflow ووقت مراجعة دوري للـ actions/providers والـ permissions. احذف steps القديمة، حدّث runtime versions، وراجع deprecation notices. اجعل failure message توضح الخطوة والـ artifact والـ environment بدل log ضخم. وثّق break-glass deployment مع audit trail ومراجعة لاحقة؛ لا تجعل emergency path bypass دائمًا لكل security gates.

11

اختبر فهمك

Knowledge check
Practical
ما الفرق بين Continuous Delivery و Continuous Deployment؟
Delivery يجعل الإصدار جاهزًا للنشر مع approval ممكن؛ Deployment ينشر تلقائيًا بعد اجتياز gates.
لماذا نبني image مرة ونرقّي نفس digest؟
حتى يكون artifact الذي اختبرناه هو نفسه الذي نُشر، مع اختلاف runtime configuration فقط.
هل OIDC وحده يكفي لتأمين cloud deployment؟
لا؛ لازم trust policy تقيد repository/branch/environment، مع least-privilege roles.
لماذا migration job منفصل أفضل من كل API instance؟
يمنع تنافس instances على DDL، ويفصل صلاحيات schema change عن صلاحيات runtime.
هل rollback application image يعكس database migration؟
لا؛ schema changes تحتاج backward compatibility أو roll-forward/restore strategy مستقلة.
12

Quality Gates: إيه الذي يمنع Release؟

Fail fast on defects that matter
Deep dive

قسّم gates حسب التكلفة: formatting/analyzers و unit tests سريعًا؛ integration tests مع database/container؛ contract tests؛ security scanning؛ ثم staging smoke tests. اجعل failure واضحًا مع artifact للتشخيص. لا تجعل flaky test يمر بصمت بعد retry غير محدود؛ سجل flakiness واصلح السبب. لا تخفِ فشل integration tests بتشغيل unit tests فقط.

اختبر migrations على نسخة schema قريبة من production، لكن لا تشغل migration destructive بلا خطة. استخدم expand-and-contract: أضف column جديدًا optional، انشر كودًا يقرأ القديم والجديد، املأ البيانات، انقل الكتابة، ثم احذف القديم في release لاحق. rollback للتطبيق لا يعيد database schema تلقائيًا؛ migration forward-fix قد يكون أكثر أمانًا من downgrade.

اجعل deployment منفصلًا عن build: artifact immutable، environment approval، OIDC identity محدودة، smoke test، health gate، ثم traffic shift. احتفظ برقم commit و artifact digest و migration version في release metadata حتى تستطيع ربط incident بالإصدار.

Release Gates: ما الذي يمنع Deployment؟

حدد gates قابلة للقياس: build clean، unit/integration tests ناجحة، critical vulnerabilities لا توجد أو لها approved exception، migration plan reviewed، image signature valid، smoke test ناجح، readiness stable، و error/latency ضمن thresholds. لا تجعل gate مجرد “coverage 80%”؛ coverage لا تقيس جودة assertions. راجع critical paths and risk-based coverage.

بعد deployment استخدم automated verification: health endpoint، synthetic transaction غير مؤثرة، قراءة/كتابة canary data، ومراقبة SLO burn. لا تنفذ synthetic payment حقيقيًا أو بيانات production بلا isolation. إذا فشل verification، أوقف promotion تلقائيًا وأرسل alert مع artifact/version و runbook.

Release Checklist: Ready to Ship

  • Artifact digest معروف وثابت، ونتائج build/test مرتبطة به.
  • Security scan و SBOM و signature/provenance متاحة وفق policy.
  • Database migration additive/backward-compatible أو لها maintenance plan واضح.
  • Secrets و managed identity و network access مضبوطة للـ environment.
  • Health/readiness و dashboards و alerts و runbook جاهزة.
  • Rollback أو forward-fix decision محدد، مع data compatibility.
  • Smoke test و synthetic checks لا تسبب side effects مالية حقيقية.
  • Owner و approver و deployment window معروفون.

لو بند غير منطبق، وثّق السبب بدل وضع علامة نجاح وهمية. Checklist تساعد على منع النسيان، لكنها لا تحل محل automated gates أو engineering judgment. بعد release راجع metrics والـ incidents لتحديث checklist نفسها.

↗

المراجع والقراءة الإضافية

References & further reading

الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)

خريطة التغطية: 16 عنصر من الـ Roadmap ومكان شرحه في الدرس
RoadmapContinuous Integration§01
RoadmapContinuous Delivery and Deployment§01
RoadmapBuild Pipelines§01
RoadmapAutomated Testing§01
RoadmapAutomated Builds§01
RoadmapDeployment Pipelines§01
RoadmapGitHub Actions§03
RoadmapEnvironment Configuration§03
RoadmapSecrets in Pipelines§03
RoadmapDeployment Strategies§03
RoadmapRollback Fundamentals§03
SuggestedBlue-green and canary releases§03
SuggestedFeature flags§03
SuggestedDatabase migrations in the pipeline§03
SuggestedPipeline security: OIDC instead of long-lived secrets§03
SuggestedDORA metrics awareness§03

خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.

محتويات الدرس