-
Notifications
You must be signed in to change notification settings - Fork 0
1223 lines (1039 loc) · 48.6 KB
/
Copy pathci-cd.yml
File metadata and controls
1223 lines (1039 loc) · 48.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# BeeCompose CI/CD Pipeline
# Docker Compose Testing with Parallel CVE Scanning and Service Testing
#
# This workflow validates all Docker Compose configurations and scans images for vulnerabilities.
# Both CVE scanning and service testing run in parallel (matrix strategy) for faster pipeline execution.
#
# Pipeline stages:
# 1. Lint - Docker Compose linting with DCLint (syntax + best practices)
# 2. Validate OCI - Check OCI compatibility for artifact publishing
# 3. Discover - Find all services and validate basic syntax
# 4. Extract Images - Collect Docker images for CVE scanning
# 5. CVE Scan - Security vulnerability scanning with Trivy (parallel per image)
# 6. CVE Summary - Aggregate scan results
# 7. Test Services - Parallel Docker Compose testing (max 8 concurrent)
# 8. Test Summary - Aggregate test results
# 9. Summary - Final pipeline results
name: CI/CD Pipeline
on:
push:
branches: [main, master, develop]
paths:
- 'services/**'
- 'scripts/**'
- '.github/workflows/**'
- '.github/scripts/**'
- '.dclintrc.yaml'
pull_request:
branches: [main, master]
paths:
- 'services/**'
- 'scripts/**'
- '.github/workflows/**'
- '.github/scripts/**'
- '.dclintrc.yaml'
workflow_dispatch:
inputs:
skip_cve_scan:
description: 'Skip CVE vulnerability scanning'
required: false
default: 'false'
type: boolean
specific_service:
description: 'Test specific service only (leave empty for all)'
required: false
default: ''
type: string
fail_on_high:
description: 'Fail on HIGH severity CVEs (not just CRITICAL)'
required: false
default: 'false'
type: boolean
env:
# Test configuration
TEST_TIMEOUT_MINUTES: 5
HEALTH_CHECK_RETRIES: 30
HEALTH_CHECK_INTERVAL: 10
# CVE scanning configuration
# Note: CVE scan generates reports but does not fail the pipeline
# This allows tracking vulnerabilities while not blocking deployments
CVE_FAIL_ON_CRITICAL: false
CVE_FAIL_ON_HIGH: false
# Prevent concurrent CI runs on the same branch
concurrency:
group: ci-cd-${{ github.ref }}
cancel-in-progress: true
# Default permissions (restrictive) - minimal access by default
permissions:
contents: read
jobs:
# ============================================================================
# Job 1: Lint Docker Compose Files
# ============================================================================
lint:
name: Lint Docker Compose
runs-on: ubuntu-latest
outputs:
lint_passed: ${{ steps.lint.outputs.passed }}
error_count: ${{ steps.lint.outputs.error_count }}
warning_count: ${{ steps.lint.outputs.warning_count }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Discover compose files to lint
id: find-files
run: |
set -euo pipefail
echo "=== Finding Docker Compose files ==="
# Find all docker-compose.yml files, excluding nested services
FILES=()
while IFS= read -r file; do
# Get the directory depth (services/name/docker-compose.yml = depth 3)
DEPTH=$(echo "$file" | tr '/' '\n' | wc -l | tr -d ' ')
if [[ "$DEPTH" -eq 3 ]]; then
FILES+=("$file")
fi
done < <(find services -name "docker-compose.yml" -type f | sort)
FILE_COUNT=${#FILES[@]}
echo "Found $FILE_COUNT Docker Compose files"
# Save file list for linting
printf '%s\n' "${FILES[@]}" > /tmp/compose-files.txt
echo "file_count=$FILE_COUNT" >> $GITHUB_OUTPUT
- name: Run DCLint
id: lint
run: |
set -uo pipefail
echo "=== Running Docker Compose Linter (DCLint) ==="
# Create results directory
mkdir -p lint-results
# Run DCLint using Docker image
# Mount workspace and run linter recursively on services directory
# Note: dclint takes paths directly, not a 'lint' subcommand
docker run --rm \
-v "${{ github.workspace }}:/app" \
zavoloklom/dclint:latest \
/app/services \
-r \
-c /app/.dclintrc.yaml \
-f stylish \
-o /app/lint-results/dclint-report.txt \
2>&1 | tee lint-results/dclint-output.txt || LINT_EXIT_CODE=$?
LINT_EXIT_CODE=${LINT_EXIT_CODE:-0}
# Parse results for summary
ERROR_COUNT=0
WARNING_COUNT=0
if [[ -f lint-results/dclint-report.txt ]] && [[ -s lint-results/dclint-report.txt ]]; then
# Count errors and warnings from output (match severity indicators)
ERROR_COUNT=$(grep -cE '\berror\b' lint-results/dclint-report.txt 2>/dev/null || true)
WARNING_COUNT=$(grep -cE '\bwarning\b' lint-results/dclint-report.txt 2>/dev/null || true)
# Ensure we have valid integers
ERROR_COUNT=${ERROR_COUNT:-0}
WARNING_COUNT=${WARNING_COUNT:-0}
# Strip any whitespace
ERROR_COUNT=$(echo "$ERROR_COUNT" | tr -d '[:space:]')
WARNING_COUNT=$(echo "$WARNING_COUNT" | tr -d '[:space:]')
fi
# Validate counts are integers, default to 0 if not
[[ "$ERROR_COUNT" =~ ^[0-9]+$ ]] || ERROR_COUNT=0
[[ "$WARNING_COUNT" =~ ^[0-9]+$ ]] || WARNING_COUNT=0
echo "error_count=${ERROR_COUNT}" >> $GITHUB_OUTPUT
echo "warning_count=${WARNING_COUNT}" >> $GITHUB_OUTPUT
# Display results
echo ""
echo "=== DCLint Results ==="
if [[ -f lint-results/dclint-report.txt ]]; then
cat lint-results/dclint-report.txt
elif [[ -f lint-results/dclint-output.txt ]]; then
cat lint-results/dclint-output.txt
fi
# Determine pass/fail
if [[ $LINT_EXIT_CODE -eq 0 ]]; then
echo ""
echo "All Docker Compose files passed linting!"
echo "passed=true" >> $GITHUB_OUTPUT
else
echo ""
echo "::error::Docker Compose linting failed with $ERROR_COUNT error(s) and $WARNING_COUNT warning(s)"
echo "passed=false" >> $GITHUB_OUTPUT
exit 1
fi
- name: Generate JSON report for CI integration
if: always()
run: |
# Generate JSON format report for potential downstream processing
docker run --rm \
-v "${{ github.workspace }}:/app" \
zavoloklom/dclint:latest \
/app/services \
-r \
-c /app/.dclintrc.yaml \
-f json \
-o /app/lint-results/dclint-report.json \
2>/dev/null || true
- name: Upload lint results
uses: actions/upload-artifact@v7
if: always()
with:
name: dclint-results
path: lint-results/
retention-days: 30
- name: Add lint summary to GitHub Actions
if: always()
run: |
echo "## Docker Compose Lint Results" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
if [[ "${{ steps.lint.outputs.passed }}" == "true" ]]; then
echo "✅ **All files passed linting**" >> $GITHUB_STEP_SUMMARY
else
echo "❌ **Linting failed**" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "- Errors: ${{ steps.lint.outputs.error_count }}" >> $GITHUB_STEP_SUMMARY
echo "- Warnings: ${{ steps.lint.outputs.warning_count }}" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
echo "See the \`dclint-results\` artifact for detailed report." >> $GITHUB_STEP_SUMMARY
# ============================================================================
# Job 1b: Test bc CLI Helper
# ============================================================================
test-cli:
name: Test CLI Helper
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Install shellcheck
run: sudo apt-get install -y shellcheck
- name: Run bc CLI tests
run: ./.github/scripts/test-bc-cli.sh
- name: Add CLI test summary
if: always()
run: |
echo "## bc CLI Tests" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "CLI helper script validated successfully." >> $GITHUB_STEP_SUMMARY
# ============================================================================
# Job 1c: Service Coverage Check
# ============================================================================
# Ensures all services in services/ are documented in README.md and scripts/bc
service-coverage:
name: Service Coverage
runs-on: ubuntu-latest
outputs:
coverage_passed: ${{ steps.coverage.outputs.passed }}
service_count: ${{ steps.coverage.outputs.service_count }}
readme_count: ${{ steps.coverage.outputs.readme_count }}
bc_count: ${{ steps.coverage.outputs.bc_count }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Check service coverage
id: coverage
run: |
set -euo pipefail
echo "=== Checking Service Coverage ==="
# Count services in each location
SERVICE_COUNT=$(find services -maxdepth 1 -mindepth 1 -type d | wc -l | tr -d ' ')
README_COUNT=$(grep -cE "^\| \[.*\]\(services/.*/README\.md\)" README.md 2>/dev/null || echo 0)
BC_COUNT=$(grep -cE "^\s*echo \"\s+[a-z0-9-]+\s+-" scripts/bc 2>/dev/null || echo 0)
echo "Service directories: $SERVICE_COUNT"
echo "README.md entries: $README_COUNT"
echo "scripts/bc entries: $BC_COUNT"
# Output counts
echo "service_count=$SERVICE_COUNT" >> $GITHUB_OUTPUT
echo "readme_count=$README_COUNT" >> $GITHUB_OUTPUT
echo "bc_count=$BC_COUNT" >> $GITHUB_OUTPUT
# Run the full coverage check script
if ./.github/scripts/check-service-coverage.sh; then
echo "passed=true" >> $GITHUB_OUTPUT
else
echo "passed=false" >> $GITHUB_OUTPUT
exit 1
fi
- name: Add coverage summary
if: always()
run: |
echo "## Service Coverage Check" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
if [[ "${{ steps.coverage.outputs.passed }}" == "true" ]]; then
echo "✅ **All services properly documented**" >> $GITHUB_STEP_SUMMARY
else
echo "❌ **Service coverage incomplete**" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Location | Count |" >> $GITHUB_STEP_SUMMARY
echo "|----------|-------|" >> $GITHUB_STEP_SUMMARY
echo "| Service Directories | ${{ steps.coverage.outputs.service_count }} |" >> $GITHUB_STEP_SUMMARY
echo "| README.md Table | ${{ steps.coverage.outputs.readme_count }} |" >> $GITHUB_STEP_SUMMARY
echo "| scripts/bc List | ${{ steps.coverage.outputs.bc_count }} |" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "All services must be documented in README.md and scripts/bc." >> $GITHUB_STEP_SUMMARY
# ============================================================================
# Job 2: Validate OCI Compatibility
# ============================================================================
validate-oci:
name: Validate OCI Compatibility
runs-on: ubuntu-latest
needs: lint
outputs:
oci_compatible: ${{ steps.validate.outputs.compatible }}
bind_mount_count: ${{ steps.validate.outputs.bind_mount_count }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Check OCI compatibility
id: validate
run: |
set -uo pipefail
echo "=== Validating OCI Compatibility ==="
ERRORS=0
WARNINGS=0
BIND_MOUNTS=0
# Create results file
echo "# OCI Compatibility Report" > /tmp/oci-report.md
echo "" >> /tmp/oci-report.md
echo "| Service | Status | Issues |" >> /tmp/oci-report.md
echo "|---------|--------|--------|" >> /tmp/oci-report.md
for COMPOSE in services/*/docker-compose.yml; do
SERVICE=$(dirname "$COMPOSE" | xargs basename)
ISSUES=""
STATUS="✅ Pass"
# Load env files for variable substitution
ENV_FILE="services/${SERVICE}/.env"
EXAMPLE_FILE="services/${SERVICE}/.env.example"
set +u
if [[ -f "$ENV_FILE" ]]; then
set -a; source "$ENV_FILE" 2>/dev/null || true; set +a
fi
if [[ -f "$EXAMPLE_FILE" ]]; then
set -a; source "$EXAMPLE_FILE" 2>/dev/null || true; set +a
fi
set -u
# Check for bind mounts (except docker.sock which is allowed for traefik)
# Use awk to detect bind mounts and check if source is docker.sock
CONFIG=$(docker compose -f "$COMPOSE" config 2>/dev/null)
# Find bind mounts that are NOT docker.sock
# The config format has 'type: bind' followed by 'source: <path>' on next lines
BINDS=$(echo "$CONFIG" | awk '
/type: bind/ { in_bind=1; next }
in_bind && /source:/ {
if ($2 !~ /docker\.sock/) {
print $0
count++
}
in_bind=0
}
/^[^ ]/ { in_bind=0 }
END { exit (count > 0 ? 0 : 1) }
' 2>/dev/null) || true
if [[ -n "$BINDS" ]]; then
BIND_COUNT=$(echo "$BINDS" | wc -l | tr -d ' ')
BIND_MOUNTS=$((BIND_MOUNTS + BIND_COUNT))
ISSUES="${ISSUES}bind mounts ($BIND_COUNT); "
STATUS="❌ Fail"
ERRORS=$((ERRORS + 1))
echo "::error file=$COMPOSE::Contains $BIND_COUNT bind mount(s) - not OCI compatible"
fi
# Check for build directives
if grep -qE '^\s+build:' "$COMPOSE" 2>/dev/null; then
ISSUES="${ISSUES}build directive; "
STATUS="⚠️ Warn"
WARNINGS=$((WARNINGS + 1))
echo "::warning file=$COMPOSE::Contains build directive - images must be pre-built for OCI"
fi
# Check for local config file references (not in volumes section)
if grep -qE '^\s+-\s+\./[^/]+\.(yml|yaml|conf|env|toml):' "$COMPOSE" 2>/dev/null; then
ISSUES="${ISSUES}local config files; "
if [[ "$STATUS" != "❌ Fail" ]]; then
STATUS="⚠️ Warn"
fi
WARNINGS=$((WARNINGS + 1))
echo "::warning file=$COMPOSE::References local config files"
fi
# Default issues text
if [[ -z "$ISSUES" ]]; then
ISSUES="None"
fi
echo "| $SERVICE | $STATUS | $ISSUES |" >> /tmp/oci-report.md
done
# Summary
echo "" >> /tmp/oci-report.md
echo "## Summary" >> /tmp/oci-report.md
echo "" >> /tmp/oci-report.md
echo "- **Errors:** $ERRORS" >> /tmp/oci-report.md
echo "- **Warnings:** $WARNINGS" >> /tmp/oci-report.md
echo "- **Total bind mounts:** $BIND_MOUNTS" >> /tmp/oci-report.md
# Output results
echo "bind_mount_count=$BIND_MOUNTS" >> $GITHUB_OUTPUT
if [[ $ERRORS -eq 0 ]]; then
echo "compatible=true" >> $GITHUB_OUTPUT
echo ""
echo "All services are OCI compatible!"
else
echo "compatible=false" >> $GITHUB_OUTPUT
echo ""
echo "::error::$ERRORS service(s) have OCI compatibility issues"
exit 1
fi
echo ""
cat /tmp/oci-report.md
- name: Add OCI summary to GitHub Actions
if: always()
run: |
echo "## OCI Compatibility Check" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
if [[ "${{ steps.validate.outputs.compatible }}" == "true" ]]; then
echo "✅ **All services are OCI compatible**" >> $GITHUB_STEP_SUMMARY
else
echo "❌ **Some services have OCI compatibility issues**" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "Bind mounts detected: ${{ steps.validate.outputs.bind_mount_count }}" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
echo "Services can be deployed from OCI artifacts:" >> $GITHUB_STEP_SUMMARY
echo '```bash' >> $GITHUB_STEP_SUMMARY
echo 'docker compose -f oci://ghcr.io/beevelop/<service>:<version> up -d' >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
# ============================================================================
# Job 3: Discover and Validate Services
# ============================================================================
discover:
name: Discover Services
runs-on: ubuntu-latest
needs: [lint, validate-oci]
outputs:
services: ${{ steps.discover.outputs.services }}
service_count: ${{ steps.discover.outputs.service_count }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Discover Docker Compose services
id: discover
run: |
set -euo pipefail
echo "=== Discovering Docker Compose services ==="
# Extract service directories using proper line-by-line reading
SERVICES=()
SKIPPED_SERVICES=()
while IFS= read -r file; do
SERVICE_DIR=$(dirname "$file")
SERVICE_NAME=$(basename "$SERVICE_DIR")
# Skip nested services (like traefik/whoami) - only include depth=2 (services/name)
DEPTH=$(echo "$SERVICE_DIR" | tr '/' '\n' | wc -l | tr -d ' ')
if [[ "$DEPTH" -eq 2 ]]; then
# Skip services with .ci-skip marker file
if [[ -f "${SERVICE_DIR}/.ci-skip" ]]; then
echo "Skipping ${SERVICE_NAME} (has .ci-skip marker)"
SKIPPED_SERVICES+=("$SERVICE_NAME")
else
SERVICES+=("$SERVICE_NAME")
fi
fi
done < <(find services -name "docker-compose.yml" -type f | sort)
if [[ ${#SKIPPED_SERVICES[@]} -gt 0 ]]; then
echo ""
echo "=== Skipped ${#SKIPPED_SERVICES[@]} services with .ci-skip marker ==="
printf '%s\n' "${SKIPPED_SERVICES[@]}"
fi
# Filter for specific service if requested
if [[ -n "${{ github.event.inputs.specific_service }}" ]]; then
SPECIFIC="${{ github.event.inputs.specific_service }}"
if printf '%s\n' "${SERVICES[@]}" | grep -q "^${SPECIFIC}$"; then
SERVICES=("$SPECIFIC")
echo "Filtering to specific service: $SPECIFIC"
else
echo "ERROR: Service '$SPECIFIC' not found!"
echo "Available services: ${SERVICES[*]}"
exit 1
fi
fi
# Convert to JSON array
SERVICES_JSON=$(printf '%s\n' "${SERVICES[@]}" | jq -R . | jq -s -c .)
SERVICE_COUNT=${#SERVICES[@]}
echo "services=$SERVICES_JSON" >> $GITHUB_OUTPUT
echo "service_count=$SERVICE_COUNT" >> $GITHUB_OUTPUT
echo ""
echo "=== Discovered $SERVICE_COUNT services ==="
echo "$SERVICES_JSON" | jq -r '.[]'
- name: Validate compose file syntax
run: |
set -euo pipefail
echo "=== Validating Docker Compose syntax ==="
ERRORS=0
for SERVICE in $(echo '${{ steps.discover.outputs.services }}' | jq -r '.[]'); do
COMPOSE_FILE="services/${SERVICE}/docker-compose.yml"
echo -n "Validating ${SERVICE}... "
if docker compose -f "$COMPOSE_FILE" config > /dev/null 2>&1; then
echo "OK"
else
echo "FAILED"
echo "--- Error details for ${SERVICE} ---"
docker compose -f "$COMPOSE_FILE" config 2>&1 || true
echo "---"
ERRORS=$((ERRORS + 1))
fi
done
if [[ $ERRORS -gt 0 ]]; then
echo ""
echo "ERROR: $ERRORS compose file(s) have syntax errors!"
exit 1
fi
echo ""
echo "All compose files validated successfully!"
# ============================================================================
# Job 4: Extract All Docker Images
# ============================================================================
extract-images:
name: Extract Docker Images
runs-on: ubuntu-latest
needs: discover
outputs:
images: ${{ steps.extract.outputs.images }}
image_count: ${{ steps.extract.outputs.image_count }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Extract unique images from all compose files
id: extract
run: |
set -uo pipefail
echo "=== Extracting Docker images from compose files ==="
# Create temp file for all images
> /tmp/all_images.txt
for SERVICE in $(echo '${{ needs.discover.outputs.services }}' | jq -r '.[]'); do
COMPOSE_FILE="services/${SERVICE}/docker-compose.yml"
ENV_FILE="services/${SERVICE}/.env"
EXAMPLE_FILE="services/${SERVICE}/.env.example"
echo "Processing ${SERVICE}..."
# Load environment variables if they exist
# Disable nounset temporarily as env files may contain $ chars in values
# (e.g., bcrypt hashes like $2y$10$...)
set +u
if [[ -f "$ENV_FILE" ]]; then
set -a
source "$ENV_FILE" 2>/dev/null || true
set +a
fi
# Also load example env for any missing vars
if [[ -f "$EXAMPLE_FILE" ]]; then
set -a
source "$EXAMPLE_FILE" 2>/dev/null || true
set +a
fi
set -u
# Extract images using docker compose config
# Use sed to trim leading/trailing whitespace from image names
IMAGES=$(docker compose -f "$COMPOSE_FILE" config 2>/dev/null | \
grep -E '^\s*image:' | \
sed 's/.*image://' | \
sed 's/^[[:space:]]*//' | \
sed 's/[[:space:]]*$//' | \
tr -d '"' || true)
if [[ -n "$IMAGES" ]]; then
echo "$IMAGES" >> /tmp/all_images.txt
fi
done
# Get unique images, remove empty lines, and trim any remaining whitespace
UNIQUE_IMAGES=$(cat /tmp/all_images.txt | sed 's/^[[:space:]]*//' | sed 's/[[:space:]]*$//' | sort -u | grep -v '^$' || true)
IMAGE_COUNT=$(echo "$UNIQUE_IMAGES" | grep -c . || echo "0")
# Convert to JSON array
IMAGES_JSON=$(echo "$UNIQUE_IMAGES" | jq -R . | jq -s -c .)
echo "images=$IMAGES_JSON" >> $GITHUB_OUTPUT
echo "image_count=$IMAGE_COUNT" >> $GITHUB_OUTPUT
echo ""
echo "=== Found $IMAGE_COUNT unique Docker images ==="
echo "$UNIQUE_IMAGES"
# ============================================================================
# Job 5: CVE Vulnerability Scanning (Parallel)
# ============================================================================
# Images are scanned in parallel using matrix strategy for faster pipeline execution.
# Each image runs in its own job, and results are aggregated in cve-scan-summary.
cve-scan:
name: CVE Scan - ${{ matrix.image }}
runs-on: ubuntu-latest
needs: extract-images
if: ${{ github.event.inputs.skip_cve_scan != 'true' && needs.extract-images.outputs.image_count != '0' }}
strategy:
fail-fast: false
max-parallel: 10
matrix:
image: ${{ fromJson(needs.extract-images.outputs.images) }}
steps:
- name: Install Trivy
uses: aquasecurity/trivy-action@master
with:
scan-type: 'image'
image-ref: ${{ matrix.image }}
format: 'json'
output: 'trivy-results.json'
severity: 'CRITICAL,HIGH,MEDIUM,LOW'
timeout: '10m'
continue-on-error: true
- name: Parse scan results
id: parse
run: |
set -uo pipefail
IMAGE="${{ matrix.image }}"
SAFE_NAME=$(echo "$IMAGE" | tr '/:' '__')
echo "=== Scan results for: $IMAGE ==="
if [[ -f trivy-results.json ]] && [[ -s trivy-results.json ]]; then
# Parse vulnerability counts
CRITICAL=$(jq '[.Results[]?.Vulnerabilities[]? | select(.Severity=="CRITICAL")] | length' trivy-results.json 2>/dev/null || echo 0)
HIGH=$(jq '[.Results[]?.Vulnerabilities[]? | select(.Severity=="HIGH")] | length' trivy-results.json 2>/dev/null || echo 0)
MEDIUM=$(jq '[.Results[]?.Vulnerabilities[]? | select(.Severity=="MEDIUM")] | length' trivy-results.json 2>/dev/null || echo 0)
LOW=$(jq '[.Results[]?.Vulnerabilities[]? | select(.Severity=="LOW")] | length' trivy-results.json 2>/dev/null || echo 0)
# Determine status
if [[ $CRITICAL -gt 0 ]]; then
STATUS="CRITICAL"
elif [[ $HIGH -gt 0 ]]; then
STATUS="HIGH"
else
STATUS="PASS"
fi
echo "Critical: $CRITICAL, High: $HIGH, Medium: $MEDIUM, Low: $LOW"
echo "Status: $STATUS"
# Export results
echo "critical=$CRITICAL" >> $GITHUB_OUTPUT
echo "high=$HIGH" >> $GITHUB_OUTPUT
echo "medium=$MEDIUM" >> $GITHUB_OUTPUT
echo "low=$LOW" >> $GITHUB_OUTPUT
echo "status=$STATUS" >> $GITHUB_OUTPUT
echo "scanned=true" >> $GITHUB_OUTPUT
# Rename for artifact upload
mv trivy-results.json "${SAFE_NAME}.json"
else
echo "WARNING: Scan failed or produced no results"
echo "critical=0" >> $GITHUB_OUTPUT
echo "high=0" >> $GITHUB_OUTPUT
echo "medium=0" >> $GITHUB_OUTPUT
echo "low=0" >> $GITHUB_OUTPUT
echo "status=SKIPPED" >> $GITHUB_OUTPUT
echo "scanned=false" >> $GITHUB_OUTPUT
# Create empty result file
echo '{"skipped": true, "image": "${{ matrix.image }}"}' > "${SAFE_NAME}.json"
fi
echo "safe_name=${SAFE_NAME}" >> $GITHUB_OUTPUT
- name: Upload individual scan result
uses: actions/upload-artifact@v7
with:
name: cve-scan-${{ steps.parse.outputs.safe_name }}
path: ${{ steps.parse.outputs.safe_name }}.json
retention-days: 30
# ============================================================================
# Job 5b: Aggregate CVE Scan Results
# ============================================================================
cve-scan-summary:
name: CVE Scan Summary
runs-on: ubuntu-latest
needs: [extract-images, cve-scan]
if: ${{ always() && needs.extract-images.result == 'success' && github.event.inputs.skip_cve_scan != 'true' }}
outputs:
critical_count: ${{ steps.summarize.outputs.critical_count }}
high_count: ${{ steps.summarize.outputs.high_count }}
scan_passed: ${{ steps.summarize.outputs.scan_passed }}
steps:
- name: Download all scan artifacts
uses: actions/download-artifact@v8
with:
pattern: cve-scan-*
path: scan-results/
merge-multiple: true
- name: Aggregate results
id: summarize
run: |
set -uo pipefail
echo "=== Aggregating CVE scan results ==="
TOTAL_CRITICAL=0
TOTAL_HIGH=0
TOTAL_MEDIUM=0
TOTAL_LOW=0
SCANNED=0
SKIPPED=0
# Create summary file
echo "# CVE Scan Results" > summary.md
echo "" >> summary.md
echo "| Image | Critical | High | Medium | Low | Status |" >> summary.md
echo "|-------|----------|------|--------|-----|--------|" >> summary.md
# Process each result file
for RESULT_FILE in scan-results/*.json; do
if [[ ! -f "$RESULT_FILE" ]]; then
continue
fi
# Extract image name from filename
FILENAME=$(basename "$RESULT_FILE" .json)
IMAGE_NAME=$(echo "$FILENAME" | tr '__' ':/')
# Check if skipped
if jq -e '.skipped' "$RESULT_FILE" > /dev/null 2>&1; then
echo "| \`$IMAGE_NAME\` | - | - | - | - | SKIPPED |" >> summary.md
SKIPPED=$((SKIPPED + 1))
continue
fi
# Parse counts
CRITICAL=$(jq '[.Results[]?.Vulnerabilities[]? | select(.Severity=="CRITICAL")] | length' "$RESULT_FILE" 2>/dev/null || echo 0)
HIGH=$(jq '[.Results[]?.Vulnerabilities[]? | select(.Severity=="HIGH")] | length' "$RESULT_FILE" 2>/dev/null || echo 0)
MEDIUM=$(jq '[.Results[]?.Vulnerabilities[]? | select(.Severity=="MEDIUM")] | length' "$RESULT_FILE" 2>/dev/null || echo 0)
LOW=$(jq '[.Results[]?.Vulnerabilities[]? | select(.Severity=="LOW")] | length' "$RESULT_FILE" 2>/dev/null || echo 0)
# Update totals
TOTAL_CRITICAL=$((TOTAL_CRITICAL + CRITICAL))
TOTAL_HIGH=$((TOTAL_HIGH + HIGH))
TOTAL_MEDIUM=$((TOTAL_MEDIUM + MEDIUM))
TOTAL_LOW=$((TOTAL_LOW + LOW))
SCANNED=$((SCANNED + 1))
# Determine status
if [[ $CRITICAL -gt 0 ]]; then
STATUS="CRITICAL"
elif [[ $HIGH -gt 0 ]]; then
STATUS="HIGH"
else
STATUS="PASS"
fi
echo "| \`$IMAGE_NAME\` | $CRITICAL | $HIGH | $MEDIUM | $LOW | $STATUS |" >> summary.md
done
IMAGE_COUNT=${{ needs.extract-images.outputs.image_count }}
# Write totals to summary
echo "" >> summary.md
echo "## Summary" >> summary.md
echo "" >> summary.md
echo "- **Images Scanned:** $SCANNED / $IMAGE_COUNT" >> summary.md
echo "- **Images Skipped:** $SKIPPED" >> summary.md
echo "- **Total Critical:** $TOTAL_CRITICAL" >> summary.md
echo "- **Total High:** $TOTAL_HIGH" >> summary.md
echo "- **Total Medium:** $TOTAL_MEDIUM" >> summary.md
echo "- **Total Low:** $TOTAL_LOW" >> summary.md
echo ""
echo "=== CVE Scan Complete ==="
cat summary.md
# Export results
echo "critical_count=$TOTAL_CRITICAL" >> $GITHUB_OUTPUT
echo "high_count=$TOTAL_HIGH" >> $GITHUB_OUTPUT
# Report vulnerabilities but don't fail the pipeline
if [[ $TOTAL_CRITICAL -gt 0 ]]; then
echo "::warning::Found $TOTAL_CRITICAL CRITICAL vulnerabilities - see CVE scan report for details"
fi
if [[ $TOTAL_HIGH -gt 0 ]]; then
echo "::warning::Found $TOTAL_HIGH HIGH vulnerabilities - see CVE scan report for details"
fi
# Always pass - CVE scan is for reporting only
echo "scan_passed=true" >> $GITHUB_OUTPUT
echo ""
echo "CVE scan completed - report generated (non-blocking)"
- name: Upload aggregated results
uses: actions/upload-artifact@v7
with:
name: cve-scan-results
path: |
summary.md
scan-results/
retention-days: 30
- name: Add CVE summary to GitHub Actions
run: |
echo "## CVE Vulnerability Scan Results" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
cat summary.md >> $GITHUB_STEP_SUMMARY
# ============================================================================
# Job 6: Parallel Docker Compose Testing
# ============================================================================
# Services are tested in parallel using matrix strategy for faster pipeline execution.
# Each service runs in its own isolated job with unique project naming to prevent conflicts.
test-services:
name: Test - ${{ matrix.service }}
runs-on: ubuntu-latest
needs: [discover, cve-scan-summary]
# Run even if CVE scan is skipped, but not if it failed
if: ${{ always() && needs.discover.result == 'success' && (needs.cve-scan-summary.result == 'success' || needs.cve-scan-summary.result == 'skipped') }}
strategy:
fail-fast: false
max-parallel: 8
matrix:
service: ${{ fromJson(needs.discover.outputs.services) }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Test service
id: test
run: |
set -uo pipefail
SERVICE="${{ matrix.service }}"
SERVICE_DIR="services/${SERVICE}"
COMPOSE_FILE="${SERVICE_DIR}/docker-compose.yml"
# Use unique project name to isolate parallel tests
PROJECT_NAME="test-${SERVICE}-${{ github.run_id }}"
echo "=== Testing: $SERVICE ==="
echo "Project: $PROJECT_NAME"
# Create results directory
mkdir -p test-results
TEST_START=$(date +%s)
TEST_STATUS="PASSED"
TEST_DETAILS=""
# Load environment variables
set +u
if [[ -f "${SERVICE_DIR}/.env" ]]; then
set -a
source "${SERVICE_DIR}/.env" 2>/dev/null || true
set +a
fi
if [[ -f "${SERVICE_DIR}/.env.example" ]]; then
set -a
source "${SERVICE_DIR}/.env.example" 2>/dev/null || true
set +a
fi
set -u
# Set test-specific environment variables
export SERVICE_DOMAIN="${SERVICE}.test.local"
# Create isolated traefik network for this test
# Using project-specific name to avoid conflicts between parallel tests
TRAEFIK_NETWORK="${PROJECT_NAME}_traefik"
docker network create "$TRAEFIK_NETWORK" > /dev/null 2>&1 || true
# Also create the standard traefik_default network (some services expect it)
# Skip for traefik/traefik-tunnel services - they create their own network
if [[ "$SERVICE" != "traefik" && "$SERVICE" != "traefik-tunnel" ]]; then
docker network create traefik_default > /dev/null 2>&1 || true
fi
# Step 1: Pull images (quiet mode, suppress progress)
echo "Pulling images..."
if timeout 300 docker compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" pull --quiet 2>&1 | grep -v "Pulling\|Pull complete\|Already exists\|Waiting\|Downloading\|Extracting" || true; then
echo "Images ready"
else
echo "WARNING: Some images may have failed to pull"
fi
# Step 2: Start services (suppress verbose Creating/Started messages)
echo "Starting services..."
# Capture output and filter out the noisy status messages
UP_OUTPUT=$(timeout 120 docker compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" up -d --quiet-pull 2>&1) || UP_EXIT=$?
UP_EXIT=${UP_EXIT:-0}
# Only show errors or warnings, not the Creating/Created/Starting/Started noise
echo "$UP_OUTPUT" | grep -vE "Creating|Created|Starting|Started|Pulling|Pull complete" | grep -v "^$" || true
if [[ $UP_EXIT -eq 0 ]]; then
echo "Services started"
# Step 3: Wait for services to stabilize
sleep 10
# Step 4: Check container health
echo "Checking container status..."
CONTAINERS=$(docker compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" ps -q 2>/dev/null | wc -l)
RUNNING=$(docker compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" ps --status running -q 2>/dev/null | wc -l)
echo "Containers: $RUNNING running of $CONTAINERS defined"
if [[ "$RUNNING" -gt 0 ]]; then
# Show container status (compact format)
docker compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" ps --format "table {{.Name}}\t{{.Status}}"
# Check each container is running (not restarting)
HEALTHY=true
for CONTAINER in $(docker compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" ps -q 2>/dev/null); do
STATE=$(docker inspect --format='{{.State.Status}}' "$CONTAINER" 2>/dev/null || echo "unknown")
RESTARTS=$(docker inspect --format='{{.RestartCount}}' "$CONTAINER" 2>/dev/null || echo "0")
if [[ "$STATE" != "running" ]] || [[ "$RESTARTS" -gt 2 ]]; then
CONTAINER_NAME=$(docker inspect --format='{{.Name}}' "$CONTAINER" 2>/dev/null | sed 's/^\///')
echo "::warning::Container $CONTAINER_NAME - State: $STATE, Restarts: $RESTARTS"
HEALTHY=false
fi
done
if [[ "$HEALTHY" == "true" ]]; then
TEST_DETAILS="All containers running"
else
TEST_STATUS="FAILED"
TEST_DETAILS="Container health issues"
fi
else
TEST_STATUS="FAILED"
TEST_DETAILS="No containers running"
fi
else
TEST_STATUS="FAILED"
TEST_DETAILS="Failed to start services"
fi
# Calculate duration
TEST_END=$(date +%s)
TEST_DURATION=$((TEST_END - TEST_START))
echo ""
echo "Result: $TEST_STATUS (${TEST_DURATION}s) - $TEST_DETAILS"
# Capture logs for failed tests
if [[ "$TEST_STATUS" == "FAILED" ]]; then
echo "--- Container logs ---"