| 1 | # CI/CD Pipeline — acme-corp/backend-api |
| 2 | # Runs on push to main and all pull_request events targeting main. |
| 3 | |
| 4 | name: CI / CD Pipeline |
| 5 | |
| 6 | on: |
| 7 | push: |
| 8 | branches: [main] |
| 9 | pull_request: |
| 10 | branches: [main] |
| 11 | |
| 12 | permissions: |
| 13 | id-token: write # Required for OIDC |
| 14 | contents: read |
| 15 | |
| 16 | env: |
| 17 | AWS_REGION: us-east-1 |
| 18 | ECR_REGISTRY: 123456789012.dkr.ecr.us-east-1.amazonaws.com |
| 19 | IMAGE_NAME: backend-api |
| 20 | |
| 21 | jobs: |
| 22 | |
| 23 | # ─── Job 1: Test ─────────────────────────────────────────── |
| 24 | test: |
| 25 | runs-on: ubuntu-latest |
| 26 | steps: |
| 27 | - uses: actions/checkout@v4 |
| 28 | - uses: actions/setup-python@v5 |
| 29 | with: |
| 30 | python-version: '3.11' |
| 31 | - name: Install dependencies |
| 32 | run: | |
| 33 | pip install -r requirements.txt |
| 34 | pip install pytest pytest-cov |
| 35 | - name: Run tests |
| 36 | run: pytest tests/ --cov=app --cov-report=xml |
| 37 | - uses: codecov/codecov-action@v4 |
| 38 | with: |
| 39 | token: ${{ secrets.CODECOV_TOKEN }} |
| 40 | |
| 41 | # ─── Job 2: Build & Push ───────────────────────────────── |
| 42 | build-and-push: |
| 43 | needs: test |
| 44 | runs-on: ubuntu-latest |
| 45 | if: github.ref == 'refs/heads/main' |
| 46 | steps: |
| 47 | - uses: actions/checkout@v4 |
| 48 | - name: Configure AWS credentials (OIDC) |
| 49 | uses: aws-actions/configure-aws-credentials@v4 |
| 50 | with: |
| 51 | role-to-assume: ${{ secrets.AWS_DEPLOY_ROLE_ARN }} |
| 52 | aws-region: ${{ env.AWS_REGION }} |
| 53 | - name: Login to Amazon ECR |
| 54 | id: login-ecr |
| 55 | uses: aws-actions/amazon-ecr-login@v2 |
| 56 | - name: Build, tag, and push image to ECR |
| 57 | env: |
| 58 | ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }} |
| 59 | IMAGE_TAG: ${{ github.sha }} |
| 60 | run: | |
| 61 | docker build -t $ECR_REGISTRY/$IMAGE_NAME:$IMAGE_TAG . |
| 62 | docker push $ECR_REGISTRY/$IMAGE_NAME:$IMAGE_TAG |
| 63 | docker tag $ECR_REGISTRY/$IMAGE_NAME:$IMAGE_TAG \ |
| 64 | $ECR_REGISTRY/$IMAGE_NAME:latest |
| 65 | docker push $ECR_REGISTRY/$IMAGE_NAME:latest |
| 66 | |
| 67 | # ─── Job 3: Deploy ──────────────────────────────────────── |
| 68 | deploy: |
| 69 | needs: build-and-push |
| 70 | runs-on: ubuntu-latest |
| 71 | environment: production |
| 72 | steps: |
| 73 | - uses: actions/checkout@v4 |
| 74 | - name: Deploy to ECS |
| 75 | run: | |
| 76 | aws ecs update-service \ |
| 77 | --cluster prod-cluster \ |
| 78 | --service backend-api-svc \ |
| 79 | --force-new-deployment |