Repository navigation
Expand file tree
/
Copy pathaction.yml
More file actions
365 lines (348 loc) · 14.5 KB
/
Copy pathaction.yml
File metadata and controls
365 lines (348 loc) · 14.5 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
name: Railway Config
description: >-
Plan Railway Infrastructure as Code on pull requests and apply the reviewed
plan artifact on merge. Merge does not re-plan: a drifted environment or a
different .railway/ tree fails instead of applying an unreviewed diff.
author: Railway
branding:
icon: upload-cloud
color: purple
inputs:
command:
description: "`plan` (on PR) or `apply` (on merged PR, or on push of a merged PR's commit)."
required: true
railway-token:
description: Railway project token with access to the target environment.
required: true
environment:
description: >-
Environment name or ID to plan. Omit to use the token's environment.
A workspace token can target any environment in the project. Apply uses
the environment pinned in the plan, so this does not change an existing
workflow that leaves it empty.
required: false
default: ""
cli-version:
description: "@railway/cli version to install."
required: false
default: latest
artifact-name:
description: Name of the uploaded plan artifact.
required: false
default: railway-plan
plan-path:
description: Path of the pinned plan file.
required: false
default: railway-plan.json
comment:
description: Post/update a plan comment on the pull request (plan only).
required: false
default: "true"
confirm-destructive:
description: >-
Pass --confirm-destructive on apply. The plan comment marks destructive
changes, so merging is the approval. Set to "false" to make destructive
applies fail instead.
required: false
default: "true"
package-manager:
description: >-
Package manager used to install repository dependencies in plan mode:
`auto` (default) detects it from package.json `packageManager` and the
lockfiles, or pin it to `npm`, `pnpm`, `yarn`, `bun` or `none`.
required: false
default: auto
github-token:
description: Token used to upload/download the plan artifact and comment.
required: false
default: ${{ github.token }}
runs:
using: composite
steps:
- name: Validate command
shell: bash
run: |
case "${{ inputs.command }}" in
plan|apply) ;;
*) echo "command must be 'plan' or 'apply', got '${{ inputs.command }}'" >&2; exit 1 ;;
esac
# The TypeScript authoring file is evaluated with node --experimental-strip-types,
# which needs node >= 22.6. This also provides npm for the CLI install.
- uses: actions/setup-node@v4
with:
node-version: 24
- name: Install Railway CLI
shell: bash
working-directory: ${{ runner.temp }}
run: npm install -g "@railway/cli@${{ inputs.cli-version }}"
- name: Detect package manager
id: pm
if: inputs.command == 'plan'
shell: bash
run: |
set -euo pipefail
pm="${{ inputs.package-manager }}"
if [ "$pm" = "auto" ]; then
pm=""
# package.json `packageManager` wins: it's what corepack enforces.
if [ -f package.json ]; then
pm="$(node -e 'try { const f = require("./package.json").packageManager; if (typeof f === "string") process.stdout.write(f.split("@")[0].trim()) } catch {}')"
fi
fi
if [ -z "$pm" ]; then
if [ -f pnpm-lock.yaml ] || [ -f pnpm-workspace.yaml ]; then
pm=pnpm
elif [ -f yarn.lock ]; then
pm=yarn
elif [ -f bun.lockb ] || [ -f bun.lock ]; then
pm=bun
elif [ -f package.json ]; then
pm=npm
else
pm=none
fi
fi
case "$pm" in
npm|pnpm|yarn|bun|none) ;;
*) echo "Unsupported package manager '$pm'. Set package-manager to npm, pnpm, yarn, bun or none." >&2; exit 1 ;;
esac
echo "Installing repository dependencies with: $pm"
echo "manager=$pm" >> "$GITHUB_OUTPUT"
- name: Enable corepack
if: inputs.command == 'plan' && (steps.pm.outputs.manager == 'pnpm' || steps.pm.outputs.manager == 'yarn')
shell: bash
env:
COREPACK_ENABLE_DOWNLOAD_PROMPT: "0"
run: |
set -euo pipefail
PM="${{ steps.pm.outputs.manager }}"
corepack enable "$PM" || true
if ! command -v "$PM" >/dev/null 2>&1; then
npm install -g "$PM"
fi
"$PM" --version
- name: Install bun
if: inputs.command == 'plan' && steps.pm.outputs.manager == 'bun'
uses: oven-sh/setup-bun@v2
- name: Install repository dependencies
if: inputs.command == 'plan' && steps.pm.outputs.manager != 'none'
shell: bash
env:
COREPACK_ENABLE_DOWNLOAD_PROMPT: "0"
run: |
set -euo pipefail
case "${{ steps.pm.outputs.manager }}" in
pnpm)
if [ -f pnpm-lock.yaml ]; then
pnpm install --frozen-lockfile
else
pnpm install --no-frozen-lockfile
fi
;;
yarn)
# Yarn 1 and Yarn 2+ spell "don't touch the lockfile" differently.
if [ "$(yarn --version | cut -d. -f1)" = "1" ]; then
if [ -f yarn.lock ]; then
yarn install --frozen-lockfile
else
yarn install
fi
elif [ -f yarn.lock ]; then
yarn install --immutable
else
yarn install --no-immutable
fi
;;
bun)
if [ -f bun.lockb ] || [ -f bun.lock ]; then
bun install --frozen-lockfile
else
bun install
fi
;;
npm)
if [ -f package-lock.json ] || [ -f npm-shrinkwrap.json ]; then
npm ci --no-audit --no-fund
else
npm install --no-audit --no-fund
fi
;;
esac
- name: Plan
if: inputs.command == 'plan'
shell: bash
env:
RAILWAY_TOKEN: ${{ inputs.railway-token }}
ENVIRONMENT: ${{ inputs.environment }}
run: |
set -euo pipefail
if [ -n "$ENVIRONMENT" ]; then
railway config plan --out "${{ inputs.plan-path }}" --environment "$ENVIRONMENT"
else
railway config plan --out "${{ inputs.plan-path }}"
fi
- name: Upload pinned plan
if: inputs.command == 'plan'
uses: actions/upload-artifact@v4
with:
name: ${{ inputs.artifact-name }}
path: ${{ inputs.plan-path }}
# Posting under the official Railway bot identity: backboard composes and
# posts the comment through the Railway GitHub App. Requires `id-token:
# write` (proves this workflow runs in this repo) and the Railway app
# installed on the repo. Falls back to github-token posting below.
- name: Comment plan (Railway identity)
id: railway_comment
if: inputs.command == 'plan' && inputs.comment == 'true' && github.event_name == 'pull_request'
shell: bash
env:
RAILWAY_TOKEN: ${{ inputs.railway-token }}
run: |
set -euo pipefail
posted=false
if [ -n "${ACTIONS_ID_TOKEN_REQUEST_URL:-}" ]; then
OIDC="$(curl -sS -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
"${ACTIONS_ID_TOKEN_REQUEST_URL}&audience=railway" | jq -r '.value // empty' || true)"
if [ -n "$OIDC" ]; then
PR_NUMBER="$(jq -r '.pull_request.number' "$GITHUB_EVENT_PATH")"
PAYLOAD="$(jq -c --arg oidc "$OIDC" --argjson pr "$PR_NUMBER" '{
query: "mutation($input: EnvironmentConfigPlanCommentUpsertInput!) { environmentConfigPlanCommentUpsert(input: $input) { url } }",
variables: { input: {
environmentId: .environmentId,
githubOidcToken: $oidc,
prNumber: $pr,
plan: {
changes: ((.changeSet.changes // []) | map({ kind: .kind, summary: (.summary // "change") })),
destructive: (.destructive // false),
sourceTree: .sourceTree,
configEtag: .configEtag,
changeSetHash: .changeSetHash,
cliVersion: .cliVersion
}
} }
}' "${{ inputs.plan-path }}")"
RESP="$(curl -sS -H "project-access-token: $RAILWAY_TOKEN" -H "Content-Type: application/json" \
-d "$PAYLOAD" https://backboard.railway.com/graphql/v2 || true)"
URL="$(echo "$RESP" | jq -r '.data.environmentConfigPlanCommentUpsert.url // empty' 2>/dev/null || true)"
if [ -n "$URL" ]; then
posted=true
echo "Posted plan comment under the Railway identity: $URL"
else
ERR="$(echo "$RESP" | jq -r '.errors[0].message // "no response"' 2>/dev/null || echo 'no response')"
echo "Railway-identity comment unavailable ($ERR); falling back to github-token."
fi
fi
else
echo "No id-token permission; posting with github-token. Grant 'id-token: write' for the Railway bot identity."
fi
echo "posted=$posted" >> "$GITHUB_OUTPUT"
- name: Comment plan
if: inputs.command == 'plan' && inputs.comment == 'true' && github.event_name == 'pull_request' && steps.railway_comment.outputs.posted != 'true'
uses: actions/github-script@v7
with:
github-token: ${{ inputs.github-token }}
script: |
const fs = require('fs');
const plan = JSON.parse(fs.readFileSync('${{ inputs.plan-path }}', 'utf8'));
const changes = Array.isArray(plan.changeSet?.changes) ? plan.changeSet.changes.length : 0;
// The CLI only marks whole-resource creates '+' and deletes '-';
// variable-level changes are all '~'. Remap those by verb so additions
// render green and removals red in the diff block.
const diff = (plan.diff || '').trimEnd().split('\n')
.map((line) => {
const verb = (line.match(/^~ (\w+)/) || [])[1]?.toLowerCase();
if (['delete', 'remove', 'unset'].includes(verb)) return '-' + line.slice(1);
if (['set', 'create', 'add'].includes(verb)) return '+' + line.slice(1);
return line;
})
.join('\n');
const summary = changes === 0
? 'No changes — the environment already matches `.railway/`.'
: '**' + changes + (changes === 1 ? ' change' : ' changes') + '** will apply on merge.';
const lines = [
'<!-- railway-config-plan -->',
'### Railway config plan',
'',
summary,
];
if (changes > 0) {
lines.push('', '```diff', diff, '```');
}
if (plan.destructive) {
lines.push(
'',
'> [!WARNING]',
'> This plan contains **destructive operations**: resources or variables currently in the environment will be deleted when this pull request merges. Review the change set above before approving.'
);
}
lines.push(
'',
'<details>',
'<summary>Pinned plan — what merge will apply</summary>',
'',
'| | |',
'|---|---|',
'| `.railway/` tree | `' + plan.sourceTree + '` |',
'| Environment etag | `' + plan.configEtag + '` |',
'| Change-set hash | `' + plan.changeSetHash + '` |',
'| Environment | `' + plan.environmentId + '` |',
'| CLI | `' + plan.cliVersion + '` |',
'',
'Merge applies exactly this change set. If the environment moves or `.railway/` changes first, the apply fails and the PR needs a fresh plan.',
'',
'</details>',
'',
'<sub>Posted by <a href="https://github.com/railwayapp/config">railwayapp/config</a> · <a href="https://docs.railway.com/infrastructure-as-code">Railway Infrastructure as Code</a></sub>'
);
const body = lines.join('\n');
const { owner, repo } = context.repo;
const number = context.issue.number;
const { data: comments } = await github.rest.issues.listComments({
owner, repo, issue_number: number,
});
const existing = comments.find((c) => (c.body || '').includes('<!-- railway-config-plan -->'));
if (existing) {
await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
} else {
await github.rest.issues.createComment({ owner, repo, issue_number: number, body });
}
- name: Download pinned plan
if: inputs.command == 'apply'
shell: bash
env:
GH_TOKEN: ${{ inputs.github-token }}
run: |
set -euo pipefail
HEAD_SHA="$(jq -r '.pull_request.head.sha // empty' "$GITHUB_EVENT_PATH")"
if [ -z "$HEAD_SHA" ] && [ "$GITHUB_EVENT_NAME" = "push" ]; then
# Push-triggered apply (e.g. a separate workflow on the default branch):
# resolve the merged PR this commit came from to find its planned artifact.
HEAD_SHA="$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA/pulls" \
--jq '[.[] | select(.merged_at != null)] | first | .head.sha // empty')"
fi
if [ -z "$HEAD_SHA" ]; then
echo "apply needs a merged pull_request event, or a push of a commit that belongs to a merged PR." >&2
exit 1
fi
# Look the artifact up by name and the PR head SHA it was planned on,
# so the consumer's workflow name doesn't matter.
ARTIFACT_ID="$(gh api "repos/$GITHUB_REPOSITORY/actions/artifacts?name=${{ inputs.artifact-name }}&per_page=100" \
--jq "[.artifacts[] | select(.workflow_run.head_sha==\"$HEAD_SHA\" and .expired==false)] | sort_by(.created_at) | last | .id // empty")"
if [ -z "$ARTIFACT_ID" ]; then
echo "No ${{ inputs.artifact-name }} artifact found for $HEAD_SHA. Wait for the plan job, or re-open the PR to re-plan." >&2
exit 1
fi
gh api "repos/$GITHUB_REPOSITORY/actions/artifacts/$ARTIFACT_ID/zip" > /tmp/railway-plan-artifact.zip
unzip -o -d . /tmp/railway-plan-artifact.zip
- name: Apply pinned plan
if: inputs.command == 'apply'
shell: bash
env:
RAILWAY_TOKEN: ${{ inputs.railway-token }}
run: |
set -euo pipefail
FLAGS="--yes"
if [ "${{ inputs.confirm-destructive }}" = "true" ]; then
FLAGS="$FLAGS --confirm-destructive"
fi
railway config apply --plan "${{ inputs.plan-path }}" $FLAGS