This repository has been archived by the owner on Aug 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
255 lines (225 loc) · 9.66 KB
/
pr-preview.yml
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
name: PR Preview
on:
# Pull Request previews
pull_request:
types:
# - opened
# - reopened
# - synchronize
- closed
workflow_dispatch:
inputs:
prNumber:
description: 'The PR number to run this against.'
required: true
type: number
forceDeploy:
description: Forces deployment of the site if the PR is in draft mode.
type: boolean
default: false
# Azure OIDC:
# App: github-deploy-site
# Credential Name: gh-actions-pr-preview
# Subscription: Sandbox
env:
prNumber: ${{ github.event.inputs.prNumber > 0 && github.event.inputs.prNumber || github.event.number }}
resourceGroup: rg-ocelot-website
storageName: "ocelotprpreview${{ github.event.inputs.prNumber > 0 && github.event.inputs.prNumber || github.event.number }}"
indexFile: index.html
errorFile: 404.html
# Sets permissions of the GITHUB_TOKEN to allow Azure OIDC
permissions:
contents: read
pull-requests: write # Commenting on PRs
id-token: write # This is required for requesting the JWT from Azure
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages-preview-${{ github.event.inputs.prNumber > 0 && github.event.inputs.prNumber || github.event.number }}"
cancel-in-progress: false
jobs:
# This may be run manually so get the PR status
get-pr:
runs-on: ubuntu-latest
outputs:
valid: ${{ steps.check-secrets.outputs.valid }}
pr: ${{ steps.get-pr.outputs.pr }}
steps:
- name: Check Secrets
id: check-secrets
run: |
echo "valid=$([ -n "${{ secrets.AZURE_CLIENT_ID }}" ] && [ -n "${{ secrets.AZURE_SUBSCRIPTION_ID }}" ] && [ -n "${{ secrets.AZURE_TENANT_ID }}" ] && echo 'true' || echo 'false')" >> $GITHUB_OUTPUT
- uses: dkershner6/get-pull-request-action@v1
id: get-pr
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
pull-number: ${{ env.prNumber }}
# Build job
build:
needs: [ get-pr ]
# If this is a PR, only run this if the PR is not a draft or closed
# This can be force deployed as well
if: ${{ needs.get-pr.outputs.valid == 'true' && (fromJSON(needs.get-pr.outputs.pr).draft == false || github.event.inputs.forceDeploy == true) && fromJSON(needs.get-pr.outputs.pr).state != 'closed' }}
uses: ./.github/workflows/build.yml
deploy-preview:
# Add a dependency to the build job
needs: [ get-pr, build ]
runs-on: ubuntu-latest
steps:
- name: Download Build Artifact
id: download-artifact
uses: actions/download-artifact@v4
with:
name: github-pages # Automatically named from actions/upload-pages-artifact
- name: Extract Artifact
id: extract-artifact
# The file is artifact.tar from https://github.com/actions/upload-pages-artifact/blob/main/action.yml#L69
run: |
tar xvf artifact.tar
rm artifact.tar
- name: Azure Login
uses: azure/login@v1
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
enable-AzPSSession: true
- name: Create Storage Account
id: storage-account
uses: azure/powershell@v1
with:
azPSVersion: latest
inlineScript: |
$acct = Get-AzStorageAccount -ResourceGroupName '${{ env.resourceGroup }}' -Name '${{ env.storageName }}' -ErrorAction SilentlyContinue
$tags = @{
'managed-by'='GitHub'
'sha'='${{ github.sha }}'
'pullrequest'='${{ github.repository }}/${{ env.prNumber }}'
'pullrequest-repository'='${{ github.repository }}'
'pullrequest-number'='${{ env.prNumber }}'
'pullrequest-url'='https://github.com/${{ github.repository }}/pull/${{ env.prNumber }}'
'created'=(Get-Date | ConvertTo-Json) -replace '"',''
'modified'=(Get-Date | ConvertTo-Json) -replace '"',''
}
if (!($acct)) {
Write-Host 'Creating storage account: ${{ env.storageName }}'
New-AzStorageAccount `
-ResourceGroupName '${{ env.resourceGroup }}' `
-Name '${{ env.storageName }}' `
-SkuName Standard_LRS `
-Location eastus `
-Tags $tags
Write-Host 'Enabling Static Websites'
$acct = Get-AzStorageAccount -ResourceGroupName '${{ env.resourceGroup }}' -Name '${{ env.storageName }}' -ErrorAction SilentlyContinue
Enable-AzStorageStaticWebsite -IndexDocument '${{ env.indexFile }}' -ErrorDocument404Path '${{ env.errorFile }}' -Context $acct.Context
} else {
Write-Host 'Storage account exists, updating tags.'
# Save the creation date
if ($acct.Tags -and $acct.Tags.ContainsKey('created')) {
$tags['created'] = $acct.Tags['created']
}
Set-AzStorageAccount `
-ResourceGroupName '${{ env.resourceGroup }}' `
-Name '${{ env.storageName }}' `
-Tags $tags
}
Write-Host 'URL:'
Write-Host $acct.PrimaryEndpoints.Web
Write-Output "previewUrl=$($acct.PrimaryEndpoints.Web)" >> $env:GITHUB_OUTPUT
- name: Deploy Preview to Azure Storage
id: deploy-preview
uses: azure/powershell@v1
with:
azPSVersion: latest
inlineScript: |
$acct = Get-AzStorageAccount -ResourceGroupName '${{ env.resourceGroup }}' -Name '${{ env.storageName }}' -ErrorAction SilentlyContinue
if (!($acct)) {
Write-Error 'Unable to find the storage account: ${{ env.storageName }}'
exit 1
}
# Generate a proper SAS token
$container = Get-AzStorageContainer -Context $acct.Context -Name `$web
$token = New-AzStorageContainerSASToken -Context $acct.Context -Name `$web -Permission rwdl -ExpiryTime (Get-Date).AddMinutes(10)
$containerUri = [System.UriBuilder]::new($container.blobContainerClient.Uri)
$containerUri.Query = $token
$containerUriStr = $containerUri.Uri.ToString()
# Enforce a robots.txt which blocks all crawlers
"User-agent: *`nDisallow: /" | Out-File -FilePath robots.txt -Force
# Using AzCopy should make this easy with content type autodetection
azcopy sync . "$containerUriStr" --recursive --delete-destination true
- name: Logout Azure
run: |
az logout
if: always()
- name: Comment PR
id: post-url
uses: thollander/actions-comment-pull-request@v2
with:
message: |
Preview deployed to [${{ steps.storage-account.outputs.previewUrl }}](${{ steps.storage-account.outputs.previewUrl }})
comment_tag: pr-link
mode: recreate
reactions: hooray, rocket
pr_number: ${{ env.prNumber }}
- name: Comment PR
id: post-failure
uses: thollander/actions-comment-pull-request@v2
# Make sure we're not posting a failure because we failed to comment
if: failure() && steps.post-url.outcome != 'failure'
with:
message: |
Unable to deploy the preview. Check the Actions log.
comment_tag: pr-link
mode: recreate
reactions: eyes
pr_number: ${{ env.prNumber }}
destroy-preview:
needs: [ get-pr ]
runs-on: ubuntu-latest
# Only run this if the PR is closed
if: ${{ needs.get-pr.outputs.valid == 'true' && fromJSON(needs.get-pr.outputs.pr).state == 'closed' }}
steps:
- name: Azure Login
uses: azure/login@v1
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
enable-AzPSSession: true
- name: Delete Storage Account
uses: azure/powershell@v1
with:
azPSVersion: latest
inlineScript: |
$acct = Get-AzStorageAccount -ResourceGroupName '${{ env.resourceGroup }}' -Name '${{ env.storageName }}' -ErrorAction SilentlyContinue
if ($acct) {
Write-Host 'Removing storage account: ${{ env.storageName }}'
Remove-AzStorageAccount -ResourceGroupName '${{ env.resourceGroup }}' -Name '${{ env.storageName }}' -ErrorAction Stop -Force
} else {
Write-Host 'Storage account does not exist, skipping.'
}
- name: Logout Azure
run: |
az logout
if: always()
- name: Comment PR
id: delete-post
uses: thollander/actions-comment-pull-request@v2
with:
message: |
The preview storage account has been deleted.
comment_tag: pr-link
mode: recreate
pr_number: ${{ env.prNumber }}
- name: Storage Account Deletion Failed
id: post-failure
uses: thollander/actions-comment-pull-request@v2
# Make sure we're not posting a failure because we failed to comment
if: failure() && steps.delete-post.outcome != 'failure'
with:
message: |
**WARNING:** The preview storage account '${{ env.storageName }}' was unable to be deleted. Please check and delete manually if required.
comment_tag: pr-link
mode: recreate
reactions: eyes
pr_number: ${{ env.prNumber }}