-
Notifications
You must be signed in to change notification settings - Fork 0
261 lines (239 loc) · 10.7 KB
/
Copy pathsweep.yml
File metadata and controls
261 lines (239 loc) · 10.7 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
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
256
257
258
259
260
261
# kamal-previews / orphan sweep
#
# Reconciles the set of registered "preview" GitHub Deployments against the
# set of currently-open pull requests, and tears down anything that's been
# orphaned. This catches the rare but real case where a `pull_request: closed`
# or `delete` event was missed (GitHub Actions outage, branch deleted while
# Actions was disabled, etc.).
#
# Consumers schedule this from their own repo:
#
# name: Preview sweep
# on:
# schedule:
# - cron: '0 6 * * *' # daily at 06:00 UTC
# workflow_dispatch:
# permissions:
# contents: read
# pull-requests: read
# deployments: write
# jobs:
# sweep:
# uses: web-ascender/github-actions-kamal-previews/.github/workflows/sweep.yml@v1
# with:
# base-deploy-file: config/deploy.staging.yml
# domain-suffix: preview.example.com
# deploy-host: deploy.example.com
# database-engine: postgres
# databases: |
# DATABASE_NAME=myapp_staging:myapp_{db_slug}
# environment-prefix: preview-
# secrets: inherit
name: kamal-previews / sweep
on:
workflow_call:
inputs:
base-deploy-file: { type: string, required: true }
domain-suffix: { type: string, required: true }
deploy-host: { type: string, required: true }
database-engine: { type: string, default: none }
databases: { type: string, default: "" }
database-admin-url-var: { type: string, default: "DATABASE_URL" }
sqlite-target-path-pattern: { type: string, default: "" }
sqlite-also-clone: { type: string, default: "" }
base-secrets-file: { type: string, default: "" }
domain-label-pattern: { type: string, default: "{slug}" }
service-pattern: { type: string, default: "{base_service}-{slug}" }
destination-pattern: { type: string, default: "{slug}" }
env-label: { type: string, default: preview }
prefix-strip: { type: string, default: "feature/,feat/,fix/,bug/,bugfix/,chore/,hotfix/,release/" }
ruby-version: { type: string, default: "3.3" }
kamal-version: { type: string, default: "" }
bundler-cache:
description: Run `bundle install` (with caching) on the runner. Default `true` because the dominant Rails-secrets pattern (`bin/rails credentials:fetch` in the secrets file) needs it. Set to `false` only if your secrets pipeline is bundle-free.
type: string
default: "true"
ssh-user: { type: string, default: deploy }
ssh-port: { type: string, default: "22" }
environment-prefix:
description: |
Only environments whose name starts with this string are considered.
Defaults to `preview-` (matches the convention used by this repo's
deployment-status action).
type: string
default: "preview-"
dry-run:
description: When `true`, log what would be torn down but don't actually do it.
type: string
default: "false"
secrets:
SSH_PRIVATE_KEY: { required: true }
DATABASE_ADMIN_URL: { required: false }
RAILS_MASTER_KEY: { required: false }
permissions:
contents: read
pull-requests: read
deployments: write
jobs:
identify-orphans:
runs-on: ubuntu-latest
outputs:
orphan-branches: ${{ steps.find.outputs.orphan_branches }}
steps:
- id: find
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
ENV_PREFIX: ${{ inputs.environment-prefix }}
run: |
set -euo pipefail
# Open PR head refs (branch names) → these are the deploys that should stay.
mapfile -t open_branches < <(gh pr list --repo "$GH_REPO" --state open --json headRefName --jq '.[].headRefName')
# All transient environments matching the configured prefix.
mapfile -t envs < <(gh api -H 'Accept: application/vnd.github+json' \
"/repos/$GH_REPO/environments" --paginate \
--jq '.environments // .[] | .name' \
| grep -E "^${ENV_PREFIX}" || true)
orphans=()
for env in "${envs[@]}"; do
# Get the most recent deployment for this environment.
deployment_state="$(gh api -H 'Accept: application/vnd.github+json' \
"/repos/$GH_REPO/deployments?environment=${env}&per_page=1" \
--jq '.[0].id // empty' || true)"
if [ -z "$deployment_state" ]; then continue; fi
latest_status="$(gh api -H 'Accept: application/vnd.github+json' \
"/repos/$GH_REPO/deployments/${deployment_state}/statuses?per_page=1" \
--jq '.[0].state // empty' || true)"
if [ "$latest_status" = "inactive" ] || [ "$latest_status" = "removed" ]; then
continue
fi
slug="${env#${ENV_PREFIX}}"
# Try to match the slug against any open PR's head ref via the
# same slug rule. We re-derive each open branch's slug locally.
matched=0
for branch in "${open_branches[@]}"; do
# Quick approximation of kamal-previews' slug rule: lowercase,
# non-alnum → '-', collapse '-', strip leading prefix segments.
candidate="$(echo "$branch" | tr '[:upper:]' '[:lower:]' | sed -E 's|^(feature|feat|fix|bug|bugfix|chore|hotfix|release)/||' | sed -E 's/[^a-z0-9]+/-/g; s/^-+//; s/-+$//')"
if [ "$candidate" = "$slug" ]; then matched=1; break; fi
done
if [ "$matched" = "0" ]; then
echo "::notice::Orphan detected: environment=$env (no open PR matches slug '$slug')"
orphans+=("$slug")
fi
done
if [ ${#orphans[@]} -eq 0 ]; then
echo "No orphans found."
echo "orphan_branches=[]" >> "$GITHUB_OUTPUT"
else
json="$(printf '%s\n' "${orphans[@]}" | jq -R -s -c 'split("\n") | map(select(length > 0))')"
echo "orphan_branches=$json" >> "$GITHUB_OUTPUT"
fi
teardown-orphans:
needs: identify-orphans
if: |
needs.identify-orphans.outputs.orphan-branches != '[]' &&
needs.identify-orphans.outputs.orphan-branches != ''
runs-on: ubuntu-latest
strategy:
fail-fast: false
max-parallel: 3
matrix:
slug: ${{ fromJSON(needs.identify-orphans.outputs.orphan-branches) }}
steps:
- if: inputs.dry-run == 'true'
run: |
echo "::notice::DRY RUN — would tear down orphan with slug=${{ matrix.slug }}"
exit 0
- uses: actions/checkout@v4
- id: kp_ref
env:
WORKFLOW_REF: ${{ github.workflow_ref }}
run: |
set -euo pipefail
repo="${WORKFLOW_REF%/.github/workflows/*}"
ref="${WORKFLOW_REF##*@}"
echo "repo=$repo" >> "$GITHUB_OUTPUT"
echo "ref=$ref" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@v4
with:
repository: ${{ steps.kp_ref.outputs.repo }}
ref: ${{ steps.kp_ref.outputs.ref }}
path: .kamal-previews
- uses: ./.kamal-previews/.github/actions/setup
with:
ruby-version: ${{ inputs.ruby-version }}
kamal-version: ${{ inputs.kamal-version }}
bundler-cache: ${{ inputs.bundler-cache }}
ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}
setup-buildx: "false"
setup-gha-cache: "false"
# The slug from the matrix is itself the destination identifier under
# the default destination-pattern. We use it directly to look up the
# database name (we still need to derive db_slug etc.) by passing the
# slug as the branch name to generate-config — yes, that's a tiny abuse
# but it produces the right artifacts.
- id: config
uses: ./.kamal-previews/.github/actions/generate-config
with:
branch-name: ${{ matrix.slug }}
base-deploy-file: ${{ inputs.base-deploy-file }}
base-secrets-file: ${{ inputs.base-secrets-file }}
domain-suffix: ${{ inputs.domain-suffix }}
domain-label-pattern: ${{ inputs.domain-label-pattern }}
service-pattern: ${{ inputs.service-pattern }}
destination-pattern: ${{ inputs.destination-pattern }}
databases: ${{ inputs.databases }}
env-label: ${{ inputs.env-label }}
prefix-strip: ${{ inputs.prefix-strip }}
- id: db_admin_url
if: inputs.database-engine == 'postgres' || inputs.database-engine == 'mysql'
env:
EXPLICIT_URL: ${{ secrets.DATABASE_ADMIN_URL }}
BASE_SECRETS_FILE: ${{ inputs.base-secrets-file }}
VAR_NAME: ${{ inputs.database-admin-url-var }}
RAILS_MASTER_KEY: ${{ secrets.RAILS_MASTER_KEY }}
run: |
set -euo pipefail
url=""
if [ -n "${EXPLICIT_URL:-}" ]; then
url="$EXPLICIT_URL"
elif [ -n "$BASE_SECRETS_FILE" ] && [ -f "$BASE_SECRETS_FILE" ]; then
url="$(set -a; . "$BASE_SECRETS_FILE"; set +a; printf '%s' "${!VAR_NAME-}")"
fi
if [ -z "$url" ]; then
echo "::error::Could not resolve a database admin URL for sweep teardown."; exit 1
fi
echo "::add-mask::$url"
echo "KAMAL_PREVIEWS_DB_ADMIN_URL=$url" >> "$GITHUB_ENV"
- id: sqlite_path
if: inputs.database-engine == 'sqlite'
env:
PATTERN: ${{ inputs.sqlite-target-path-pattern }}
SLUG: ${{ steps.config.outputs.slug }}
DB_SLUG: ${{ steps.config.outputs.db_slug }}
run: |
set -euo pipefail
if [ -z "$PATTERN" ]; then echo "path=" >> "$GITHUB_OUTPUT"; exit 0; fi
resolved="${PATTERN//\{slug\}/$SLUG}"
resolved="${resolved//\{db_slug\}/$DB_SLUG}"
echo "path=$resolved" >> "$GITHUB_OUTPUT"
- uses: ./.kamal-previews/.github/actions/teardown
with:
destination: ${{ steps.config.outputs.destination }}
- if: inputs.database-engine != 'none'
uses: ./.kamal-previews/.github/actions/drop-database
with:
engine: ${{ inputs.database-engine }}
host: ${{ inputs.deploy-host }}
ssh-user: ${{ inputs.ssh-user }}
ssh-port: ${{ inputs.ssh-port }}
admin-url: ${{ env.KAMAL_PREVIEWS_DB_ADMIN_URL }}
databases: ${{ steps.config.outputs.databases_resolved }}
sqlite-target-path: ${{ steps.sqlite_path.outputs.path }}
sqlite-also-drop: ${{ inputs.sqlite-also-clone }}
- if: always()
uses: ./.kamal-previews/.github/actions/deployment-status
with:
state: removed
environment-name: preview-${{ steps.config.outputs.slug }}