Skip to content

Commit 6109e4e

Browse files
committed
1
1 parent 2ecc3de commit 6109e4e

File tree

1 file changed

+280
-0
lines changed

1 file changed

+280
-0
lines changed

.github/workflows/deploy.yml

Lines changed: 280 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,280 @@
1+
name: deploy.yml
2+
3+
env:
4+
IMAGE_REPOSITORY: team11 # GHCR 이미지 리포지토리명(소유자 포함 X)
5+
CONTAINER_1_NAME: team11_1 # 슬롯1(고정 이름)
6+
CONTAINER_PORT: 8080 # 컨테이너 내부 포트(스프링부트)
7+
EC2_INSTANCE_TAG_NAME: team11-terra-ec2-1 # 배포 대상 EC2 Name 태그
8+
DOCKER_NETWORK: common # 도커 네트워크
9+
BACKEND_DIR: . # Dockerfile 위치
10+
11+
concurrency:
12+
group: ${{ github.workflow }}-${{ github.ref }} # 커밋이 짧은 시간안에 몰려도 최신 커밋에 대해서만 액션이 수행되도록
13+
cancel-in-progress: false # 기존에 시작된 작업은 새 커밋이 들어왔다고 해서 바로 끄지 않고 끝날때까지 대기
14+
15+
on:
16+
push:
17+
paths:
18+
- ".github/workflows/**"
19+
- ".env"
20+
- "src/**"
21+
- "build.gradle.kts"
22+
- "settings.gradle.kts"
23+
- "Dockerfile"
24+
branches:
25+
- main
26+
- feat/be/**
27+
permissions:
28+
contents: write # 태그/릴리즈
29+
packages: write # GHCR 푸시
30+
31+
# 기본 셸
32+
defaults:
33+
run:
34+
shell: bash
35+
36+
jobs:
37+
makeTagAndRelease:
38+
runs-on: ubuntu-latest
39+
outputs:
40+
tag_name: ${{ steps.create_tag.outputs.new_tag }} # 이후 잡에서 사용할 태그명
41+
steps:
42+
- uses: actions/checkout@v4
43+
44+
# 버전 태그 자동 생성 (vX.Y.Z)
45+
- name: Create Tag
46+
id: create_tag
47+
uses: mathieudutour/github-tag-action@v6.2
48+
with:
49+
github_token: ${{ secrets.GITHUB_TOKEN }}
50+
51+
# 릴리즈 생성
52+
- name: Create Release
53+
id: create_release
54+
uses: actions/create-release@v1
55+
env:
56+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
57+
with:
58+
tag_name: ${{ steps.create_tag.outputs.new_tag }}
59+
release_name: Release ${{ steps.create_tag.outputs.new_tag }}
60+
body: ${{ steps.create_tag.outputs.changelog }}
61+
draft: false
62+
prerelease: false
63+
64+
# ---------------------------------------------------------
65+
# 2) 도커 이미지 빌드/푸시 (캐시 최대 활용)
66+
# ---------------------------------------------------------
67+
buildImageAndPush:
68+
name: 도커 이미지 빌드와 푸시
69+
needs: makeTagAndRelease
70+
runs-on: ubuntu-latest
71+
steps:
72+
- uses: actions/checkout@v4
73+
74+
# 빌드 컨텍스트에 .env 생성 (비어있어도 실패하지 않게)
75+
- name: .env 파일 생성
76+
env:
77+
DOT_ENV: ${{ secrets.DOT_ENV }}
78+
run: |
79+
# .env가 없으면 빌드 캐시가 매번 깨질 수 있으므로 항상 생성
80+
mkdir -p "${{ env.BACKEND_DIR }}"
81+
printf "%s" "${DOT_ENV}" > "${{ env.BACKEND_DIR }}/.env"
82+
83+
- name: Docker Buildx 설치
84+
uses: docker/setup-buildx-action@v3
85+
86+
# GHCR 로그인
87+
- name: 레지스트리 로그인
88+
uses: docker/login-action@v3
89+
with:
90+
registry: ghcr.io
91+
username: ${{ github.actor }}
92+
password: ${{ secrets.GITHUB_TOKEN }}
93+
94+
# 저장소 소유자명을 소문자로 (GHCR 경로 표준화)
95+
- name: set lower case owner name
96+
run: |
97+
echo "OWNER_LC=${OWNER,,}" >> "${GITHUB_ENV}"
98+
env:
99+
OWNER: "${{ github.repository_owner }}"
100+
101+
# 캐시를 최대한 활용하여 빌드 → 버전태그 및 latest 동시 푸시
102+
- name: 빌드 앤 푸시
103+
uses: docker/build-push-action@v6
104+
with:
105+
context: ${{ env.BACKEND_DIR }}
106+
push: true
107+
cache-from: type=gha
108+
cache-to: type=gha,mode=max
109+
tags: |
110+
ghcr.io/${{ env.OWNER_LC }}/${{ env.IMAGE_REPOSITORY }}:${{ needs.makeTagAndRelease.outputs.tag_name }}
111+
ghcr.io/${{ env.OWNER_LC }}/${{ env.IMAGE_REPOSITORY }}:latest
112+
113+
# ---------------------------------------------------------
114+
# 3) Blue/Green 무중단 배포 (EC2 + NPM 스위치)
115+
# ---------------------------------------------------------
116+
deploy:
117+
name: Blue/Green 무중단 배포
118+
runs-on: ubuntu-latest
119+
needs: [ makeTagAndRelease, buildImageAndPush ]
120+
steps:
121+
# AWS 자격 구성
122+
- uses: aws-actions/configure-aws-credentials@v4
123+
with:
124+
aws-region: ${{ secrets.AWS_REGION }}
125+
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
126+
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
127+
128+
# Name 태그로 EC2 인스턴스 조회 (없으면 실패)
129+
- name: 인스턴스 ID 가져오기
130+
id: get_instance_id
131+
run: |
132+
INSTANCE_ID=$(aws ec2 describe-instances \
133+
--filters "Name=tag:Name,Values=${{ env.EC2_INSTANCE_TAG_NAME }}" "Name=instance-state-name,Values=running" \
134+
--query "Reservations[].Instances[].InstanceId" --output text)
135+
[[ -n "${INSTANCE_ID}" && "${INSTANCE_ID}" != "None" ]] || { echo "No running instance found"; exit 1; }
136+
echo "INSTANCE_ID=${INSTANCE_ID}" >> "${GITHUB_ENV}"
137+
138+
# 원격(SSM)으로 Blue/Green 스위치 수행
139+
- name: AWS SSM Send-Command
140+
uses: peterkimzz/aws-ssm-send-command@master
141+
with:
142+
aws-region: ${{ secrets.AWS_REGION }}
143+
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
144+
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
145+
instance-ids: ${{ env.INSTANCE_ID }}
146+
working-directory: /
147+
comment: Deploy
148+
command: |
149+
set -Eeuo pipefail
150+
151+
# ---------------------------------------------------------
152+
# 0) 실행 로그(라인 타임스탬프 부착)
153+
# ---------------------------------------------------------
154+
LOG="/tmp/ssm-$(date +%Y%m%d_%H%M%S).log"
155+
exec > >(awk '{ fflush(); print strftime("[%Y-%m-%d %H:%M:%S]"), $0 }' | tee -a "$LOG")
156+
exec 2> >(awk '{ fflush(); print strftime("[%Y-%m-%d %H:%M:%S]"), $0 }' | tee -a "$LOG" >&2)
157+
158+
# ---------------------------------------------------------
159+
# 1) 변수 정의
160+
# - 슬롯 이름은 고정(두 개의 컨테이너 이름)
161+
# - blue/green은 "역할"이며 매 배포마다 바뀜
162+
# ---------------------------------------------------------
163+
source /etc/environment || true # 시스템 전역 변수(+ 비밀) 주입 시도
164+
OWNER_LC="${{ github.repository_owner }}"
165+
OWNER_LC="${OWNER_LC,,}" # 소문자 표준화
166+
IMAGE_TAG="${{ needs.makeTagAndRelease.outputs.tag_name }}"
167+
IMAGE_REPOSITORY="${{ env.IMAGE_REPOSITORY }}"
168+
IMAGE="ghcr.io/${OWNER_LC}/${IMAGE_REPOSITORY}:${IMAGE_TAG}"
169+
SLOT1="${{ env.CONTAINER_1_NAME }}"
170+
SLOT2="${{ env.CONTAINER_2_NAME }}"
171+
PORT_IN="${{ env.CONTAINER_PORT }}"
172+
NET="${{ env.DOCKER_NETWORK }}"
173+
174+
echo "🔹 Use image: ${IMAGE}"
175+
docker pull "${IMAGE}"
176+
177+
# ---------------------------------------------------------
178+
# 2) Nginx Proxy Manager(NPM) API 토큰 발급
179+
# - /etc/environment 등에 설정된 PASSWORD_1, APP_1_DOMAIN 사용 가정
180+
# ---------------------------------------------------------
181+
TOKEN=$(curl -s -X POST http://127.0.0.1:81/api/tokens \
182+
-H "Content-Type: application/json" \
183+
-d "{\"identity\": \"admin@npm.com\", \"secret\": \"${PASSWORD_1:-}\"}" | jq -r '.token')
184+
185+
# 토큰/도메인 검증(없으면 실패)
186+
[[ -n "${TOKEN}" && "${TOKEN}" != "null" ]] || { echo "NPM token issue failed"; exit 1; }
187+
[[ -n "${APP_1_DOMAIN:-}" ]] || { echo "APP_1_DOMAIN is empty"; exit 1; }
188+
189+
# 대상 프록시 호스트 ID 조회(도메인 매칭)
190+
PROXY_ID=$(curl -s -X GET "http://127.0.0.1:81/api/nginx/proxy-hosts" \
191+
-H "Authorization: Bearer ${TOKEN}" \
192+
| jq ".[] | select(.domain_names[]==\"${APP_1_DOMAIN}\") | .id")
193+
194+
[[ -n "${PROXY_ID}" && "${PROXY_ID}" != "null" ]] || { echo "Proxy host not found for ${APP_1_DOMAIN}"; exit 1; }
195+
196+
# 현재 프록시가 바라보는 업스트림(컨테이너명) 조회
197+
CURRENT_HOST=$(curl -s -X GET "http://127.0.0.1:81/api/nginx/proxy-hosts/${PROXY_ID}" \
198+
-H "Authorization: Bearer ${TOKEN}" \
199+
| jq -r '.forward_host')
200+
201+
echo "🔎 CURRENT_HOST: ${CURRENT_HOST:-none}"
202+
203+
# ---------------------------------------------------------
204+
# 3) 역할(blue/green) 판정
205+
# - blue : 현재 운영 중(CURRENT_HOST)
206+
# - green: 다음 운영(교체 대상)
207+
# ---------------------------------------------------------
208+
if [[ "${CURRENT_HOST:-}" == "${SLOT1}" ]]; then
209+
BLUE="${SLOT1}"
210+
GREEN="${SLOT2}"
211+
elif [[ "${CURRENT_HOST:-}" == "${SLOT2}" ]]; then
212+
BLUE="${SLOT2}"
213+
GREEN="${SLOT1}"
214+
else
215+
BLUE="none" # 초기 배포
216+
GREEN="${SLOT1}"
217+
fi
218+
echo "🎨 role -> blue(now): ${BLUE}, green(next): ${GREEN}"
219+
220+
# ---------------------------------------------------------
221+
# 4) green 역할 컨테이너 재기동
222+
# - 같은 네트워크 상에서 NPM이 컨테이너명:PORT로 프록시하므로 -p 불필요
223+
# ---------------------------------------------------------
224+
docker rm -f "${GREEN}" >/dev/null 2>&1 || true
225+
echo "🚀 run new container → ${GREEN}"
226+
docker run -d --name "${GREEN}" \
227+
--restart unless-stopped \
228+
--network "${NET}" \
229+
-e TZ=Asia/Seoul \
230+
"${IMAGE}"
231+
232+
# ---------------------------------------------------------
233+
# 5) 헬스체크 (/actuator/health 200 OK까지 대기)
234+
# ---------------------------------------------------------
235+
echo "⏱ health-check: ${GREEN}"
236+
TIMEOUT=120
237+
INTERVAL=3
238+
ELAPSED=0
239+
sleep 8 # 초기 부팅 여유
240+
241+
while (( ELAPSED < TIMEOUT )); do
242+
CODE=$(docker exec "${GREEN}" curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:${PORT_IN}/actuator/health" || echo 000)
243+
[[ "${CODE}" == "200" ]] && { echo "✅ ${GREEN} healthy"; break; }
244+
sleep "${INTERVAL}"
245+
ELAPSED=$((ELAPSED + INTERVAL))
246+
done
247+
[[ "${CODE:-000}" == "200" ]] || { echo "❌ ${GREEN} health failed"; docker logs --tail=200 "${GREEN}" || true; docker rm -f "${GREEN}" || true; exit 1; }
248+
249+
# ---------------------------------------------------------
250+
# 6) 업스트림 전환 (forward_host/forward_port만 업데이트)
251+
# ---------------------------------------------------------
252+
NEW_CFG=$(jq -n --arg host "${GREEN}" --argjson port ${PORT_IN} '{forward_host:$host, forward_port:$port}')
253+
curl -s -X PUT "http://127.0.0.1:81/api/nginx/proxy-hosts/${PROXY_ID}" \
254+
-H "Authorization: Bearer ${TOKEN}" \
255+
-H "Content-Type: application/json" \
256+
-d "${NEW_CFG}" >/dev/null
257+
echo "🔁 switch upstream → ${GREEN}:${PORT_IN}"
258+
259+
# ---------------------------------------------------------
260+
# 7) 이전 blue 종료(최초 배포면 생략)
261+
# ---------------------------------------------------------
262+
if [[ "${BLUE}" != "none" ]]; then
263+
docker stop "${BLUE}" >/dev/null 2>&1 || true
264+
docker rm "${BLUE}" >/dev/null 2>&1 || true
265+
echo "🧹 removed old blue: ${BLUE}"
266+
fi
267+
268+
# ---------------------------------------------------------
269+
# 8) 이미지 정리(현재 태그/ latest 제외) - 결과 없음도 오류 아님
270+
# - pipefail과 grep의 종료코드(1)를 고려해 블록 전체에 || true 적용
271+
# ---------------------------------------------------------
272+
{
273+
docker images --format '{{.Repository}}:{{.Tag}}' \
274+
| grep -F "ghcr.io/${OWNER_LC}/${IMAGE_REPOSITORY}:" \
275+
| grep -v -F ":${IMAGE_TAG}" \
276+
| grep -v -F ":latest" \
277+
| xargs -r docker rmi
278+
} || true
279+
280+
echo "🏁 Blue/Green switch complete. now blue = ${GREEN}"

0 commit comments

Comments
 (0)