-
Notifications
You must be signed in to change notification settings - Fork 54
221 lines (194 loc) Β· 8.89 KB
/
deploy.yml
File metadata and controls
221 lines (194 loc) Β· 8.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
name: Deploy to Cloud Run
on:
pull_request:
branches: [main, master]
types: [opened, synchronize, reopened, closed]
push:
branches: [main, master]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
deploy:
if: github.event.action != 'closed'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Authenticate to Google Cloud
uses: google-github-actions/auth@v2
with:
credentials_json: ${{ secrets.GCP_SA_KEY }}
- name: Set Environment Variables
run: |
if [[ "${{ github.event_name }}" == "pull_request" ]]; then
# PR Preview environment
echo "ENV_NAME=pr-${{ github.event.pull_request.number }}" >> $GITHUB_ENV
echo "PROJECT_ID=nxtdo-dev" >> $GITHUB_ENV
echo "REGION=asia-south1" >> $GITHUB_ENV
elif [[ "${{ github.ref }}" == "refs/heads/master" ]]; then
# Production environment
echo "ENV_NAME=production" >> $GITHUB_ENV
echo "PROJECT_ID=nxtdo-prod" >> $GITHUB_ENV
echo "REGION=asia-south1" >> $GITHUB_ENV
else
# Staging/Dev environment (main branch)
echo "ENV_NAME=staging" >> $GITHUB_ENV
echo "PROJECT_ID=nxtdo-dev" >> $GITHUB_ENV
echo "REGION=asia-south1" >> $GITHUB_ENV
fi
- name: Build and Push Container
run: |
# Use async to avoid log streaming permission issues
BUILD_ID=$(gcloud builds submit --tag gcr.io/${{ env.PROJECT_ID }}/nxtdo-api:${{ github.sha }} \
--project=${{ env.PROJECT_ID }} \
--async \
--format='value(id)')
echo "Build ID: $BUILD_ID"
# Poll for build completion
while true; do
STATUS=$(gcloud builds describe $BUILD_ID \
--project=${{ env.PROJECT_ID }} \
--format='value(status)')
echo "Build status: $STATUS"
if [[ "$STATUS" == "SUCCESS" ]]; then
echo "Build completed successfully!"
break
elif [[ "$STATUS" == "FAILURE" || "$STATUS" == "CANCELLED" || "$STATUS" == "TIMEOUT" ]]; then
echo "Build failed with status: $STATUS"
# Get build logs for debugging
gcloud builds log $BUILD_ID --project=${{ env.PROJECT_ID }} || true
exit 1
fi
sleep 10
done
- name: Deploy to Cloud Run
id: deploy
run: |
gcloud run deploy nxtdo-api-${{ env.ENV_NAME }} \
--image gcr.io/${{ env.PROJECT_ID }}/nxtdo-api:${{ github.sha }} \
--platform managed \
--region ${{ env.REGION }} \
--allow-unauthenticated \
--project=${{ env.PROJECT_ID }} \
--port 8080
# Get the service URL
SERVICE_URL=$(gcloud run services describe nxtdo-api-${{ env.ENV_NAME }} \
--region ${{ env.REGION }} \
--project=${{ env.PROJECT_ID }} \
--format='value(status.url)')
echo "service_url=$SERVICE_URL" >> $GITHUB_OUTPUT
- name: Comment PR with Preview URL
if: github.event_name == 'pull_request'
uses: actions/github-script@v7
with:
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: `### π Preview Deployment Ready!\n\n**Preview URL:** ${{ steps.deploy.outputs.service_url }}\n\n**Environment:** \`pr-${{ github.event.pull_request.number }}\`\n**Commit:** ${{ github.sha }}\n\n> This preview will be automatically deleted when the PR is closed.`
})
# Create/Update README with Staging URL
- name: Update README with Staging URL
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
// Read current README
let readmeContent = '';
try {
const { data } = await github.rest.repos.getContent({
owner: context.repo.owner,
repo: context.repo.repo,
path: 'README.md'
});
readmeContent = Buffer.from(data.content, 'base64').toString('utf8');
} catch (error) {
console.log('README.md not found, creating new one');
readmeContent = '# NxtDo Backend\n\n';
}
// Update or add staging URL section
const stagingUrl = '${{ steps.deploy.outputs.service_url }}';
const stagingSection = `## π Environments\n\n- **Staging**: [${stagingUrl}](${stagingUrl})\n- **Last Updated**: ${new Date().toISOString().split('T')[0]}\n`;
// Replace existing environments section or add new one
if (readmeContent.includes('## π Environments')) {
readmeContent = readmeContent.replace(/## π Environments[\s\S]*?(?=\n## |\n# |$)/, stagingSection);
} else {
readmeContent = readmeContent + '\n' + stagingSection;
}
// Update README file
try {
const { data: currentFile } = await github.rest.repos.getContent({
owner: context.repo.owner,
repo: context.repo.repo,
path: 'README.md'
});
await github.rest.repos.createOrUpdateFileContents({
owner: context.repo.owner,
repo: context.repo.repo,
path: 'README.md',
message: `π Update staging URL: ${stagingUrl}`,
content: Buffer.from(readmeContent).toString('base64'),
sha: currentFile.sha
});
} catch (error) {
// Create new README if it doesn't exist
await github.rest.repos.createOrUpdateFileContents({
owner: context.repo.owner,
repo: context.repo.repo,
path: 'README.md',
message: `π Create README with staging URL: ${stagingUrl}`,
content: Buffer.from(readmeContent).toString('base64')
});
}
console.log('README updated with staging URL');
# NEW: Create GitHub Release with Staging Info
- name: Create Staging Release
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
uses: actions/github-script@v7
with:
script: |
const tagName = `staging-${context.sha.substring(0, 7)}`;
try {
await github.rest.repos.createRelease({
owner: context.repo.owner,
repo: context.repo.repo,
tag_name: tagName,
name: `Staging Deployment - ${new Date().toISOString().split('T')[0]}`,
body: `## π Staging Deployment\n\n**Staging URL:** ${{ steps.deploy.outputs.service_url }}\n**Commit:** ${context.sha}\n**Environment:** staging\n**Deployed:** ${new Date().toISOString()}\n\n### Changes\n${context.payload.head_commit?.message || 'Auto-deployment from main branch'}`,
prerelease: true,
draft: false
});
console.log(`Created staging release: ${tagName}`);
} catch (error) {
console.log('Release creation failed:', error.message);
}
# Cleanup PR preview environments after PR is closed/merged
cleanup:
if: github.event_name == 'pull_request' && github.event.action == 'closed'
runs-on: ubuntu-latest
steps:
- name: Authenticate to Google Cloud
uses: google-github-actions/auth@v2
with:
credentials_json: ${{ secrets.GCP_SA_KEY }}
- name: Delete Preview Service
run: |
gcloud run services delete nxtdo-api-pr-${{ github.event.pull_request.number }} \
--region asia-south1 \
--project=nxtdo-dev \
--quiet || true
# NEW: Comment on merged PR with staging info
- name: Comment on Merged PR with Staging Info
if: github.event.pull_request.merged == true
uses: actions/github-script@v7
with:
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: `### β
PR Merged & Deployed to Staging!\n\nποΈ **Preview environment deleted**\nπ **Now live on staging:** https://nxtdo-api-staging-42m3vcanhq-el.a.run.app\n\n*Check the [Releases page](https://github.com/${context.repo.owner}/${context.repo.repo}/releases) for deployment details.*`
})