Skip to content

fix

fix #3

Workflow file for this run

name: Deploy API to AWS
on:
pull_request:
branches:
- master
types:
- closed
jobs:
deploy-api:
if: github.event.pull_request.merged
runs-on: ubuntu-latest
env:
CODE_BUCKET: ${{vars.CODE_BUCKET}}
REGION: ${{ vars.AWS_REGION }}
EC2_INSTANCE_ID: ${{ vars.EC2_INSTANCE_ID }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Cache api files
id: cache-api
uses: actions/cache@v4
env:
cache-name: cache-api-files
with:
path: .
key: ${{ hashFiles('package*.json') }}-${{ hashFiles('src/**/*') }}
- if: ${{ steps.cache-api.outputs.cache-hit == 'true' }}
name: Check api changes
continue-on-error: true
run: echo 'No api changes found. Skip api build and deployment.'
- if: ${{ steps.cache-api.outputs.cache-hit != 'true' }}
name: Build
run: |
npm ci
npm run build
- if: ${{ steps.cache-api.outputs.cache-hit != 'true' }}
name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v4
with:
aws-access-key-id: ${{secrets.AWS_ACCESS_KEY_ID}}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{vars.AWS_REGION}}
- if: ${{ steps.cache-api.outputs.cache-hit != 'true' }}
name: Zip application
run: zip -r app.zip . -x ".git/*" ".github/*" "infra/" "docker/" "test/"
- if: ${{ steps.cache-api.outputs.cache-hit != 'true' }}
name: Upload to S3
run: |
FILE_NAME="app-${{ github.sha }}.zip"
aws s3 cp app.zip s3://$CODE_BUCKET/$FILE_NAME
echo "FILE_NAME=$FILE_NAME" >> $GITHUB_ENV
- if: ${{ steps.cache-api.outputs.cache-hit != 'true' }}
name: Update EC2 from S3 and restart docker-compose
run: |
# Send SSM command to sync code, rebuild, restart, and run migrations
aws ssm send-command \
--document-name "AWS-RunShellScript" \
--targets "Key=instanceids,Values=$EC2_INSTANCE_ID" \
--comment "Deploy $GITHUB_SHA" \
--parameters commands='[
"set -e",
"cd /var/www/app",
"aws s3 cp s3://'"$CODE_BUCKET"'/'"$FILE_NAME"' app.zip --region '"$REGION"'",
"unzip -o app.zip,
"chown -R ec2-user:ec2-user /var/www/app",
"sudo -u ec2-user /usr/local/bin/docker-compose up -d --build",
"sleep 15",
"sudo -u ec2-user /usr/local/bin/docker-compose exec -T api npm run migration:run"
]' /
--region "$REGION" \
--query "Command.CommandId" \
--output text > command_id.txt
COMMAND_ID=$(cat command_id.txt)
echo "SSM CommandId: $COMMAND_ID"
# Optionally wait for completion
aws ssm wait command-executed \
--command-id "$COMMAND_ID" \
--instance-id "$EC2_INSTANCE_ID" \
--region "$REGION"
# Fetch and print last 100 lines of output for visibility
aws ssm list-command-invocations \
--command-id "$COMMAND_ID" \
--details --region "$REGION" \
--query "CommandInvocations[0].CommandPlugins[0].Output" \
--output text | tail -n 100 || true