Skip to content

Added Actions for EC2 Deployment #1

Added Actions for EC2 Deployment

Added Actions for EC2 Deployment #1

Workflow file for this run

name: ci-deploy-ec2
on:
push:
branches: [ gopi-dev ]
permissions:
id-token: write # required for OIDC
contents: read
env:
AWS_REGION: ${{ vars.AWS_REGION || 'us-east-1' }}
ECR_REPOSITORY: ${{ vars.ECR_REPOSITORY || 'careerforge' }}
EC2_INSTANCE_ID: ${{ vars.EC2_INSTANCE_ID }}
APP_PORT: "8080"
SERVICE_NAME: "careerforge"
jobs:
build-push-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK 21
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
cache: maven
- name: Unit tests
working-directory: code/backend
run: mvn -B -ntp test
- name: Configure AWS credentials (OIDC)
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_DEPLOY_ROLE_ARN }}
aws-region: ${{ env.AWS_REGION }}
- name: Ensure ECR repo exists
run: |
aws ecr describe-repositories --repository-names "${{ env.ECR_REPOSITORY }}" >/dev/null 2>&1 || \
aws ecr create-repository --repository-name "${{ env.ECR_REPOSITORY }}"
- name: Login to ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@v2
- name: Compute image tag
id: vars
run: |
echo "image=${{ steps.login-ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:${{ github.sha }}" >> $GITHUB_OUTPUT
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push image
uses: docker/build-push-action@v6
with:
context: code/backend
file: code/backend/Dockerfile
push: true
tags: ${{ steps.vars.outputs.image }}
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Deploy on EC2 via SSM
env:
IMAGE: ${{ steps.vars.outputs.image }}
run: |
set -euo pipefail
# SSM document executes a bash script on the instance to install Docker (if needed), login to ECR, pull, and run.
aws ssm send-command \
--instance-ids "$EC2_INSTANCE_ID" \
--document-name "AWS-RunShellScript" \
--comment "Deploy $SERVICE_NAME" \
--parameters 'commands=[
"set -euxo pipefail",
"sudo yum -y update || sudo dnf -y update || true",
"sudo yum -y install docker awscli || sudo dnf -y install docker awscli",
"sudo systemctl enable --now docker",
"ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)",
"REGION='${AWS_REGION}'",
"REGISTRY=${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com",
"aws ecr get-login-password --region ${REGION} | sudo docker login --username AWS --password-stdin ${REGISTRY}",
"sudo docker rm -f ${SERVICE_NAME} || true",
"sudo docker pull ${IMAGE}",
"sudo docker run -d --restart unless-stopped --name ${SERVICE_NAME} -p 80:${APP_PORT} ${IMAGE}",
"sudo docker image prune -f || true"
]' \
--output text