settings: AWS EC2 CI/CD 구성 Actions 수정 #27 #5
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: Deploy to AWS EC2 | |
on: | |
push: | |
branches: | |
- main # main 브랜치에 push할 때 실행 | |
jobs: | |
deploy: | |
runs-on: ubuntu-latest | |
defaults: | |
run: | |
shell: bash | |
steps: | |
# 1. 리포지토리 체크아웃 | |
- name: Checkout repository | |
uses: actions/checkout@v3 | |
# 2. Node.js 설치 및 설정 | |
- name: Setup Node.js | |
uses: actions/setup-node@v3 | |
with: | |
node-version: '18' | |
# 3. 프로젝트 빌드 | |
- name: Install dependencies and build | |
env: | |
VITE_API_URL: ${{ secrets.VITE_API_URL }} | |
run: | | |
# Vite용 .env 파일 생성 | |
echo "VITE_API_URL=${{ secrets.VITE_API_URL }}" > .env | |
# 의존성 설치 및 빌드 | |
npm ci | |
npm run build | |
# 4. EC2 서버로 배포 | |
- name: Deploy to EC2 | |
env: | |
SSH_PRIVATE_KEY: ${{ secrets.EC2_SSH_KEY }} | |
USER: ${{ secrets.EC2_USER }} | |
HOST: ${{ secrets.EC2_HOST }} | |
DEPLOY_PATH: ${{ secrets.EC2_PATH }} | |
run: | | |
# SSH 키 설정 | |
mkdir -p ~/.ssh | |
echo "$SSH_PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa | |
chmod 600 ~/.ssh/id_rsa | |
# 임시 디렉토리 생성 및 빌드 파일 업로드 | |
ssh -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa $USER@$HOST "mkdir -p $DEPLOY_PATH-temp" | |
scp -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa -r dist/* $USER@$HOST:$DEPLOY_PATH-temp | |
# 기존 폴더 백업 및 교체 | |
ssh -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa $USER@$HOST " | |
mv $DEPLOY_PATH $DEPLOY_PATH-backup-$(date +%Y%m%d%H%M%S) || true && | |
mv $DEPLOY_PATH-temp $DEPLOY_PATH | |
" | |
# 파일 권한 설정 | |
ssh -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa $USER@$HOST "sudo chown -R nginx:nginx $DEPLOY_PATH" | |
# 오래된 백업 삭제 | |
ssh -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa $USER@$HOST " | |
find $DEPLOY_PATH-backup-* -type d -mtime +7 -exec rm -rf {} + | |
" |