Usamos cookies para mejorar tu experiencia en el sitio
CodeWorlds

CI/CD Pipeline - automatyczna kuźnia legionów

mistrzu automatyzacji! Konsul Caesar.js odkrył tajemnicę automatycznej kuźni legionów, która sama buduje, testuje i wysyła forty na kampanię bez ręcznej interwencji! CI/CD Pipeline to zautomatyzowany system, który przejmuje całą pracę związaną z integracją kodu, testowaniem i wdrażaniem aplikacji.

CI/CD to praktyki DevOps obejmujące Continuous Integration (ciągłą integrację) i Continuous Deployment/Delivery (ciągłe wdrażanie), które automatyzują proces od commitowania kodu do produkcji.

GitHub Actions - robotyczna legion

1# .github/workflows/legionariusze-legion-ci.yml
2name: Legionary Legion CI/CD Pipeline
3
4on:
5 push:
6 branches: [ main, develop ]
7 pull_request:
8 branches: [ main ]
9 release:
10 types: [ published ]
11
12env:
13 NODE_VERSION: '18'
14 REGISTRY: ghcr.io
15 IMAGE_NAME: legionariusze-legion/api
16
17jobs:
18 # Etap 1: Sprawdzenie jakości kodu
19 code-quality:
20 name: Code Quality Check
21 runs-on: ubuntu-latest
22 
23 steps:
24 - name: 🦅 Checkout repository
25 uses: actions/checkout@v4
26 
27 - name: Setup Node.js
28 uses: actions/setup-node@v4
29 with:
30 node-version: ${{ env.NODE_VERSION }}
31 cache: 'npm'
32 
33 - name: Install dependencies
34 run: npm ci
35 
36 - name: Lint code
37 run: npm run lint
38 
39 - name: Check code formatting
40 run: npm run format:check
41 
42 - name: Security audit
43 run: npm audit --audit-level=high
44 
45 - name: Upload lint results
46 uses: github/super-linter@v4
47 if: always()
48 env:
49 DEFAULT_BRANCH: main
50 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
51
52 # Etap 2: Uruchomienie testów
53 test:
54 name: 🧪 Run Tests
55 runs-on: ubuntu-latest
56 needs: code-quality
57 
58 services:
59 postgres:
60 image: postgres:15
61 env:
62 POSTGRES_PASSWORD: test_password
63 POSTGRES_USER: test_user
64 POSTGRES_DB: legionariusze_legion_test
65 options: >-
66 --health-cmd pg_isready
67 --health-interval 10s
68 --health-timeout 5s
69 --health-retries 5
70 ports:
71 - 5432:5432
72 
73 redis:
74 image: redis:7-alpine
75 options: >-
76 --health-cmd "redis-cli ping"
77 --health-interval 10s
78 --health-timeout 5s
79 --health-retries 5
80 ports:
81 - 6379:6379
82 
83 steps:
84 - name: 🦅 Checkout repository
85 uses: actions/checkout@v4
86 
87 - name: Setup Node.js
88 uses: actions/setup-node@v4
89 with:
90 node-version: ${{ env.NODE_VERSION }}
91 cache: 'npm'
92 
93 - name: Install dependencies
94 run: npm ci
95 
96 - name: Build application
97 run: npm run build
98 
99 - name: 🧪 Run unit tests
100 run: npm run test:unit
101 env:
102 DB_HOST: localhost
103 DB_PORT: 5432
104 DB_USERNAME: test_user
105 DB_PASSWORD: test_password
106 DB_DATABASE: legionariusze_legion_test
107 REDIS_HOST: localhost
108 REDIS_PORT: 6379
109 JWT_SECRET: test-secret-key-for-ci
110 
111 - name: Run integration tests
112 run: npm run test:integration
113 env:
114 DB_HOST: localhost
115 DB_PORT: 5432
116 DB_USERNAME: test_user
117 DB_PASSWORD: test_password
118 DB_DATABASE: legionariusze_legion_test
119 REDIS_HOST: localhost
120 REDIS_PORT: 6379
121 
122 - name: Run e2e tests
123 run: npm run test:e2e
124 env:
125 DB_HOST: localhost
126 DB_PORT: 5432
127 DB_USERNAME: test_user
128 DB_PASSWORD: test_password
129 DB_DATABASE: legionariusze_legion_test
130 
131 - name: Generate coverage report
132 run: npm run test:coverage
133 
134 - name: Upload coverage to Codecov
135 uses: codecov/codecov-action@v3
136 with:
137 file: ./coverage/lcov.info
138 flags: unittests
139 name: legionariusze-legion-coverage
140
141 # Etap 3: Budowanie obrazu Docker
142 build:
143 name: Build Docker Image
144 runs-on: ubuntu-latest
145 needs: test
146 outputs:
147 image-digest: ${{ steps.build.outputs.digest }}
148 image-tag: ${{ steps.meta.outputs.tags }}
149 
150 steps:
151 - name: 🦅 Checkout repository
152 uses: actions/checkout@v4
153 
154 - name: Set up Docker Buildx
155 uses: docker/setup-buildx-action@v3
156 
157 - name: Log in to Container Registry
158 uses: docker/login-action@v3
159 with:
160 registry: ${{ env.REGISTRY }}
161 username: ${{ github.actor }}
162 password: ${{ secrets.GITHUB_TOKEN }}
163 
164 - name: Extract metadata
165 id: meta
166 uses: docker/metadata-action@v5
167 with:
168 images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
169 tags: |
170 type=ref,event=branch
171 type=ref,event=pr
172 type=semver,pattern={{version}}
173 type=semver,pattern={{major}}.{{minor}}
174 type=sha,prefix={{branch}}-
175 
176 - name: Build and push Docker image
177 id: build
178 uses: docker/build-push-action@v5
179 with:
180 context: .
181 platforms: linux/amd64,linux/arm64
182 push: true
183 tags: ${{ steps.meta.outputs.tags }}
184 labels: ${{ steps.meta.outputs.labels }}
185 cache-from: type=gha
186 cache-to: type=gha,mode=max
187 
188 - name: Generate SBOM
189 uses: anchore/sbom-action@v0
190 with:
191 image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
192 format: spdx-json
193 output-file: sbom.spdx.json
194 
195 - name: Scan image for vulnerabilities
196 uses: aquasecurity/trivy-action@master
197 with:
198 image-ref: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
199 format: 'sarif'
200 output: 'trivy-results.sarif'
201 
202 - name: Upload Trivy scan results
203 uses: github/codeql-action/upload-sarif@v2
204 if: always()
205 with:
206 sarif_file: 'trivy-results.sarif'
207
208 # Etap 4: Deploy do staging
209 deploy-staging:
210 name: Deploy to Staging
211 runs-on: ubuntu-latest
212 needs: build
213 if: github.ref == 'refs/heads/develop'
214 environment: 
215 name: staging
216 url: https://staging-api.legionariuszelegion.com
217 
218 steps:
219 - name: 🦅 Checkout repository
220 uses: actions/checkout@v4
221 
222 - name: Configure AWS credentials
223 uses: aws-actions/configure-aws-credentials@v4
224 with:
225 aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
226 aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
227 aws-region: us-east-1
228 
229 - name: Deploy to ECS Staging
230 run: |
231 aws ecs update-service  --cluster legionariusze-legion-staging  --service legionariusze-api-staging  --force-new-deployment
232 
233 - name: ⏳ Wait for deployment
234 run: |
235 aws ecs wait services-stable  --cluster legionariusze-legion-staging  --services legionariusze-api-staging
236 
237 - name: Health check
238 run: |
239 for i in {1..30}; do
240 if curl -f https://staging-api.legionariuszelegion.com/health; then
241 echo "✅ Staging deployment healthy"
242 exit 0
243 fi
244 echo "⏳ Waiting for health check... ($i/30)"
245 sleep 30
246 done
247 echo "❌ Health check failed"
248 exit 1
249 
250 - name: 🧪 Run smoke tests
251 run: npm run test:smoke -- --env=staging
252
253 # Etap 5: Deploy do produkcji
254 deploy-production:
255 name: Deploy to Production
256 runs-on: ubuntu-latest
257 needs: build
258 if: github.event_name == 'release'
259 environment: 
260 name: production
261 url: https://api.legionariuszelegion.com
262 
263 steps:
264 - name: 🦅 Checkout repository
265 uses: actions/checkout@v4
266 
267 - name: Configure AWS credentials
268 uses: aws-actions/configure-aws-credentials@v4
269 with:
270 aws-access-key-id: ${{ secrets.PROD_AWS_ACCESS_KEY_ID }}
271 aws-secret-access-key: ${{ secrets.PROD_AWS_SECRET_ACCESS_KEY }}
272 aws-region: us-east-1
273 
274 - name: Backup database
275 run: |
276 aws rds create-db-snapshot  --db-instance-identifier legionariusze-legion-prod  --db-snapshot-identifier "pre-deploy-$(date +%Y%m%d-%H%M%S)"
277 
278 - name: Blue-Green deployment
279 run: |
280 # Update task definition with new image
281 TASK_DEFINITION=$(aws ecs describe-task-definition  --task-definition legionariusze-legion-prod  --query taskDefinition)
282 
283 NEW_TASK_DEFINITION=$(echo $TASK_DEFINITION | jq --arg IMAGE "${{ needs.build.outputs.image-tag }}"  '.containerDefinitions[0].image = $IMAGE')
284 
285 aws ecs register-task-definition  --cli-input-json "$NEW_TASK_DEFINITION"
286 
287 # Update service
288 aws ecs update-service  --cluster legionariusze-legion-prod  --service legionariusze-api-prod  --task-definition legionariusze-legion-prod
289 
290 - name: ⏳ Wait for deployment
291 run: |
292 aws ecs wait services-stable  --cluster legionariusze-legion-prod  --services legionariusze-api-prod
293 
294 - name: Production health check
295 run: |
296 for i in {1..60}; do
297 if curl -f https://api.legionariuszelegion.com/health; then
298 echo "✅ Production deployment healthy"
299 exit 0
300 fi
301 echo "⏳ Waiting for health check... ($i/60)"
302 sleep 30
303 done
304 echo "❌ Production health check failed"
305 exit 1
306 
307 - name: Update monitoring
308 run: |
309 curl -X POST https://api.datadog.com/api/v1/events  -H "Content-Type: application/json"  -H "DD-API-KEY: ${{ secrets.DATADOG_API_KEY }}"  -d '{
310 "title": " Legionary Legion Deployed",
311 "text": "Version ${{ github.event.release.tag_name }} deployed to production",
312 "tags": ["deployment", "production", "legionariusze-legion"]
313 }'

GitLab CI/CD Pipeline

1# .gitlab-ci.yml
2stages:
3 - validate
4 - test
5 - build
6 - security
7 - deploy-staging
8 - deploy-production
9
10variables:
11 DOCKER_IMAGE: $CI_REGISTRY_IMAGE
12 DOCKER_TAG: $CI_COMMIT_SHORT_SHA
13 NODE_VERSION: "18"
14
15# Szablony dla wielokrotnego użycia
16.node_template: &node_template
17 image: node:18-alpine
18 cache:
19 paths:
20 - node_modules/
21 before_script:
22 - npm ci
23
24.docker_template: &docker_template
25 image: docker:24-dind
26 services:
27 - docker:24-dind
28 before_script:
29 - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
30
31# Etap walidacji
32code-quality:
33 <<: *node_template
34 stage: validate
35 script:
36 - npm run lint
37 - npm run format:check
38 - npm audit --audit-level=high
39 artifacts:
40 reports:
41 junit: lint-results.xml
42 expire_in: 1 week
43
44# Testowanie
45unit-tests:
46 <<: *node_template
47 stage: test
48 services:
49 - postgres:15-alpine
50 - redis:7-alpine
51 variables:
52 POSTGRES_PASSWORD: test_password
53 POSTGRES_USER: test_user
54 POSTGRES_DB: legionariusze_legion_test
55 DB_HOST: postgres
56 REDIS_HOST: redis
57 script:
58 - npm run build
59 - npm run test:unit
60 - npm run test:integration
61 coverage: '/Statementss*:s*([^%]+)/'
62 artifacts:
63 reports:
64 junit: test-results.xml
65 coverage_report:
66 coverage_format: cobertura
67 path: coverage/cobertura-coverage.xml
68 expire_in: 1 week
69
70e2e-tests:
71 <<: *node_template
72 stage: test
73 services:
74 - postgres:15-alpine
75 - redis:7-alpine
76 variables:
77 POSTGRES_PASSWORD: test_password
78 POSTGRES_USER: test_user
79 POSTGRES_DB: legionariusze_legion_test
80 script:
81 - npm run test:e2e
82 artifacts:
83 when: always
84 paths:
85 - e2e-screenshots/
86 expire_in: 1 week
87
88# Budowanie
89build-image:
90 <<: *docker_template
91 stage: build
92 script:
93 - docker build --pull -t $DOCKER_IMAGE:$DOCKER_TAG .
94 - docker push $DOCKER_IMAGE:$DOCKER_TAG
95 - docker tag $DOCKER_IMAGE:$DOCKER_TAG $DOCKER_IMAGE:latest
96 - docker push $DOCKER_IMAGE:latest
97 only:
98 - main
99 - develop
100
101# Bezpieczeństwo
102security-scan:
103 image: registry.gitlab.com/security-products/container-scanning:latest
104 stage: security
105 variables:
106 CS_IMAGE: $DOCKER_IMAGE:$DOCKER_TAG
107 artifacts:
108 reports:
109 container_scanning: gl-container-scanning-report.json
110 dependencies:
111 - build-image
112 only:
113 - main
114 - develop
115
116# Deploy staging
117deploy-staging:
118 image: alpine/helm:latest
119 stage: deploy-staging
120 environment:
121 name: staging
122 url: https://staging-api.legionariuszelegion.com
123 script:
124 - helm upgrade --install legionariusze-legion-staging ./helm/legionariusze-legion 
125 --namespace staging 
126 --set image.tag=$DOCKER_TAG
127 --set environment=staging
128 --wait
129 - kubectl rollout status deployment/legionariusze-legion-api -n staging
130 only:
131 - develop
132
133deploy-production:
134 image: alpine/helm:latest
135 stage: deploy-production
136 environment:
137 name: production
138 url: https://api.legionariuszelegion.com
139 when: manual
140 script:
141 - helm upgrade --install legionariusze-legion ./helm/legionariusze-legion 
142 --namespace production 
143 --set image.tag=$DOCKER_TAG
144 --set environment=production
145 --wait
146 - kubectl rollout status deployment/legionariusze-legion-api -n production
147 only:
148 - main

Azure DevOps Pipeline

1# azure-pipelines.yml
2trigger:
3 branches:
4 include:
5 - main
6 - develop
7 paths:
8 exclude:
9 - README.md
10 - docs/*
11
12pool:
13 vmImage: 'ubuntu-latest'
14
15variables:
16 containerRegistry: 'legionariuszelegionregistry.azurecr.io'
17 imageName: 'legionariusze-legion-api'
18 imageTag: '$(Build.BuildId)'
19 nodeVersion: '18.x'
20
21stages:
22- stage: Validate
23 displayName: 'Code Quality & Security'
24 jobs:
25 - job: CodeQuality
26 displayName: 'Code Quality Check'
27 steps:
28 - task: NodeTool@0
29 inputs:
30 versionSpec: $(nodeVersion)
31 displayName: 'Install Node.js'
32 
33 - task: Cache@2
34 inputs:
35 key: 'npm | "$(Agent.OS)" | package-lock.json'
36 restoreKeys: |
37 npm | "$(Agent.OS)"
38 path: $(npm_config_cache)
39 displayName: 'Cache npm'
40 
41 - script: |
42 npm ci
43 npm run lint
44 npm run format:check
45 npm audit --audit-level=high
46 displayName: 'Code quality checks'
47
48- stage: Test
49 displayName: 'Run Tests'
50 dependsOn: Validate
51 jobs:
52 - job: UnitTests
53 displayName: 'Unit & Integration Tests'
54 services:
55 postgres: postgres:15
56 redis: redis:7-alpine
57 variables:
58 POSTGRES_PASSWORD: test_password
59 POSTGRES_USER: test_user
60 POSTGRES_DB: legionariusze_legion_test
61 steps:
62 - task: NodeTool@0
63 inputs:
64 versionSpec: $(nodeVersion)
65 
66 - script: |
67 npm ci
68 npm run build
69 npm run test:unit
70 npm run test:integration
71 displayName: 'Run tests'
72 env:
73 DB_HOST: localhost
74 DB_PORT: 5432
75 REDIS_HOST: localhost
76 REDIS_PORT: 6379
77 
78 - task: PublishTestResults@2
79 condition: succeededOrFailed()
80 inputs:
81 testRunner: JUnit
82 testResultsFiles: 'test-results.xml'
83 
84 - task: PublishCodeCoverageResults@1
85 inputs:
86 codeCoverageTool: Cobertura
87 summaryFileLocation: 'coverage/cobertura-coverage.xml'
88
89- stage: Build
90 displayName: 'Build & Push Docker Image'
91 dependsOn: Test
92 jobs:
93 - job: BuildImage
94 displayName: 'Build Docker Image'
95 steps:
96 - task: Docker@2
97 displayName: 'Build and push image'
98 inputs:
99 command: 'buildAndPush'
100 repository: $(imageName)
101 dockerfile: 'Dockerfile'
102 containerRegistry: $(containerRegistry)
103 tags: |
104 $(imageTag)
105 latest
106
107- stage: DeployStaging
108 displayName: 'Deploy to Staging'
109 dependsOn: Build
110 condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/develop'))
111 jobs:
112 - deployment: DeployToStaging
113 displayName: 'Deploy to Staging Environment'
114 environment: 'legionariusze-legion-staging'
115 strategy:
116 runOnce:
117 deploy:
118 steps:
119 - task: HelmDeploy@0
120 inputs:
121 command: 'upgrade'
122 chartType: 'FilePath'
123 chartPath: './helm/legionariusze-legion'
124 releaseName: 'legionariusze-legion-staging'
125 namespace: 'staging'
126 overrideValues: |
127 image.tag=$(imageTag)
128 environment=staging

Skrypty deployment

1#!/bin/bash
2# scripts/deploy.sh - uniwersalny skrypt deployment
3
4set -euo pipefail
5
6# Kolory dla output
7RED='\033[0;31m'
8GREEN='\033[0;32m'
9YELLOW='\033[1;33m'
10BLUE='\033[0;34m'
11NC='\033[0m'
12
13log() {
14 echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}"
15}
16
17warn() {
18 echo -e "${YELLOW}[WARNING] $1${NC}"
19}
20
21error() {
22 echo -e "${RED}[ERROR] $1${NC}"
23 exit 1
24}
25
26# Konfiguracja
27ENVIRONMENT=${1:-staging}
28VERSION=${2:-latest}
29NAMESPACE="legionariusze-legion-${ENVIRONMENT}"
30HELM_CHART="./helm/legionariusze-legion"
31HEALTH_CHECK_URL=""
32
33case $ENVIRONMENT in
34 staging)
35 HEALTH_CHECK_URL="https://staging-api.legionariuszelegion.com/health"
36 ;;
37 production)
38 HEALTH_CHECK_URL="https://api.legionariuszelegion.com/health"
39 ;;
40 *)
41 error "Unknown environment: $ENVIRONMENT"
42 ;;
43esac
44
45log " Starting deployment to $ENVIRONMENT"
46log " Version: $VERSION"
47log " Namespace: $NAMESPACE"
48
49# Pre-deployment checks
50log " Running pre-deployment checks..."
51
52# Check if kubectl is configured
53if ! kubectl cluster-info &> /dev/null; then
54 error "kubectl is not configured or cluster is not accessible"
55fi
56
57# Check if namespace exists
58if ! kubectl get namespace $NAMESPACE &> /dev/null; then
59 log "Creating namespace $NAMESPACE"
60 kubectl create namespace $NAMESPACE
61fi
62
63# Check if Helm chart exists
64if [ ! -d "$HELM_CHART" ]; then
65 error "Helm chart not found at $HELM_CHART"
66fi
67
68# Database backup (for production only)
69if [ "$ENVIRONMENT" = "production" ]; then
70 log " Creating database backup..."
71 kubectl exec -n $NAMESPACE deployment/postgres -- pg_dump -U legionariusze legionariusze_legion_prod > "backup-$(date +%Y%m%d_%H%M%S).sql"
72fi
73
74# Deploy with Helm
75log "Deploying with Helm..."
76helm upgrade --install legionariusze-legion-$ENVIRONMENT $HELM_CHART  --namespace $NAMESPACE  --set image.tag=$VERSION  --set environment=$ENVIRONMENT  --set ingress.enabled=true  --wait  --timeout=10m
77
78# Wait for rollout
79log "⏳ Waiting for rollout to complete..."
80kubectl rollout status deployment/legionariusze-legion-api -n $NAMESPACE --timeout=600s
81
82# Health check
83log "Performing health check..."
84for i in {1..30}; do
85 if curl -f $HEALTH_CHECK_URL; then
86 log "✅ Health check passed"
87 break
88 fi
89 if [ $i -eq 30 ]; then
90 error "❌ Health check failed after 30 attempts"
91 fi
92 log "⏳ Health check attempt $i/30 failed, retrying in 10s..."
93 sleep 10
94done
95
96# Post-deployment verification
97log "🧪 Running post-deployment verification..."
98
99# Check if all pods are ready
100READY_PODS=$(kubectl get pods -n $NAMESPACE -l app=legionariusze-legion-api --field-selector=status.phase=Running | wc -l)
101if [ $READY_PODS -lt 2 ]; then
102 warn "Only $READY_PODS pods are ready"
103fi
104
105# Run smoke tests
106if command -v npm &> /dev/null; then
107 log "Running smoke tests..."
108 npm run test:smoke -- --env=$ENVIRONMENT
109fi
110
111# Update monitoring
112log " Updating monitoring dashboards..."
113curl -X POST "https://api.datadog.com/api/v1/events"  -H "Content-Type: application/json"  -H "DD-API-KEY: ${DATADOG_API_KEY:-}"  -d "{
114 "title": " Legionary Legion Deployed",
115 "text": "Version $VERSION deployed to $ENVIRONMENT",
116 "tags": ["deployment", "$ENVIRONMENT", "legionariusze-legion"],
117 "alert_type": "info"
118 }" || warn "Failed to send monitoring event"
119
120log "Deployment to $ENVIRONMENT completed successfully!"
121log "Application URL: $HEALTH_CHECK_URL"
122
123# Cleanup old images (keep last 5)
124log "🧹 Cleaning up old Docker images..."
125docker images | grep legionariusze-legion-api | tail -n +6 | awk '{print $3}' | xargs -r docker rmi || true
126
127log "✨ All done! Your legionariusze legion is marching smoothly!"

Monitoring pipeline

1// src/monitoring/pipeline-monitor.service.ts
2import { Injectable, Logger } from '@nestjs/common';
3import { HttpService } from '@nestjs/axios';
4
5@Injectable()
6export class PipelineMonitorService {
7 private readonly logger = new Logger(PipelineMonitorService.name);
8
9 constructor(private httpService: HttpService) {}
10
11 async notifyDeploymentStart(environment: string, version: string) {
12 const payload = {
13 text: `Starting deployment of Legionary Legion v${version} to ${environment}`,
14 attachments: [{
15 color: 'warning',
16 fields: [
17 { title: 'Environment', value: environment, short: true },
18 { title: 'Version', value: version, short: true },
19 { title: 'Status', value: 'Starting', short: true },
20 { title: 'Time', value: new Date().toISOString(), short: true }
21 ]
22 }]
23 };
24
25 await this.sendSlackNotification(payload);
26 }
27
28 async notifyDeploymentSuccess(environment: string, version: string, duration: number) {
29 const payload = {
30 text: `✅ Legionary Legion v${version} successfully deployed to ${environment}`,
31 attachments: [{
32 color: 'good',
33 fields: [
34 { title: 'Environment', value: environment, short: true },
35 { title: 'Version', value: version, short: true },
36 { title: 'Duration', value: `${duration}s`, short: true },
37 { title: 'Status', value: 'Success', short: true }
38 ]
39 }]
40 };
41
42 await this.sendSlackNotification(payload);
43 }
44
45 async notifyDeploymentFailure(environment: string, version: string, error: string) {
46 const payload = {
47 text: `❌ Legionary Legion v${version} deployment to ${environment} failed`,
48 attachments: [{
49 color: 'danger',
50 fields: [
51 { title: 'Environment', value: environment, short: true },
52 { title: 'Version', value: version, short: true },
53 { title: 'Error', value: error, short: false },
54 { title: 'Time', value: new Date().toISOString(), short: true }
55 ]
56 }]
57 };
58
59 await this.sendSlackNotification(payload);
60 }
61
62 private async sendSlackNotification(payload: any) {
63 try {
64 const webhookUrl = process.env.SLACK_WEBHOOK_URL;
65 if (!webhookUrl) {
66 this.logger.warn('Slack webhook URL not configured');
67 return;
68 }
69
70 await this.httpService.post(webhookUrl, payload).toPromise();
71 this.logger.log('Slack notification sent successfully');
72 } catch (error) {
73 this.logger.error('Failed to send Slack notification:', error);
74 }
75 }
76}

CI/CD Pipeline to automatyczna kuźnia legionów, która zapewnia że każdy fort wyruszający z bazy jest w pełni sprawny i gotowy do najcięższych kampanii!

Ir a CodeWorlds