Dev #16
This file contains 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: Frontend CI/CD | |
on: | |
push: | |
branches: | |
- main | |
pull_request_target: | |
branches: | |
- main | |
jobs: | |
build-and-push: | |
runs-on: ubuntu-latest | |
steps: | |
- name: Checkout Repository | |
uses: actions/checkout@v3 | |
- name: Build Docker Image | |
run: | | |
docker build -t ${{ secrets.DOCKERHUB_USERNAME }}/ustock-frontend:${{ github.sha }} . | |
- name: Login to Docker Hub | |
uses: docker/login-action@v3 | |
with: | |
username: ${{ secrets.DOCKERHUB_USERNAME }} | |
password: ${{ secrets.DOCKERHUB_TOKEN }} | |
- name: Push Docker Image | |
run: | | |
docker push ${{ secrets.DOCKERHUB_USERNAME }}/ustock-frontend:${{ github.sha }} | |
deploy-to-ec2: | |
runs-on: ubuntu-latest | |
needs: build-and-push | |
steps: | |
- name: Get Public IP | |
id: ip | |
uses: haythem/[email protected] | |
- name: Allow SSH access from GitHub Actions | |
run: | | |
aws ec2 authorize-security-group-ingress --group-id ${{ secrets.AWS_SG_ID }} --protocol tcp --port 22 --cidr ${{ steps.ip.outputs.ipv4 }}/32 | |
env: | |
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} | |
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} | |
AWS_REGION: ${{ secrets.AWS_REGION }} | |
- name: Add SSH key | |
run: | | |
mkdir -p ~/.ssh | |
echo "${{ secrets.EC2_SSH_KEY }}" > ~/.ssh/id_rsa | |
chmod 600 ~/.ssh/id_rsa | |
- name: Deploy to EC2 via SSH | |
run: | | |
ssh -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no ${{ secrets.EC2_USER }}@${{ secrets.EC2_HOST }} << 'EOF' | |
docker pull ${{ secrets.DOCKERHUB_USERNAME }}/ustock-frontend:${{ github.sha }} | |
docker stop ustock-frontend || true | |
docker rm ustock-frontend || true | |
docker run -dp 80:80 --network ustock-network --name ustock-frontend ${{ secrets.DOCKERHUB_USERNAME }}/ustock-frontend:${{ github.sha }} | |
EOF | |
- name: Revoke SSH access from GitHub Actions | |
run: | | |
aws ec2 revoke-security-group-ingress --group-id ${{ secrets.AWS_SG_ID }} --protocol tcp --port 22 --cidr ${{ steps.ip.outputs.ipv4 }}/32 | |
env: | |
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} | |
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} | |
AWS_REGION: ${{ secrets.AWS_REGION }} |