Skip to content

cd test

cd test #7

Workflow file for this run

name: backend CI/CD
on:
push:
branches: [ main ]
paths:
- 'backend/**'
pull_request:
branches: [ main ]
paths:
- 'backend/**'
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:15
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: test_db
ports:
- 5432:5432
options: >-
--health-cmd="pg_isready -U postgres"
--health-interval=10s
--health-timeout=5s
--health-retries=5
env:
# Django environment variables for test
DJANGO_SETTINGS_MODULE: backend.settings # update if different
DATABASE_URL: postgres://postgres:postgres@localhost:5432/test_db
SECRET_KEY: test-secret
DEBUG: "0"
TESTING: "true" # Flag to indicate we're in test environment
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install dependencies
working-directory: backend
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Wait for Postgres
run: |
until pg_isready -h localhost -p 5432 -U postgres; do
echo "Waiting for Postgres..."
sleep 2
done
- name: Run migrations
working-directory: backend
run: |
python manage.py migrate
- name: Run tests
working-directory: backend
run: |
python manage.py test --noinput
deploy:
runs-on: ubuntu-latest
needs: test
if: github.ref == 'refs/heads/main'
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Install SSH Client
run: sudo apt-get install -y openssh-client
- name: Setup SSH Key
run: |
mkdir -p ~/.ssh
echo "${{ secrets.EC2_KEY }}" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
- name: Deploy to EC2
run: |
ssh -o StrictHostKeyChecking=no ${{ secrets.EC2_USER }}@${{ secrets.EC2_HOST }} "\
export AWS_REGION=${{ secrets.AWS_REGION }} && \
export ECR_REPO=${{ secrets.ECR_REPO }} && \
aws ecr get-login-password --region \$AWS_REGION | docker login --username AWS --password-stdin \$ECR_REPO && \
docker pull \$ECR_REPO:latest && \
docker stop stocksense || true && docker rm stocksense || true && \
docker run -d -p 8000:8000 --name stocksense \$ECR_REPO:latest"