Khắc phục lỗi file môi trường với github webhook
Hiện tượng: Sau khi deploy tính năng mới website đã bị sập.
Nguyên nhân: Khi phát triển tính năng đã tải package mới với pip. Mặc dù mình đã thêm tên package mới vào file requirements.txt nhưng mình đã quên việc tải package trên env của server website.
Cách khắc phục: Dùng
github webhook. Khi dùng webhook github sẽ gửi request POST đến endpoint do mình đề ra. Mình sẽ dựa vào trường chứa các file bị chỉnh sửa trong commit. Nếu xuất hiện file môi trường trong đó, pull commit về và tự động tải package.
Ví dụ code pull github và tải package python với pip dùng framework django
from django.http import HttpResponse, HttpRequest
from django.views.decorators.csrf import csrf_exempt
import json
import subprocess
import os
@csrf_exempt
def github_view(request: HttpRequest):
data = json.loads(request.POST["payload"])
os.chdir("github_repo_path")
subprocess.run(["git", "pull"], check=True)
if "requirements.txt" in data["head_commit"]["modified"]:
command = [
'/opt/my_website_venv/bin/python3.9',
'-m',
'pip',
'install',
'-r',
'/opt/my_website/django_my_website/requirements.txt'
]
subprocess.run(command, check=True)
return HttpResponse(content="Success")
Fun fact: Trong thời gian mình làm việc tại công ty mình cũng đã chứng kiến lỗi trong lúc deploy code product. Và việc quản lý môi trường không tốt dẫn đến việc không thể deploy code trên server mới, gây ra khá nhiều vấn đề liên quan.
Ngày đăng: April 5, 2024

211 total views
Comment
Hiện tại chưa có comment nào...