name: Deploy to AWS ECS on: push: branches: - {{DEPLOY_BRANCH}} # Overlapping deploys race: each run registers its own revision and force- # deploys, so a stale run finishing last would silently regress production. # Superseded runs cancel instead — newest always wins. concurrency: group: deploy-${{ github.ref }} cancel-in-progress: true env: AWS_REGION: {{REGION}} ECR_REPOSITORY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-repo ECS_CLUSTER: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-cluster ECS_SERVICE: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-service ECS_TASK_FAMILY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-task ECS_WORKER_SERVICE: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-worker-service ECS_WORKER_TASK_FAMILY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-worker-task CF_COMMENT: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-cdn permissions: id-token: write contents: read jobs: deploy: name: Build & Deploy runs-on: ubuntu-latest timeout-minutes: 60 steps: - name: Checkout Code uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 # --- 1. IaC SECURITY SCAN --- - name: Scan Terraform for Misconfigurations uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 with: scan-type: 'fs' scan-ref: 'terraform/' scanners: 'vuln,secret,misconfig' format: 'table' exit-code: '0' # Informational only, will not break the build severity: 'CRITICAL,HIGH' output: 'trivy-iac-summary.txt' - name: Publish IaC Summary if: always() run: | if [ -f trivy-iac-summary.txt ]; then echo "### 🏗️ Terraform Misconfiguration Scan" >> $GITHUB_STEP_SUMMARY echo '```' >> $GITHUB_STEP_SUMMARY cat trivy-iac-summary.txt >> $GITHUB_STEP_SUMMARY echo '```' >> $GITHUB_STEP_SUMMARY fi # --- 2. AWS AUTH (job-level credentials for every step below) --- - name: Configure AWS credentials id: aws-creds uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4 continue-on-error: true with: role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{DEPLOY_ROLE_NAME}} aws-region: ${{ env.AWS_REGION }} # Deploy never skips: a failed assume fails the run with the # bootstrap pointer. - name: Interpret credential failure if: steps.aws-creds.outcome == 'failure' run: | echo "::error::AWS credential assumption failed — if the stack was never provisioned, bootstrap it first (npx grada-run apply); otherwise check terraform/oidc.tf trust." exit 1 # --- 3. ECR BOOTSTRAP --- # The image is pushed BEFORE the full apply (fresh stacks must never # start tasks on an unpushed tag), but the repository itself is # Terraform-managed — so it is bootstrapped with a targeted apply # first. Idempotent on existing stacks. - name: Setup Terraform uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd # v3 - name: Bootstrap ECR repository working-directory: ./terraform run: | terraform init -input=false terraform workspace select default terraform apply -target=aws_ecr_repository.app -auto-approve -input=false # --- 4. BUILD --- - name: Login to Amazon ECR id: login-ecr uses: aws-actions/amazon-ecr-login@03f1aad4c6c7ffd436567f42f9384779290529bd # v2 - name: Build Docker image id: build-image env: ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }} IMAGE_TAG: latest run: | SHA_TAG=${GITHUB_SHA::7} docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$SHA_TAG . docker tag $ECR_REGISTRY/$ECR_REPOSITORY:$SHA_TAG $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG # --- 5. CONTAINER SECURITY SCAN --- - name: Scan Container for Vulnerabilities (table summary) uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 with: image-ref: '${{ steps.login-ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:latest' format: 'table' output: 'trivy-container-summary.txt' exit-code: '0' # Informational only, will not break the build ignore-unfixed: true vuln-type: 'os,library' severity: 'CRITICAL,HIGH' - name: Publish Container Summary if: always() run: | if [ -f trivy-container-summary.txt ]; then echo "### 🛡️ Container Security Scan Results" >> $GITHUB_STEP_SUMMARY echo '```' >> $GITHUB_STEP_SUMMARY cat trivy-container-summary.txt >> $GITHUB_STEP_SUMMARY echo '```' >> $GITHUB_STEP_SUMMARY fi # --- 6. PUSH --- - name: Push image to Amazon ECR id: push env: ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }} IMAGE_TAG: latest run: | SHA_TAG=${GITHUB_SHA::7} docker push $ECR_REGISTRY/$ECR_REPOSITORY:$SHA_TAG docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG echo "image=$ECR_REGISTRY/$ECR_REPOSITORY:$SHA_TAG" >> $GITHUB_OUTPUT # --- 7. INFRASTRUCTURE SYNC (The New Marketplace Action) --- # Runs AFTER the push: by the time apply moves tasks onto `:latest`, # the tag exists. A gate failure below can therefore never strand # the service on an unpullable revision. - name: Apply Infrastructure Changes uses: grada-run/grada-action@12227808ae4caafaec1041319645586a1132fc57 # v1 with: aws-region: ${{ env.AWS_REGION }} role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{DEPLOY_ROLE_NAME}} terraform-dir: 'terraform' # --- 8. DEPLOY --- # Each code push registers a new task definition revision pinned to the # immutable SHA-tagged image, so `rollback` always has history to # return to (and `latest` is never overwritten in place as the deploy # artifact of record). - name: Register new task definition revision id: register-task-def run: | IMAGE_URI=${{ steps.login-ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:${GITHUB_SHA::7} TASK_DEF=$(aws ecs describe-task-definition \ --task-definition ${{ env.ECS_TASK_FAMILY }} \ --region ${{ env.AWS_REGION }} \ --query 'taskDefinition' \ --output json) NEW_TASK_DEF=$(echo "$TASK_DEF" | jq \ --arg IMAGE "$IMAGE_URI" \ '.containerDefinitions[0].image = $IMAGE | del(.taskDefinitionArn, .revision, .status, .requiresAttributes, .compatibilities, .registeredAt, .registeredBy, .deregisteredAt)') NEW_TASK_ARN=$(aws ecs register-task-definition \ --region ${{ env.AWS_REGION }} \ --cli-input-json "$NEW_TASK_DEF" \ --query 'taskDefinition.taskDefinitionArn' \ --output text) echo "task-arn=$NEW_TASK_ARN" >> $GITHUB_OUTPUT - name: Force ECS deployment run: | aws ecs update-service \ --cluster ${{ env.ECS_CLUSTER }} \ --service ${{ env.ECS_SERVICE }} \ --task-definition ${{ steps.register-task-def.outputs.task-arn }} \ --force-new-deployment \ --region ${{ env.AWS_REGION }} # update-service returns before the rollout finishes: wait for # stability, then verify PRIMARY actually runs the registered # revision — a circuit-breaker rollback re-stabilizes on the OLD # revision, which the wait alone would report green. - name: Wait for web rollout run: | aws ecs wait services-stable \ --cluster ${{ env.ECS_CLUSTER }} \ --services ${{ env.ECS_SERVICE }} \ --region ${{ env.AWS_REGION }} PRIMARY_TD=$(aws ecs describe-services \ --cluster ${{ env.ECS_CLUSTER }} \ --services ${{ env.ECS_SERVICE }} \ --query 'services[0].deployments[?status==`PRIMARY`].taskDefinition' \ --output text \ --region ${{ env.AWS_REGION }}) if [ "$PRIMARY_TD" != "${{ steps.register-task-def.outputs.task-arn }}" ]; then echo "Web rollout of ${{ steps.register-task-def.outputs.task-arn }} did not stick (PRIMARY runs $PRIMARY_TD) — the deployment failed or rolled back." >&2 exit 1 fi # The background worker ships the same image as web, so it gets the # same SHA-pinned revision treatment — otherwise it would run stale # code forever while web moves on. Skipped on workerless projects. - name: Register worker task definition revision if: hashFiles('terraform/worker.tf') != '' id: register-worker-task-def run: | IMAGE_URI=${{ steps.login-ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:${GITHUB_SHA::7} TASK_DEF=$(aws ecs describe-task-definition \ --task-definition ${{ env.ECS_WORKER_TASK_FAMILY }} \ --region ${{ env.AWS_REGION }} \ --query 'taskDefinition' \ --output json) NEW_TASK_DEF=$(echo "$TASK_DEF" | jq \ --arg IMAGE "$IMAGE_URI" \ '.containerDefinitions[0].image = $IMAGE | del(.taskDefinitionArn, .revision, .status, .requiresAttributes, .compatibilities, .registeredAt, .registeredBy, .deregisteredAt)') NEW_TASK_ARN=$(aws ecs register-task-definition \ --region ${{ env.AWS_REGION }} \ --cli-input-json "$NEW_TASK_DEF" \ --query 'taskDefinition.taskDefinitionArn' \ --output text) echo "task-arn=$NEW_TASK_ARN" >> $GITHUB_OUTPUT - name: Force worker deployment if: hashFiles('terraform/worker.tf') != '' run: | aws ecs update-service \ --cluster ${{ env.ECS_CLUSTER }} \ --service ${{ env.ECS_WORKER_SERVICE }} \ --task-definition ${{ steps.register-worker-task-def.outputs.task-arn }} \ --force-new-deployment \ --region ${{ env.AWS_REGION }} - name: Wait for worker rollout if: hashFiles('terraform/worker.tf') != '' run: | aws ecs wait services-stable \ --cluster ${{ env.ECS_CLUSTER }} \ --services ${{ env.ECS_WORKER_SERVICE }} \ --region ${{ env.AWS_REGION }} PRIMARY_TD=$(aws ecs describe-services \ --cluster ${{ env.ECS_CLUSTER }} \ --services ${{ env.ECS_WORKER_SERVICE }} \ --query 'services[0].deployments[?status==`PRIMARY`].taskDefinition' \ --output text \ --region ${{ env.AWS_REGION }}) if [ "$PRIMARY_TD" != "${{ steps.register-worker-task-def.outputs.task-arn }}" ]; then echo "Worker rollout of ${{ steps.register-worker-task-def.outputs.task-arn }} did not stick (PRIMARY runs $PRIMARY_TD) — the deployment failed or rolled back." >&2 exit 1 fi # --- 9. CACHE INVALIDATION --- # New code means new HTML: clear the CDN so deploys go live # immediately instead of serving stale pages until TTL expiry. - name: Invalidate CloudFront run: | DIST_ID=$(aws cloudfront list-distributions \ --query "DistributionList.Items[?Comment=='${{ env.CF_COMMENT }}'].Id | [0]" \ --output text \ --region ${{ env.AWS_REGION }}) if [ -z "$DIST_ID" ] || [ "$DIST_ID" = "None" ]; then echo "CloudFront distribution '${{ env.CF_COMMENT }}' not found." >&2 exit 1 fi aws cloudfront create-invalidation \ --distribution-id "$DIST_ID" \ --paths "/*" \ --region ${{ env.AWS_REGION }} # A cancelled apply/destroy can strand the S3 state lockfile: point # at recovery instead of leaving the next run to fail obscurely #. Generic by necessity — the lock ID only exists in the # follow-up run's own error. - name: Cancellation recovery note if: cancelled() run: | echo "::warning::This run was cancelled while Terraform may have held the state lock. If the next run fails with 'Error acquiring the state lock', run terraform force-unlock (the ID is printed in that error) inside ./terraform — or delete the .tflock object beside the state file in S3 — then re-run."