@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
mdx 819 lines 25.4 KB
Raw
1 ---
2 title: CI
3 description: Set up CI/CD pipelines for alchemy projects with GitHub Actions, automated deployments, and PR previews — with provider credentials managed as code.
4 ---
5
6 import { Code, Steps, TabItem, Tabs } from "@astrojs/starlight/components";
7 import yaml from "yaml";
8
9 export function DeployWorkflow({ manager = "bun" }) {
10 const managers = {
11 bun: {
12 setup: [
13 {
14 name: "Setup Bun",
15 uses: "oven-sh/setup-bun@v2",
16 },
17 ],
18 install: "bun install",
19 run: "bun alchemy",
20 destroy: "bun alchemy",
21 },
22 npm: {
23 setup: [
24 {
25 name: "Setup Node.js",
26 uses: "actions/setup-node@v4",
27 with: {
28 "node-version": "24",
29 },
30 },
31 ],
32 install: "npm ci",
33 run: "npx alchemy",
34 destroy: "npx alchemy",
35 },
36 pnpm: {
37 setup: [
38 {
39 name: "Setup pnpm",
40 uses: "pnpm/action-setup@v4",
41 with: {
42 version: "10",
43 run_install: false,
44 },
45 },
46 {
47 name: "Setup Node.js",
48 uses: "actions/setup-node@v4",
49 with: {
50 "node-version": "24",
51 cache: "pnpm",
52 },
53 },
54 ],
55 install: "pnpm install",
56 run: "pnpm dlx alchemy",
57 destroy: "pnpm dlx alchemy",
58 },
59 yarn: {
60 setup: [
61 {
62 name: "Setup Node.js",
63 uses: "actions/setup-node@v4",
64 with: {
65 "node-version": "24",
66 cache: "yarn",
67 },
68 },
69 {
70 name: "Install yarn",
71 run: "npm install -g yarn",
72 },
73 ],
74 install: "yarn install",
75 run: "yarn dlx alchemy",
76 destroy: "yarn dlx alchemy",
77 },
78 };
79
80 const cfg = managers[manager] || managers.bun;
81
82 const content = yaml.stringify({
83 name: "Deploy Application",
84 on: {
85 push: {
86 branches: ["main"],
87 },
88 pull_request: {
89 types: ["opened", "reopened", "synchronize", "closed"],
90 },
91 },
92 concurrency: {
93 group: "deploy-${{ github.ref }}",
94 "cancel-in-progress": false,
95 },
96 env: {
97 STAGE:
98 "${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.number) || (github.ref == 'refs/heads/main' && 'prod' || github.ref_name) }}",
99 },
100 jobs: {
101 deploy: {
102 if: "${{ github.event.action != 'closed' }}",
103 "runs-on": "ubuntu-latest",
104 permissions: {
105 contents: "read",
106 "pull-requests": "write",
107 },
108 steps: [
109 {
110 uses: "actions/checkout@v4",
111 },
112 ...cfg.setup,
113 {
114 name: "Install dependencies",
115 run: cfg.install,
116 },
117 {
118 name: "Deploy",
119 run: `${cfg.run} deploy --stage \${{ env.STAGE }}`,
120 env: {
121 PULL_REQUEST: "${{ github.event.number }}",
122 GITHUB_SHA: "${{ github.sha }}",
123 GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}",
124 },
125 },
126 ],
127 },
128 cleanup: {
129 "runs-on": "ubuntu-latest",
130 if: "${{ github.event_name == 'pull_request' && github.event.action == 'closed' }}",
131 permissions: {
132 contents: "read",
133 "pull-requests": "write",
134 },
135 steps: [
136 {
137 uses: "actions/checkout@v4",
138 },
139 ...cfg.setup,
140 {
141 name: "Install dependencies",
142 run: cfg.install,
143 },
144 {
145 name: "Safety Check",
146 run: `if [ "\${{ env.STAGE }}" = "prod" ]; then
147 echo "ERROR: Cannot destroy prod environment in cleanup job"
148 exit 1
149 fi`,
150 },
151 {
152 name: "Destroy Preview Environment",
153 run: `${cfg.destroy} destroy --stage \${{ env.STAGE }}`,
154 env: {
155 PULL_REQUEST: "${{ github.event.number }}",
156 },
157 },
158 ],
159 },
160 },
161 }, { aliasDuplicateObjects: false });
162
163 return <Code lang="yaml" code={content} />;
164 }
165
166 The core idea is **credentials as code**. Rather than copy-paste
167 API keys into the GitHub UI, you let Alchemy provision exactly the
168 credentials your CI needs — a scoped Cloudflare API token, an AWS
169 IAM role for OIDC, etc. — and write them straight into the repo as
170 encrypted secrets.
171
172 ## Preflight: verify the environment
173
174 Every auth provider declares the environment variables its CI resolution
175 consumes, and `alchemy provider check-env` validates them against that
176 contract. It prints one line per registered provider and exits with code 1
177 when a required variable is missing:
178
179 ```sh
180 $ bun alchemy provider check-env
181 ok Cloudflare
182 MISSING AWS: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION | AWS_DEFAULT_REGION
183 ```
184
185 Run it as the first step of a deploy job to fail fast with a list of
186 missing secrets instead of failing minutes later inside a provider API
187 call. `--provider <name>` (repeatable) checks a subset; `--env-file`
188 includes a dotenv file in resolution.
189
190 ## How PR previews work
191
192 Open a PR. Alchemy does the rest.
193
194 1. **A pull request is opened.** GitHub fires `pull_request`. The
195 workflow computes `STAGE = pr-{number}` and runs the deploy job.
196 2. **Alchemy deploys the stack to that stage.** An isolated copy of
197 every resource — Workers, Lambdas, queues, tables.
198 [Stage state lives separately](/environments/stages), so PRs can't
199 touch each other or prod.
200 3. **A bot comment is posted (or updated) on the PR.** The
201 `GitHub.Comment` resource keeps its logical id stable, so the
202 comment updates in place on each push.
203 4. **PR is merged or closed → cleanup runs.** A second job runs
204 `alchemy destroy --stage pr-{n}`. Resources gone. Costs gone.
205
206 ## What we'll build
207
208 By the end you'll have:
209
210 1. A GitHub Actions workflow (`.github/workflows/deploy.yml`) with
211 PR previews, prod deploys, and automatic cleanup.
212 2. A `stacks/github.ts` that creates provider credentials and writes
213 them to your repo as `GitHub.Secret` / `GitHub.Variable`.
214 3. A PR-comment resource in your `alchemy.run.ts` that posts the
215 preview URL on each push.
216
217 ## GitHub Actions Workflow
218
219 <Steps>
220
221 1. **Add preview comments to your stack**
222
223 Update your `alchemy.run.ts` to post a preview URL on each pull
224 request. The comment auto-updates on every push because the
225 logical ID stays the same.
226
227 ```diff lang="typescript"
228 import * as Alchemy from "alchemy";
229 +import * as GitHub from "@alchemy.run/github";
230 +import * as Output from "alchemy/Output";
231 import * as Effect from "effect/Effect";
232
233 export default Alchemy.Stack(
234 "my-app",
235 { providers: Layer.mergeAll(GitHub.providers(), Cloudflare.providers()) },
236 Effect.gen(function* () {
237 const app = yield* App;
238 + const github = yield* GitHub.GitHubEnv;
239
240 + if (github?.pr) {
241 + yield* GitHub.Comment("preview-comment", {
242 + owner: github.owner,
243 + repository: github.repository,
244 + issueNumber: github.pr,
245 + body: Output.interpolate`
246 + ## Preview Deployed
247 +
248 + **URL:** ${app.url}
249 +
250 + Built from commit ${github.sha.slice(0, 7)}
251 +
252 + ---
253 + _This comment updates automatically with each push._
254 + `,
255 + });
256 + }
257
258 return { url: app.url };
259 }),
260 );
261 ```
262
263 2. **Create the base deployment workflow**
264
265 Create `.github/workflows/deploy.yml`. This workflow deploys `prod` on
266 pushes to `main` and a `pr-<number>` stage for each pull request. When a
267 PR is closed the preview environment is destroyed automatically.
268
269 <Tabs syncKey="pkgManager">
270 <TabItem label="pnpm">
271 <DeployWorkflow manager="pnpm" />
272 </TabItem>
273 <TabItem label="bun">
274 <DeployWorkflow manager="bun" />
275 </TabItem>
276 <TabItem label="npm">
277 <DeployWorkflow manager="npm" />
278 </TabItem>
279 <TabItem label="yarn">
280 <DeployWorkflow manager="yarn" />
281 </TabItem>
282 </Tabs>
283
284 :::note[STAGE Variable Logic]
285 The `STAGE` environment variable is computed from the GitHub event:
286
287 ```yaml
288 env:
289 STAGE: ${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.number) || (github.ref == 'refs/heads/main' && 'prod' || github.ref_name) }}
290 ```
291
292 - Pull request events → `pr-{number}`
293 - Pushes to `main` → `prod`
294 - Other branches → the branch name
295
296 The cleanup job includes a safety check to prevent accidental destruction
297 of the production environment.
298 :::
299
300 3. **Add provider credentials**
301
302 The base workflow above doesn't include any provider credentials yet.
303 Pick the section below that matches your provider and apply the changes
304 to your workflow.
305
306 `GITHUB_TOKEN` is provided automatically by GitHub Actions and is used
307 by the `GitHub.Comment` resource to post PR comments.
308
309 </Steps>
310
311 ## The GitHub Stack
312
313 Before CI can deploy, your repo needs provider credentials configured
314 as Actions secrets and variables. We recommend managing this with a
315 dedicated `stacks/github.ts` that you deploy once locally — that way
316 the credential set is reviewable, diffable, and reproducible.
317
318 The stack uses `GitHub.Secret` and `GitHub.Variable` to write into
319 your repository, and provider resources like
320 `Cloudflare.ApiToken.AccountApiToken` or `AWS.IAM.Role` to mint the
321 credentials themselves.
322
323 ### Set up an `admin` profile
324
325 The `stacks/github.ts` you're about to write needs more privilege
326 than your day-to-day app stack. Creating a Cloudflare API token
327 requires `API Tokens > Write`; creating an IAM role and OIDC
328 provider requires IAM admin rights.
329
330 Rather than hand those rights to your default
331 [profile](/environments/profiles), create a separate `admin` profile:
332
333 ```sh
334 alchemy profile create admin
335 alchemy profile edit --profile admin
336 ```
337
338 For Cloudflare, choose **API Token or API Key** when asked for the
339 authentication method, not the recommended OAuth: Cloudflare's OAuth
340 scopes can't manage API tokens, so an OAuth `admin` profile fails
341 when `stacks/github.ts` creates the CI token. See
342 [required Cloudflare permissions](#cloudflare) for which key or token
343 to use.
344
345 :::danger[Heads up]
346 The credentials stored under `--profile admin` can mint new tokens
347 and roles with arbitrary scope. Treat it like root. Use it only
348 when deploying `stacks/github.ts`, and keep your default profile
349 on a narrowly scoped credential (OAuth, a scoped API token, or
350 OIDC) for everyday `alchemy deploy` runs.
351 :::
352
353 After creating the file, deploy it once locally under the admin
354 profile:
355
356 ```sh
357 alchemy deploy --config stacks/github.ts --profile admin
358 ```
359
360 You only need to re-run this stack when you want to rotate
361 credentials or change permissions.
362
363 ## Cloudflare
364
365 The simplest case: a single Cloudflare account, used for both prod
366 and PR previews. Your `admin` profile mints a scoped API token, and
367 the stack pushes it into your repo as a GitHub Actions secret.
368
369 :::caution[Required Cloudflare permissions]
370 The credential behind `--profile admin` must be allowed to create
371 API tokens. The two practical options are:
372
373 - The **Global API Key** (API Key + Email) — has full account
374 access, including token management.
375 - An **API Token** with at least `User > API Tokens > Write` (for
376 user-owned tokens) **and** `Account > API Tokens > Write` for the
377 target account.
378
379 A standard "Edit Cloudflare Workers" token is **not** enough — it
380 can deploy Workers but cannot mint other tokens. Use the Global API
381 Key for `--profile admin` unless you've explicitly configured a
382 token-management token.
383 :::
384
385 ```typescript
386 // stacks/github.ts
387 import * as Alchemy from "alchemy";
388 import * as Cloudflare from "@alchemy.run/cloudflare";
389 import * as GitHub from "@alchemy.run/github";
390 import * as Effect from "effect/Effect";
391 import * as Layer from "effect/Layer";
392 import * as Redacted from "effect/Redacted";
393
394 export default Alchemy.Stack(
395 "github",
396 {
397 providers: Layer.mergeAll(
398 Cloudflare.providers(),
399 GitHub.providers(),
400 ),
401 state: Cloudflare.state(),
402 },
403 Effect.gen(function* () {
404 const { accountId } = yield* yield* Cloudflare.CloudflareEnvironment;
405
406 const apiToken = yield* Cloudflare.ApiToken.AccountApiToken("CIToken", {
407 accountId,
408 policies: [
409 {
410 effect: "allow",
411 permissionGroups: [
412 "Workers Scripts Write",
413 "Workers KV Storage Write",
414 "Workers R2 Storage Write",
415 "D1 Write",
416 "Queues Write",
417 "Pages Write",
418 "Account Settings Write",
419 "Secrets Store Write",
420 "Workers Tail Read",
421 ],
422 resources: {
423 [`com.cloudflare.api.account.${accountId}`]: "*",
424 },
425 },
426 ],
427 });
428
429 yield* GitHub.Secret("cf-api-token", {
430 owner: "your-org",
431 repository: "your-repo",
432 name: "CLOUDFLARE_API_TOKEN",
433 value: apiToken.value,
434 });
435
436 yield* GitHub.Secret("cf-account-id", {
437 owner: "your-org",
438 repository: "your-repo",
439 name: "CLOUDFLARE_ACCOUNT_ID",
440 value: Redacted.make(accountId),
441 });
442 }),
443 );
444 ```
445
446 A few details worth knowing:
447
448 - `Cloudflare.CloudflareEnvironment` resolves the credentials of the
449 profile you're deploying with, account ID included — no
450 `CLOUDFLARE_ACCOUNT_ID` env var needed for this local deploy. The
451 double `yield*` is because the service's value is itself an Effect:
452 credentials are cached and can refresh themselves (OAuth tokens
453 expire), so you yield once for the service and once to resolve the
454 current credentials.
455 - `Cloudflare.ApiToken.AccountApiToken` calls
456 `POST /accounts/{account_id}/tokens` and Cloudflare returns the
457 freshly minted token value exactly once. Alchemy captures it,
458 stores it in state, and pipes it straight into `GitHub.Secret` —
459 the raw token never appears in your terminal or in CI logs.
460 - Trim the `permissionGroups` list to just what your app needs.
461 Listed above is a sensible default for a Workers + KV + R2 + D1
462 app.
463 - The resource diff is stable across redeploys. Editing a policy
464 produces a clean update against the same token ID.
465
466 :::note[Why `Secrets Store Write`?]
467 `Cloudflare.state()` keeps the state-store worker's bearer token in
468 the account-wide [Cloudflare Secrets Store](https://developers.cloudflare.com/secrets-store/).
469 On every CI run Alchemy reads that secret back by uploading a
470 short-lived edge-preview worker that *binds* the secret — and
471 binding a Secrets Store secret to a worker (even an ephemeral
472 preview) requires the **`Secrets Store Write`** permission, not
473 just `Read`. `Read` is only enough to enumerate the store via
474 `GET /accounts/{id}/secrets_store/stores`; the
475 `POST .../scripts/{name}/edge-preview` call that mounts the
476 binding is rejected without `Write`.
477 :::
478
479 Then add the secrets to your workflow's deploy and cleanup steps:
480
481 ```diff lang="yaml"
482 - name: Deploy
483 run: bun alchemy deploy --stage ${{ env.STAGE }}
484 env:
485 + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
486 + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
487 PULL_REQUEST: ${{ github.event.number }}
488 GITHUB_SHA: ${{ github.sha }}
489 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
490 ```
491
492 ```diff lang="yaml"
493 - name: Destroy Preview Environment
494 run: bun alchemy destroy --stage ${{ env.STAGE }}
495 env:
496 + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
497 + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
498 PULL_REQUEST: ${{ github.event.number }}
499 ```
500
501 ### Optional: separate test and prod accounts
502
503 For stricter isolation you can run preview environments on one
504 Cloudflare account and production on another. Mint two tokens from
505 the same `stacks/github.ts` and prefix the secrets so the workflow
506 can pick the right pair based on `STAGE`.
507
508 Your profile resolves a single account ID, so this is the one case
509 where you pass the account IDs in explicitly — set
510 `TEST_CLOUDFLARE_ACCOUNT_ID` and `PROD_CLOUDFLARE_ACCOUNT_ID` in
511 your environment when deploying this stack.
512
513 ```typescript
514 // stacks/github.ts
515 import * as Alchemy from "alchemy";
516 import * as Cloudflare from "@alchemy.run/cloudflare";
517 import * as GitHub from "@alchemy.run/github";
518 import * as Config from "effect/Config";
519 import * as Effect from "effect/Effect";
520 import * as Layer from "effect/Layer";
521 import * as Redacted from "effect/Redacted";
522
523 export default Alchemy.Stack(
524 "github",
525 {
526 providers: Layer.mergeAll(
527 Cloudflare.providers(),
528 GitHub.providers(),
529 ),
530 state: Cloudflare.state(),
531 },
532 Effect.gen(function* () {
533 const testAccountId = yield* Config.String("TEST_CLOUDFLARE_ACCOUNT_ID");
534 const prodAccountId = yield* Config.String("PROD_CLOUDFLARE_ACCOUNT_ID");
535
536 const policies = (accountId: string) => [
537 {
538 effect: "allow" as const,
539 permissionGroups: [
540 "Workers Scripts Write",
541 "Workers KV Storage Write",
542 "Workers R2 Storage Write",
543 "D1 Write",
544 "Queues Write",
545 "Pages Write",
546 "Account Settings Write",
547 "Secrets Store Write",
548 "Workers Tail Read",
549 ],
550 resources: { [`com.cloudflare.api.account.${accountId}`]: "*" },
551 },
552 ];
553
554 const testToken = yield* Cloudflare.ApiToken.AccountApiToken("TestApiToken", {
555 accountId: testAccountId,
556 policies: policies(testAccountId),
557 });
558
559 const prodToken = yield* Cloudflare.ApiToken.AccountApiToken("ProdApiToken", {
560 accountId: prodAccountId,
561 policies: policies(prodAccountId),
562 });
563
564 const secrets: Record<string, Redacted.Redacted<string>> = {
565 TEST_CLOUDFLARE_API_TOKEN: testToken.value,
566 TEST_CLOUDFLARE_ACCOUNT_ID: Redacted.make(testAccountId),
567 PROD_CLOUDFLARE_API_TOKEN: prodToken.value,
568 PROD_CLOUDFLARE_ACCOUNT_ID: Redacted.make(prodAccountId),
569 };
570
571 yield* Effect.all(
572 Object.entries(secrets).map(([name, value]) =>
573 GitHub.Secret(name, {
574 owner: "your-org",
575 repository: "your-repo",
576 name,
577 value,
578 }),
579 ),
580 );
581 }),
582 );
583 ```
584
585 Your `admin` profile needs API-token-write permission on **both**
586 accounts. The simplest setup is to log in with the Global API Key of
587 a user that's a member of both.
588
589 In your workflow, switch on `STAGE` to choose the right credential
590 pair:
591
592 ```diff lang="yaml"
593 - name: Deploy
594 run: bun alchemy deploy --stage ${{ env.STAGE }}
595 env:
596 + CLOUDFLARE_API_TOKEN: ${{ env.STAGE == 'prod' && secrets.PROD_CLOUDFLARE_API_TOKEN || secrets.TEST_CLOUDFLARE_API_TOKEN }}
597 + CLOUDFLARE_ACCOUNT_ID: ${{ env.STAGE == 'prod' && secrets.PROD_CLOUDFLARE_ACCOUNT_ID || secrets.TEST_CLOUDFLARE_ACCOUNT_ID }}
598 PULL_REQUEST: ${{ github.event.number }}
599 GITHUB_SHA: ${{ github.sha }}
600 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
601 ```
602
603 ## AWS with GitHub OIDC (recommended)
604
605 GitHub OIDC lets your workflow assume an IAM role without storing
606 long-lived access keys. The GitHub stack creates the OIDC provider
607 and an IAM role scoped to your repo, then writes the role ARN and
608 region to the repo as Actions **variables** (not secrets — they're
609 not sensitive).
610
611 Your `--profile admin` AWS credentials need IAM admin rights for
612 this stack: it creates an `OpenIDConnectProvider` and an IAM `Role`.
613 Run `alchemy profile edit --profile admin --add AWS` and choose a credential
614 (SSO/OIDC, access keys, etc.) that's authorized for IAM
615 administration.
616
617 ```typescript
618 // stacks/github.ts
619 import * as Alchemy from "alchemy";
620 import * as AWS from "@alchemy.run/aws";
621 import * as GitHub from "@alchemy.run/github";
622 import * as Effect from "effect/Effect";
623 import * as Layer from "effect/Layer";
624
625 export default Alchemy.Stack(
626 "github",
627 {
628 providers: Layer.mergeAll(
629 AWS.providers(),
630 GitHub.providers(),
631 ),
632 },
633 Effect.gen(function* () {
634 const oidc = yield* AWS.IAM.OpenIDConnectProvider("GitHubOidc", {
635 url: "https://token.actions.githubusercontent.com",
636 clientIDList: ["sts.amazonaws.com"],
637 // GitHub's well-known OIDC thumbprint. AWS auto-discovers
638 // thumbprints for github.com these days, but the provider's
639 // thumbprint sync still requires a non-empty list.
640 // https://aws.amazon.com/blogs/security/use-iam-roles-to-connect-github-actions-to-actions-in-aws/
641 thumbprintList: ["6938fd4d98bab03faadb97b34396831e3780aea1"],
642 });
643
644 const role = yield* AWS.IAM.Role("GitHubActionsRole", {
645 roleName: "github-actions",
646 assumeRolePolicyDocument: {
647 Version: "2012-10-17",
648 Statement: [
649 {
650 Effect: "Allow",
651 Principal: {
652 Federated: oidc.openIDConnectProviderArn,
653 },
654 Action: ["sts:AssumeRoleWithWebIdentity"],
655 Condition: {
656 StringEquals: {
657 "token.actions.githubusercontent.com:aud":
658 "sts.amazonaws.com",
659 },
660 StringLike: {
661 "token.actions.githubusercontent.com:sub":
662 "repo:your-org/your-repo:*",
663 },
664 },
665 },
666 ],
667 },
668 managedPolicyArns: [
669 "arn:aws:iam::aws:policy/AdministratorAccess",
670 ],
671 });
672
673 const region = yield* AWS.Region;
674
675 yield* GitHub.Variable("aws-role-arn", {
676 owner: "your-org",
677 repository: "your-repo",
678 name: "AWS_ROLE_ARN",
679 value: role.roleArn,
680 });
681
682 yield* GitHub.Variable("aws-region", {
683 owner: "your-org",
684 repository: "your-repo",
685 name: "AWS_REGION",
686 value: region,
687 });
688 }),
689 );
690 ```
691
692 :::tip[Tighten the role]
693 `AdministratorAccess` is the path of least resistance for getting
694 CI working, but for production you should swap it for a
695 custom-managed policy that grants only the actions your app needs
696 (for example, `lambda:*`, `dynamodb:*`, and the bucket actions
697 you use). The `assumeRolePolicyDocument` already restricts who can
698 assume the role to your specific repo via the `sub` condition.
699 :::
700
701 After deploying, update the workflow to add `id-token: write` and
702 the `configure-aws-credentials` step. No secrets needed:
703
704 ```diff lang="yaml"
705 deploy:
706 permissions:
707 + id-token: write
708 contents: read
709 pull-requests: write
710 steps:
711 - uses: actions/checkout@v4
712 # ...setup and install...
713 + - name: Configure AWS credentials
714 + uses: aws-actions/configure-aws-credentials@v4
715 + with:
716 + role-to-assume: ${{ vars.AWS_ROLE_ARN }}
717 + aws-region: ${{ vars.AWS_REGION }}
718 - name: Deploy
719 run: bun alchemy deploy --stage ${{ env.STAGE }}
720 ```
721
722 ```diff lang="yaml"
723 cleanup:
724 permissions:
725 + id-token: write
726 contents: read
727 pull-requests: write
728 steps:
729 - uses: actions/checkout@v4
730 # ...setup, install, and safety check...
731 + - name: Configure AWS credentials
732 + uses: aws-actions/configure-aws-credentials@v4
733 + with:
734 + role-to-assume: ${{ vars.AWS_ROLE_ARN }}
735 + aws-region: ${{ vars.AWS_REGION }}
736 - name: Destroy Preview Environment
737 run: bun alchemy destroy --stage ${{ env.STAGE }}
738 ```
739
740 ## AWS with access keys
741
742 If OIDC isn't an option (some sandbox accounts disallow it, or
743 you're targeting an account you don't fully control), fall back to
744 static IAM access keys stored as repo secrets. The stack pushes
745 existing keys from your environment into the repo — it does **not**
746 mint a new IAM user, since most teams prefer to do that step in the
747 AWS console.
748
749 ```typescript
750 // stacks/github.ts
751 import * as Alchemy from "alchemy";
752 import * as GitHub from "@alchemy.run/github";
753 import * as Config from "effect/Config";
754 import * as Effect from "effect/Effect";
755 import * as Redacted from "effect/Redacted";
756
757 export default Alchemy.Stack(
758 "github",
759 {
760 providers: GitHub.providers(),
761 },
762 Effect.gen(function* () {
763 const accessKeyId = yield* Config.String("AWS_ACCESS_KEY_ID");
764 const secretAccessKey = yield* Config.Redacted("AWS_SECRET_ACCESS_KEY");
765
766 yield* GitHub.Secret("aws-access-key-id", {
767 owner: "your-org",
768 repository: "your-repo",
769 name: "AWS_ACCESS_KEY_ID",
770 value: Redacted.make(accessKeyId),
771 });
772
773 yield* GitHub.Secret("aws-secret-access-key", {
774 owner: "your-org",
775 repository: "your-repo",
776 name: "AWS_SECRET_ACCESS_KEY",
777 value: secretAccessKey,
778 });
779
780 yield* GitHub.Variable("aws-region", {
781 owner: "your-org",
782 repository: "your-repo",
783 name: "AWS_REGION",
784 value: "us-east-1",
785 });
786 }),
787 );
788 ```
789
790 Then add the secrets to your workflow's deploy and cleanup steps:
791
792 ```diff lang="yaml"
793 - name: Deploy
794 run: bun alchemy deploy --stage ${{ env.STAGE }}
795 env:
796 + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
797 + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
798 + AWS_REGION: ${{ vars.AWS_REGION || 'us-east-1' }}
799 PULL_REQUEST: ${{ github.event.number }}
800 GITHUB_SHA: ${{ github.sha }}
801 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
802 ```
803
804 ```diff lang="yaml"
805 - name: Destroy Preview Environment
806 run: bun alchemy destroy --stage ${{ env.STAGE }}
807 env:
808 + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
809 + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
810 + AWS_REGION: ${{ vars.AWS_REGION || 'us-east-1' }}
811 PULL_REQUEST: ${{ github.event.number }}
812 ```
813
814 ## Where next
815
816 - [Stages](/environments/stages) — how `pr-42` and `prod` stay isolated.
817 - [Profiles](/environments/profiles) documents local credentials and the CI environment-variable matrix.
818 - [Secrets & env on Cloudflare](/cloudflare/security/secrets-env) — wire app secrets into a Worker.
819 - [Secrets & env on AWS](/aws/security/secrets-env) — the same walk for Lambda.