Overview

I had the opportunity to build a Django CI/CD environment from GitHub to EC2 using GitHub Actions, and here are my notes.

The following article was used as a reference.

https://qiita.com/fffukken/items/27b0bfa712940914d3f6

I made some updates to the GitHub Actions configuration compared to the above article.

GitHub Actions Configuration

name: Test and Deploy

on:
  push:
    branches: [ develop, main ]
  pull_request:
    branches: [ develop ]

jobs:
  build:

    runs-on: ubuntu-latest
    strategy:
      max-parallel: 4
      matrix:
        python-version: [3.9, "3.10"]

    steps:
    - uses: actions/checkout@v3
    - name: Set up Python ${{ matrix.python-version }}
      uses: actions/setup-python@v4
      with:
        python-version: ${{ matrix.python-version }}
    - name: Install Dependencies
      run: |
        python -m pip install --upgrade pip
        pip install -r requirements.txt
    - name: Run Tests
      run: |
        python manage.py makemigrations
        python manage.py migrate
        python manage.py test
    - name: deploy
      run: |
        echo "$SECRET_KEY" > secret_key
        chmod 600 secret_key
        ssh -oStrictHostKeyChecking=no ${EC2_USER}@${EC2_HOST} -i secret_key "source <仮想環境名>/bin/activate \
        && cd ~/<プロジェクト名>\
        && git pull origin main \
        && python manage.py makemigrations \
        && python manage.py migrate \
        && deactivate \
        && sudo systemctl restart gunicorn"
    env:
      SECRET_KEY: ${{ secrets.SECRET_KEY }}
      EC2_USER: ${{ secrets.EC2_USER }}
      EC2_HOST: ${{ secrets.EC2_HOST }}

The changes made were updating the versions of actions/checkout and actions/setup-python. I also changed the pip install section to pip install -r requirements.txt.

Summary

With the above configuration, I was able to achieve deployment from GitHub to EC2. I hope this serves as a useful reference for others.