Merge pull request #78 from CareCode-Repo/hotfix/docker-base-image #34
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| name: CI/CD Pipeline - Blue/Green Deployment | |
| on: | |
| push: | |
| branches: [ main, develop ] | |
| pull_request: | |
| branches: [ main ] | |
| workflow_dispatch: | |
| inputs: | |
| environment: | |
| description: 'Deployment Environment' | |
| required: true | |
| default: 'staging' | |
| type: choice | |
| options: | |
| - staging | |
| - production | |
| env: | |
| REGISTRY: ghcr.io | |
| IMAGE_NAME: ${{ github.repository }} | |
| STAGING_HEALTH_URL: ${{ secrets.STAGING_HEALTH_URL }} | |
| PRODUCTION_HEALTH_URL: ${{ secrets.PRODUCTION_HEALTH_URL }} | |
| permissions: | |
| contents: read | |
| packages: write | |
| security-events: write | |
| concurrency: | |
| group: carecode-${{ github.ref }} | |
| cancel-in-progress: true | |
| jobs: | |
| # =========================================== | |
| # Test & Build Job | |
| # =========================================== | |
| test-and-build: | |
| name: Test and Build | |
| runs-on: ubuntu-latest | |
| steps: | |
| - name: Checkout code | |
| uses: actions/checkout@v4 | |
| # 이 잡은 SSH 를 사용하지 않는다. PR 트리거에서도 도는 잡에 | |
| # 배포용 개인키를 올리지 않도록 SSH 설정을 두지 않는다. | |
| - name: Validate Gradle wrapper | |
| uses: gradle/actions/wrapper-validation@v4 | |
| - name: Set up JDK 17 | |
| uses: actions/setup-java@v4 | |
| with: | |
| java-version: '17' | |
| distribution: 'temurin' | |
| - name: Cache Gradle packages | |
| uses: actions/cache@v4 | |
| with: | |
| path: | | |
| ~/.gradle/caches | |
| ~/.gradle/wrapper | |
| key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} | |
| restore-keys: | | |
| ${{ runner.os }}-gradle- | |
| - name: Run tests | |
| run: ./gradlew clean test jacocoTestReport | |
| # Testcontainers 테스트는 Docker 가 없으면 조용히 skip 되고 빌드는 초록불이 된다. | |
| # 스키마 정합성 검증이 그렇게 빠지면 마이그레이션 누락을 아무도 못 잡는다. | |
| - name: Assert schema validation actually ran | |
| run: | | |
| report=build/test-results/test/TEST-com.carecode.integration.FlywaySchemaValidationTest.xml | |
| if [ ! -f "$report" ]; then | |
| echo "::error::스키마 정합성 테스트 리포트가 없습니다." | |
| exit 1 | |
| fi | |
| if grep -q 'skipped="0"' "$report"; then | |
| echo "스키마 정합성 테스트 실행 확인" | |
| else | |
| echo "::error::스키마 정합성 테스트가 skip 되었습니다. Docker 환경을 확인하세요." | |
| exit 1 | |
| fi | |
| - name: Publish test report | |
| uses: mikepenz/action-junit-report@v5 | |
| if: always() | |
| with: | |
| report_paths: 'build/test-results/test/TEST-*.xml' | |
| # build 에서 -x test 로 테스트를 빼면 check 에 걸어둔 커버리지 검증까지 함께 무력화된다. | |
| # 위에서 이미 test 를 돌렸으므로 여기서는 검증을 포함해 그대로 build 한다. | |
| - name: Build application | |
| run: ./gradlew build | |
| - name: Upload build artifacts | |
| uses: actions/upload-artifact@v4 | |
| with: | |
| name: application-jar | |
| path: build/libs/*.jar | |
| retention-days: 7 | |
| # =========================================== | |
| # Security Scan Job | |
| # =========================================== | |
| security-scan: | |
| name: Security Scan | |
| runs-on: ubuntu-latest | |
| needs: test-and-build | |
| steps: | |
| - name: Checkout code | |
| uses: actions/checkout@v4 | |
| # 이 잡도 SSH 를 사용하지 않으므로 배포용 개인키를 로드하지 않는다. | |
| # 1) SARIF 리포트 생성 (Security 탭 업로드용) - 여기서는 실패시키지 않는다. | |
| - name: Run Trivy vulnerability scanner (report) | |
| uses: aquasecurity/trivy-action@v0.36.0 | |
| with: | |
| scan-type: 'fs' | |
| scan-ref: '.' | |
| format: 'sarif' | |
| output: 'trivy-results.sarif' | |
| - name: Upload Trivy scan results to GitHub Security tab | |
| uses: github/codeql-action/upload-sarif@v3 | |
| if: always() | |
| with: | |
| sarif_file: 'trivy-results.sarif' | |
| # 2) 게이트: CRITICAL/HIGH 취약점이 있으면 파이프라인을 실패시킨다. | |
| # exit-code 를 지정하지 않으면 취약점이 나와도 그냥 통과해 스캔이 장식이 된다. | |
| - name: Fail on CRITICAL/HIGH vulnerabilities | |
| uses: aquasecurity/trivy-action@v0.36.0 | |
| with: | |
| scan-type: 'fs' | |
| scan-ref: '.' | |
| format: 'table' | |
| severity: 'CRITICAL,HIGH' | |
| ignore-unfixed: true | |
| exit-code: '1' | |
| # =========================================== | |
| # Build Docker Image Job | |
| # =========================================== | |
| build-docker: | |
| name: Build Docker Image | |
| runs-on: ubuntu-latest | |
| needs: [test-and-build, security-scan] | |
| if: github.event_name == 'push' || github.event_name == 'workflow_dispatch' | |
| outputs: | |
| image-tag: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }} | |
| steps: | |
| - name: Checkout code | |
| uses: actions/checkout@v4 | |
| - name: Set up Docker Buildx | |
| uses: docker/setup-buildx-action@v3 | |
| - name: Log in to Container Registry | |
| uses: docker/login-action@v3 | |
| with: | |
| registry: ${{ env.REGISTRY }} | |
| username: ${{ github.actor }} | |
| password: ${{ secrets.GITHUB_TOKEN }} | |
| - name: Extract metadata | |
| id: meta | |
| uses: docker/metadata-action@v5 | |
| with: | |
| images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} | |
| tags: | | |
| type=ref,event=branch | |
| type=ref,event=pr | |
| type=sha,prefix={{branch}}- | |
| type=raw,value=latest,enable={{is_default_branch}} | |
| - name: Build and push Docker image | |
| uses: docker/build-push-action@v5 | |
| with: | |
| context: . | |
| push: true | |
| tags: ${{ steps.meta.outputs.tags }} | |
| labels: ${{ steps.meta.outputs.labels }} | |
| cache-from: type=gha | |
| cache-to: type=gha,mode=max | |
| # =========================================== | |
| # Deploy to Staging (Green) Job | |
| # =========================================== | |
| deploy-staging: | |
| name: Deploy to Staging (Green) | |
| runs-on: ubuntu-latest | |
| needs: build-docker | |
| if: github.ref == 'refs/heads/develop' || (github.event_name == 'workflow_dispatch' && github.event.inputs.environment == 'staging') | |
| environment: staging | |
| steps: | |
| - name: Checkout code | |
| uses: actions/checkout@v4 | |
| - name: Deploy to staging environment | |
| run: | | |
| test -n "${{ secrets.STAGING_DEPLOY_HOST }}" | |
| ssh -o StrictHostKeyChecking=no ${{ secrets.STAGING_DEPLOY_USER }}@${{ secrets.STAGING_DEPLOY_HOST }} \ | |
| "docker pull ${{ needs.build-docker.outputs.image-tag }} && docker stop carecode-staging || true && docker rm carecode-staging || true && docker run -d --name carecode-staging -p 8082:8082 --env-file /opt/carecode/.env ${{ needs.build-docker.outputs.image-tag }}" | |
| - name: Run health check | |
| run: | | |
| test -n "$STAGING_HEALTH_URL" | |
| for i in {1..20}; do | |
| if curl -fsS "$STAGING_HEALTH_URL/actuator/health" | grep -q '"status":"UP"'; then | |
| echo "Staging health check passed" | |
| exit 0 | |
| fi | |
| sleep 5 | |
| done | |
| echo "Staging health check failed" | |
| exit 1 | |
| - name: Notify deployment status | |
| if: always() | |
| run: | | |
| echo "Staging deployment completed" | |
| # 슬랙, 이메일 등 알림 추가 | |
| # =========================================== | |
| # Deploy to Production (Blue/Green) Job | |
| # =========================================== | |
| deploy-production: | |
| name: Deploy to Production (Blue/Green) | |
| runs-on: ubuntu-latest | |
| needs: build-docker | |
| if: github.ref == 'refs/heads/main' || (github.event_name == 'workflow_dispatch' && github.event.inputs.environment == 'production') | |
| environment: production | |
| steps: | |
| - name: Checkout code | |
| uses: actions/checkout@v4 | |
| # blue/green 두 컨테이너는 서로 다른 포트를 점유해야 한다. | |
| # 둘 다 8082 를 쓰면 동시에 뜰 수 없어 무중단 전환 자체가 성립하지 않는다. | |
| - name: Determine deployment strategy | |
| id: strategy | |
| run: | | |
| CURRENT_ENV=$(curl -fsS "${{ secrets.PRODUCTION_ROUTER_STATUS_URL }}" || echo "blue") | |
| if [ "$CURRENT_ENV" = "blue" ]; then | |
| echo "target-env=green" >> $GITHUB_OUTPUT | |
| echo "current-env=blue" >> $GITHUB_OUTPUT | |
| echo "target-port=8083" >> $GITHUB_OUTPUT | |
| else | |
| echo "target-env=blue" >> $GITHUB_OUTPUT | |
| echo "current-env=green" >> $GITHUB_OUTPUT | |
| echo "target-port=8082" >> $GITHUB_OUTPUT | |
| fi | |
| - name: Deploy to target environment | |
| run: | | |
| test -n "${{ secrets.PRODUCTION_DEPLOY_HOST }}" | |
| TARGET="${{ steps.strategy.outputs.target-env }}" | |
| PORT="${{ steps.strategy.outputs.target-port }}" | |
| ssh -o StrictHostKeyChecking=no ${{ secrets.PRODUCTION_DEPLOY_USER }}@${{ secrets.PRODUCTION_DEPLOY_HOST }} \ | |
| "docker pull ${{ needs.build-docker.outputs.image-tag }} \ | |
| && (docker stop carecode-$TARGET || true) \ | |
| && (docker rm carecode-$TARGET || true) \ | |
| && docker run -d --name carecode-$TARGET -p $PORT:8082 --env-file /opt/carecode/.env ${{ needs.build-docker.outputs.image-tag }}" | |
| # 전환 전에는 아직 라우팅되지 않는 대기(target) 인스턴스를 직접 확인해야 한다. | |
| # 공용 헬스 URL 을 보면 구버전이 UP 이라 항상 통과해버린다. | |
| - name: Wait for target instance to be ready | |
| run: | | |
| test -n "${{ secrets.PRODUCTION_TARGET_HEALTH_URL_TEMPLATE }}" | |
| PORT="${{ steps.strategy.outputs.target-port }}" | |
| TARGET_HEALTH_URL=$(echo "${{ secrets.PRODUCTION_TARGET_HEALTH_URL_TEMPLATE }}" | sed "s/{port}/$PORT/") | |
| for i in {1..20}; do | |
| if curl -fsS "$TARGET_HEALTH_URL/actuator/health" | grep -q '"status":"UP"'; then | |
| echo "Production target ($PORT) is healthy" | |
| exit 0 | |
| fi | |
| sleep 5 | |
| done | |
| echo "Production target health check failed" | |
| exit 1 | |
| - name: Switch traffic to new environment | |
| run: | | |
| test -n "${{ secrets.PRODUCTION_ROUTER_SWITCH_URL }}" | |
| curl -fsS -X POST "${{ secrets.PRODUCTION_ROUTER_SWITCH_URL }}" \ | |
| -H "Authorization: Bearer ${{ secrets.PRODUCTION_ROUTER_TOKEN }}" \ | |
| -H "Content-Type: application/json" \ | |
| -d "{\"target\":\"${{ steps.strategy.outputs.target-env }}\"}" | |
| - name: Verify deployment | |
| run: | | |
| curl -fsS "$PRODUCTION_HEALTH_URL/actuator/health" | grep -q '"status":"UP"' | |
| - name: Rollback if needed | |
| if: failure() | |
| run: | | |
| curl -fsS -X POST "${{ secrets.PRODUCTION_ROUTER_SWITCH_URL }}" \ | |
| -H "Authorization: Bearer ${{ secrets.PRODUCTION_ROUTER_TOKEN }}" \ | |
| -H "Content-Type: application/json" \ | |
| -d "{\"target\":\"${{ steps.strategy.outputs.current-env }}\"}" | |
| - name: Notify deployment status | |
| if: always() | |
| run: | | |
| echo "Production deployment completed" | |
| # 슬랙, 이메일 등 알림 추가 | |
| # =========================================== | |
| # Cleanup Job | |
| # =========================================== | |
| cleanup: | |
| name: Cleanup | |
| runs-on: ubuntu-latest | |
| needs: [deploy-staging, deploy-production] | |
| if: always() | |
| steps: | |
| - name: Cleanup old images | |
| run: | | |
| echo "Cleaning up old Docker images" | |
| # 오래된 Docker 이미지 정리 | |
| - name: Cleanup old deployments | |
| run: | | |
| echo "Cleaning up old deployments" | |
| # 오래된 배포 정리 |