📘
Github Actionsを使ってGithubからEC2までのDjangoのCICD環境構築(2023版)
概要
Github Actionsを使ってGithubからEC2までのDjangoのCICD環境を構築する機会があり、その備忘録です。
以下の記事を参考にさせていただきました。
上記の記事に対して、Github Actionsの設定を一部更新しました。
Github Actionsの設定
.github/workflows/deploy.yml
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 }}
変更した点として、actions/checkout
とactions/setup-python
のバージョンを変更しました。また、pip installの部分を変更し、pip install -r requirements.txt
にしました。
まとめ
上記により、GithubからEC2へのデプロイを実現できました。他の方の参考になりましたら幸いです。
Discussion