The best way to control Claude Code, Codex and more from any computer or phone
| 1 | #!/usr/bin/env bun |
| 2 | |
| 3 | // @ts-nocheck |
| 4 | |
| 5 | import { parseArgs } from "node:util"; |
| 6 | import * as Credentials from "@distilled.cloud/aws/Credentials"; |
| 7 | import * as ec2 from "@distilled.cloud/aws/ec2"; |
| 8 | import { Region } from "@distilled.cloud/aws/Region"; |
| 9 | import { NodeServices } from "@effect/platform-node"; |
| 10 | import * as Data from "effect/Data"; |
| 11 | import * as Effect from "effect/Effect"; |
| 12 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 13 | import * as Layer from "effect/Layer"; |
| 14 | |
| 15 | export class CleanAwsNotReady extends Data.TaggedError("CleanAwsNotReady")<{ |
| 16 | readonly message: string; |
| 17 | readonly cause?: unknown; |
| 18 | }> {} |
| 19 | |
| 20 | const { values } = parseArgs({ |
| 21 | args: Bun.argv.slice(2), |
| 22 | options: { |
| 23 | region: { type: "string", short: "r" }, |
| 24 | profile: { type: "string", short: "p" }, |
| 25 | execute: { type: "boolean" }, |
| 26 | "include-default-vpcs": { type: "boolean" }, |
| 27 | passes: { type: "string" }, |
| 28 | help: { type: "boolean", short: "h" }, |
| 29 | }, |
| 30 | strict: true, |
| 31 | }); |
| 32 | |
| 33 | const usage = ` |
| 34 | Best-effort EC2 regional cleanup using @distilled.cloud/aws. |
| 35 | |
| 36 | Usage: |
| 37 | bun alchemy/scripts/clean-aws.ts --region us-east-1 [--profile dev] |
| 38 | bun alchemy/scripts/clean-aws.ts --region us-east-1 --execute |
| 39 | |
| 40 | Options: |
| 41 | --region, -r AWS region to clean |
| 42 | --profile, -p Optional AWS profile |
| 43 | --execute Perform deletions (default is dry-run) |
| 44 | --include-default-vpcs Also attempt to delete default VPC resources |
| 45 | --passes Cleanup passes to run (default: 1 dry-run, 4 execute) |
| 46 | --help, -h Show this help |
| 47 | `; |
| 48 | |
| 49 | if (values.help) { |
| 50 | console.log(usage.trim()); |
| 51 | process.exit(0); |
| 52 | } |
| 53 | |
| 54 | const region = values.region ?? process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION; |
| 55 | if (!region) { |
| 56 | console.error("Missing --region. Set it explicitly or via AWS_REGION."); |
| 57 | console.error(usage.trim()); |
| 58 | process.exit(1); |
| 59 | } |
| 60 | |
| 61 | if (values.profile) { |
| 62 | process.env.AWS_PROFILE = values.profile; |
| 63 | } |
| 64 | |
| 65 | const execute = values.execute ?? false; |
| 66 | const includeDefaultVpcs = values["include-default-vpcs"] ?? false; |
| 67 | const maxPasses = Number(values.passes ?? (execute ? "4" : "1")); |
| 68 | |
| 69 | if (!Number.isFinite(maxPasses) || maxPasses < 1) { |
| 70 | console.error("--passes must be a positive integer."); |
| 71 | process.exit(1); |
| 72 | } |
| 73 | |
| 74 | const credentialsLayer = values.profile |
| 75 | ? Layer.provideMerge( |
| 76 | Credentials.fromSSO(values.profile), |
| 77 | Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer), |
| 78 | ) |
| 79 | : Credentials.fromChain(); |
| 80 | |
| 81 | const runtime = Layer.mergeAll( |
| 82 | NodeServices.layer, |
| 83 | FetchHttpClient.layer, |
| 84 | credentialsLayer, |
| 85 | Layer.succeed(Region, region), |
| 86 | ); |
| 87 | |
| 88 | const formatError = (error: unknown) => { |
| 89 | if (typeof error === "object" && error && "_tag" in error) { |
| 90 | const tagged = error as { _tag: string; message?: string }; |
| 91 | return tagged.message ? `${tagged._tag}: ${tagged.message}` : tagged._tag; |
| 92 | } |
| 93 | if (error instanceof Error) { |
| 94 | return error.message; |
| 95 | } |
| 96 | try { |
| 97 | return JSON.stringify(error); |
| 98 | } catch { |
| 99 | return String(error); |
| 100 | } |
| 101 | }; |
| 102 | |
| 103 | const log = (message: string) => Effect.sync(() => console.log(message)); |
| 104 | const warn = (message: string) => Effect.sync(() => console.warn(message)); |
| 105 | |
| 106 | const isNotFoundError = (error: unknown) => |
| 107 | typeof error === "object" && |
| 108 | error !== null && |
| 109 | "_tag" in error && |
| 110 | String((error as { _tag: string })._tag).includes("NotFound"); |
| 111 | |
| 112 | const uniq = <T>(items: ReadonlyArray<T | null | undefined>) => [ |
| 113 | ...new Set(items.filter((item): item is T => item !== null && item !== undefined)), |
| 114 | ]; |
| 115 | |
| 116 | const chunk = <T>(items: ReadonlyArray<T>, size: number) => { |
| 117 | const groups: T[][] = []; |
| 118 | for (let index = 0; index < items.length; index += size) { |
| 119 | groups.push(items.slice(index, index + size)); |
| 120 | } |
| 121 | return groups; |
| 122 | }; |
| 123 | |
| 124 | const preview = (label: string, ids: ReadonlyArray<string>) => |
| 125 | ids.length === 0 ? Effect.void : log(`Found ${ids.length} ${label}: ${ids.join(", ")}`); |
| 126 | |
| 127 | const ignoreFailure = <A, E, R>( |
| 128 | label: string, |
| 129 | effect: Effect.Effect<A, E, R>, |
| 130 | ): Effect.Effect<void, E, R> => |
| 131 | effect.pipe( |
| 132 | Effect.asVoid, |
| 133 | Effect.catch((error) => |
| 134 | isNotFoundError(error) |
| 135 | ? warn(`Already gone ${label}: ${formatError(error)}`) |
| 136 | : Effect.fail(error as E), |
| 137 | ), |
| 138 | ); |
| 139 | |
| 140 | const deleteEach = <R>( |
| 141 | label: string, |
| 142 | ids: ReadonlyArray<string>, |
| 143 | remove: (id: string) => Effect.Effect<any, any, R>, |
| 144 | ) => |
| 145 | Effect.gen(function* () { |
| 146 | if (ids.length === 0) { |
| 147 | return; |
| 148 | } |
| 149 | |
| 150 | yield* preview(label, ids); |
| 151 | if (!execute) { |
| 152 | return; |
| 153 | } |
| 154 | |
| 155 | yield* Effect.forEach(ids, (id) => ignoreFailure(`${label} ${id}`, remove(id)), { |
| 156 | concurrency: 1, |
| 157 | discard: true, |
| 158 | }); |
| 159 | }); |
| 160 | |
| 161 | const repeatUntil = <A, E, R>( |
| 162 | label: string, |
| 163 | effect: Effect.Effect<A, E, R>, |
| 164 | done: (value: A) => boolean, |
| 165 | attempts: number, |
| 166 | delayMs: number, |
| 167 | ): Effect.Effect<void, E, R> => |
| 168 | Effect.gen(function* () { |
| 169 | const value = yield* effect; |
| 170 | if (done(value)) { |
| 171 | return; |
| 172 | } |
| 173 | if (attempts <= 1) { |
| 174 | yield* warn(`Timed out waiting for ${label}.`); |
| 175 | return; |
| 176 | } |
| 177 | yield* log(`Waiting for ${label}...`); |
| 178 | yield* Effect.sleep(delayMs); |
| 179 | yield* repeatUntil(label, effect, done, attempts - 1, delayMs); |
| 180 | }); |
| 181 | |
| 182 | const terminateInstances = Effect.gen(function* () { |
| 183 | const response = yield* ec2.describeInstances({} as any); |
| 184 | const ids = uniq( |
| 185 | (response.Reservations ?? []).flatMap((reservation: any) => |
| 186 | (reservation.Instances ?? []) |
| 187 | .filter((instance: any) => { |
| 188 | const state = instance.State?.Name; |
| 189 | return state !== "shutting-down" && state !== "terminated"; |
| 190 | }) |
| 191 | .map((instance: any) => instance.InstanceId), |
| 192 | ), |
| 193 | ); |
| 194 | |
| 195 | if (ids.length === 0) { |
| 196 | return; |
| 197 | } |
| 198 | |
| 199 | yield* preview("instance(s)", ids); |
| 200 | if (!execute) { |
| 201 | return; |
| 202 | } |
| 203 | |
| 204 | for (const group of chunk(ids, 100)) { |
| 205 | yield* ignoreFailure( |
| 206 | `instances ${group.join(", ")}`, |
| 207 | ec2.terminateInstances({ InstanceIds: group } as any), |
| 208 | ); |
| 209 | } |
| 210 | |
| 211 | yield* repeatUntil( |
| 212 | "instances to terminate", |
| 213 | ec2 |
| 214 | .describeInstances({} as any) |
| 215 | .pipe( |
| 216 | Effect.map((result) => |
| 217 | uniq( |
| 218 | (result.Reservations ?? []).flatMap((reservation: any) => |
| 219 | (reservation.Instances ?? []) |
| 220 | .filter((instance: any) => ids.includes(instance.InstanceId)) |
| 221 | .map((instance: any) => instance.State?.Name), |
| 222 | ), |
| 223 | ), |
| 224 | ), |
| 225 | ), |
| 226 | (states) => states.every((state) => state === "terminated"), |
| 227 | 40, |
| 228 | 5_000, |
| 229 | ); |
| 230 | }); |
| 231 | |
| 232 | const deleteVpcEndpoints = Effect.gen(function* () { |
| 233 | const ids = uniq( |
| 234 | (yield* ec2.describeVpcEndpoints({} as any)).VpcEndpoints?.map( |
| 235 | (endpoint: any) => endpoint.VpcEndpointId, |
| 236 | ), |
| 237 | ); |
| 238 | |
| 239 | if (ids.length === 0) { |
| 240 | return; |
| 241 | } |
| 242 | |
| 243 | yield* preview("VPC endpoint(s)", ids); |
| 244 | if (!execute) { |
| 245 | return; |
| 246 | } |
| 247 | |
| 248 | for (const group of chunk(ids, 25)) { |
| 249 | yield* ignoreFailure( |
| 250 | `VPC endpoints ${group.join(", ")}`, |
| 251 | ec2.deleteVpcEndpoints({ VpcEndpointIds: group } as any), |
| 252 | ); |
| 253 | } |
| 254 | |
| 255 | yield* repeatUntil( |
| 256 | "VPC endpoints to delete", |
| 257 | ec2.describeVpcEndpoints({ VpcEndpointIds: ids } as any).pipe( |
| 258 | Effect.map((result) => |
| 259 | uniq((result.VpcEndpoints ?? []).map((endpoint: any) => endpoint.VpcEndpointId)), |
| 260 | ), |
| 261 | Effect.catch((error) => |
| 262 | isNotFoundError(error) ? Effect.succeed([] as string[]) : Effect.fail(error), |
| 263 | ), |
| 264 | ), |
| 265 | (remainingIds) => remainingIds.length === 0, |
| 266 | 30, |
| 267 | 5_000, |
| 268 | ); |
| 269 | }); |
| 270 | |
| 271 | const deleteNatGateways = Effect.gen(function* () { |
| 272 | const ids = uniq( |
| 273 | (yield* ec2.describeNatGateways({} as any)).NatGateways?.filter( |
| 274 | (natGateway: any) => natGateway.State !== "deleted", |
| 275 | ).map((natGateway: any) => natGateway.NatGatewayId), |
| 276 | ); |
| 277 | |
| 278 | if (ids.length === 0) { |
| 279 | return; |
| 280 | } |
| 281 | |
| 282 | yield* preview("NAT gateway(s)", ids); |
| 283 | if (!execute) { |
| 284 | return; |
| 285 | } |
| 286 | |
| 287 | yield* Effect.forEach( |
| 288 | ids, |
| 289 | (id) => |
| 290 | ignoreFailure(`NAT gateway ${String(id)}`, ec2.deleteNatGateway({ NatGatewayId: id } as any)), |
| 291 | { concurrency: 1, discard: true }, |
| 292 | ); |
| 293 | |
| 294 | yield* repeatUntil( |
| 295 | "NAT gateways to delete", |
| 296 | ec2 |
| 297 | .describeNatGateways({} as any) |
| 298 | .pipe( |
| 299 | Effect.map((result) => |
| 300 | uniq( |
| 301 | (result.NatGateways ?? []) |
| 302 | .filter((natGateway: any) => ids.includes(natGateway.NatGatewayId)) |
| 303 | .map((natGateway: any) => natGateway.State), |
| 304 | ), |
| 305 | ), |
| 306 | ), |
| 307 | (states) => states.every((state) => state === "deleted"), |
| 308 | 30, |
| 309 | 10_000, |
| 310 | ); |
| 311 | }); |
| 312 | |
| 313 | const deleteNetworkInterfaces = Effect.gen(function* () { |
| 314 | const interfaces = (yield* ec2.describeNetworkInterfaces({} as any)).NetworkInterfaces ?? []; |
| 315 | |
| 316 | const blocked = interfaces.filter( |
| 317 | (networkInterface: any) => |
| 318 | networkInterface.Attachment || |
| 319 | networkInterface.RequesterManaged || |
| 320 | networkInterface.Status !== "available", |
| 321 | ); |
| 322 | |
| 323 | if (blocked.length > 0) { |
| 324 | return yield* new CleanAwsNotReady({ |
| 325 | message: `Network interfaces still in use: ${blocked |
| 326 | .map( |
| 327 | (networkInterface: any) => |
| 328 | `${networkInterface.NetworkInterfaceId}(status=${networkInterface.Status ?? "unknown"}, requesterManaged=${networkInterface.RequesterManaged ?? false}, attachment=${networkInterface.Attachment?.AttachmentId ?? "none"})`, |
| 329 | ) |
| 330 | .join(", ")}`, |
| 331 | }); |
| 332 | } |
| 333 | |
| 334 | const ids = uniq(interfaces.map((networkInterface: any) => networkInterface.NetworkInterfaceId)); |
| 335 | |
| 336 | yield* deleteEach("network interface(s)", ids, (id) => |
| 337 | ec2.deleteNetworkInterface({ NetworkInterfaceId: id } as any), |
| 338 | ); |
| 339 | }); |
| 340 | |
| 341 | const releaseElasticIps = Effect.gen(function* () { |
| 342 | const addresses = (yield* ec2.describeAddresses({} as any)).Addresses ?? []; |
| 343 | const ids = uniq(addresses.map((address: any) => address.AllocationId ?? address.PublicIp)); |
| 344 | |
| 345 | if (ids.length === 0) { |
| 346 | return; |
| 347 | } |
| 348 | |
| 349 | yield* preview("elastic IP(s)", ids); |
| 350 | if (!execute) { |
| 351 | return; |
| 352 | } |
| 353 | |
| 354 | yield* Effect.forEach( |
| 355 | addresses, |
| 356 | (address: any) => |
| 357 | Effect.gen(function* () { |
| 358 | if (address.AssociationId) { |
| 359 | yield* ignoreFailure( |
| 360 | `elastic IP association ${address.AssociationId}`, |
| 361 | ec2.disassociateAddress({ |
| 362 | AssociationId: address.AssociationId, |
| 363 | } as any), |
| 364 | ); |
| 365 | } |
| 366 | yield* ignoreFailure( |
| 367 | `elastic IP ${address.AllocationId ?? address.PublicIp}`, |
| 368 | ec2.releaseAddress( |
| 369 | address.AllocationId |
| 370 | ? ({ AllocationId: address.AllocationId } as any) |
| 371 | : ({ PublicIp: address.PublicIp } as any), |
| 372 | ), |
| 373 | ); |
| 374 | }), |
| 375 | { concurrency: 1, discard: true }, |
| 376 | ); |
| 377 | }); |
| 378 | |
| 379 | const deleteVpcPeeringConnections = Effect.gen(function* () { |
| 380 | const ids = uniq( |
| 381 | (yield* ec2.describeVpcPeeringConnections({} as any)).VpcPeeringConnections?.filter( |
| 382 | (connection: any) => connection.Status?.Code !== "deleted", |
| 383 | ).map((connection: any) => connection.VpcPeeringConnectionId), |
| 384 | ); |
| 385 | |
| 386 | yield* deleteEach("VPC peering connection(s)", ids, (id) => |
| 387 | ec2.deleteVpcPeeringConnection({ VpcPeeringConnectionId: id } as any), |
| 388 | ); |
| 389 | }); |
| 390 | |
| 391 | const deleteVpnConnections = Effect.gen(function* () { |
| 392 | const ids = uniq( |
| 393 | (yield* ec2.describeVpnConnections({} as any)).VpnConnections?.filter( |
| 394 | (connection: any) => connection.State !== "deleted", |
| 395 | ).map((connection: any) => connection.VpnConnectionId), |
| 396 | ); |
| 397 | |
| 398 | yield* deleteEach("VPN connection(s)", ids, (id) => |
| 399 | ec2.deleteVpnConnection({ VpnConnectionId: id } as any), |
| 400 | ); |
| 401 | }); |
| 402 | |
| 403 | const deleteVpnGateways = Effect.gen(function* () { |
| 404 | const gateways = (yield* ec2.describeVpnGateways({} as any)).VpnGateways ?? []; |
| 405 | const ids = uniq( |
| 406 | gateways |
| 407 | .filter((gateway: any) => gateway.State !== "deleted") |
| 408 | .map((gateway: any) => gateway.VpnGatewayId), |
| 409 | ); |
| 410 | |
| 411 | if (ids.length === 0) { |
| 412 | return; |
| 413 | } |
| 414 | |
| 415 | yield* preview("VPN gateway(s)", ids); |
| 416 | if (!execute) { |
| 417 | return; |
| 418 | } |
| 419 | |
| 420 | yield* Effect.forEach( |
| 421 | gateways, |
| 422 | (gateway: any) => |
| 423 | Effect.gen(function* () { |
| 424 | for (const attachment of gateway.VpcAttachments ?? []) { |
| 425 | if (attachment.VpcId && attachment.State !== "detached") { |
| 426 | yield* ignoreFailure( |
| 427 | `VPN gateway attachment ${gateway.VpnGatewayId}`, |
| 428 | ec2.detachVpnGateway({ |
| 429 | VpcId: attachment.VpcId, |
| 430 | VpnGatewayId: gateway.VpnGatewayId, |
| 431 | } as any), |
| 432 | ); |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | yield* ignoreFailure( |
| 437 | `VPN gateway ${gateway.VpnGatewayId}`, |
| 438 | ec2.deleteVpnGateway({ VpnGatewayId: gateway.VpnGatewayId } as any), |
| 439 | ); |
| 440 | }), |
| 441 | { concurrency: 1, discard: true }, |
| 442 | ); |
| 443 | }); |
| 444 | |
| 445 | const deleteCustomerGateways = Effect.gen(function* () { |
| 446 | const ids = uniq( |
| 447 | (yield* ec2.describeCustomerGateways({} as any)).CustomerGateways?.map( |
| 448 | (gateway: any) => gateway.CustomerGatewayId, |
| 449 | ), |
| 450 | ); |
| 451 | |
| 452 | yield* deleteEach("customer gateway(s)", ids, (id) => |
| 453 | ec2.deleteCustomerGateway({ CustomerGatewayId: id } as any), |
| 454 | ); |
| 455 | }); |
| 456 | |
| 457 | const deleteInternetGateways = Effect.gen(function* () { |
| 458 | const gateways = (yield* ec2.describeInternetGateways({} as any)).InternetGateways ?? []; |
| 459 | const ids = uniq(gateways.map((gateway: any) => gateway.InternetGatewayId)); |
| 460 | |
| 461 | if (ids.length === 0) { |
| 462 | return; |
| 463 | } |
| 464 | |
| 465 | yield* preview("internet gateway(s)", ids); |
| 466 | if (!execute) { |
| 467 | return; |
| 468 | } |
| 469 | |
| 470 | yield* Effect.forEach( |
| 471 | gateways, |
| 472 | (gateway: any) => |
| 473 | Effect.gen(function* () { |
| 474 | for (const attachment of gateway.Attachments ?? []) { |
| 475 | if (attachment.VpcId) { |
| 476 | yield* ignoreFailure( |
| 477 | `internet gateway attachment ${gateway.InternetGatewayId}`, |
| 478 | ec2.detachInternetGateway({ |
| 479 | InternetGatewayId: gateway.InternetGatewayId, |
| 480 | VpcId: attachment.VpcId, |
| 481 | } as any), |
| 482 | ); |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | yield* ignoreFailure( |
| 487 | `internet gateway ${gateway.InternetGatewayId}`, |
| 488 | ec2.deleteInternetGateway({ |
| 489 | InternetGatewayId: gateway.InternetGatewayId, |
| 490 | } as any), |
| 491 | ); |
| 492 | }), |
| 493 | { concurrency: 1, discard: true }, |
| 494 | ); |
| 495 | }); |
| 496 | |
| 497 | const deleteEgressOnlyInternetGateways = Effect.gen(function* () { |
| 498 | const gateways = |
| 499 | (yield* ec2.describeEgressOnlyInternetGateways({} as any)).EgressOnlyInternetGateways ?? []; |
| 500 | const ids = uniq(gateways.map((gateway: any) => gateway.EgressOnlyInternetGatewayId)); |
| 501 | |
| 502 | yield* deleteEach("egress-only internet gateway(s)", ids, (id) => |
| 503 | ec2.deleteEgressOnlyInternetGateway({ |
| 504 | EgressOnlyInternetGatewayId: id, |
| 505 | } as any), |
| 506 | ); |
| 507 | }); |
| 508 | |
| 509 | const deleteRouteTables = Effect.gen(function* () { |
| 510 | const routeTables = |
| 511 | (yield* ec2.describeRouteTables({} as any)).RouteTables?.filter( |
| 512 | (routeTable: any) => |
| 513 | !(routeTable.Associations ?? []).some((association: any) => association.Main), |
| 514 | ) ?? []; |
| 515 | |
| 516 | const ids = uniq(routeTables.map((routeTable: any) => routeTable.RouteTableId)); |
| 517 | |
| 518 | if (ids.length === 0) { |
| 519 | return; |
| 520 | } |
| 521 | |
| 522 | yield* preview("non-main route table(s)", ids); |
| 523 | if (!execute) { |
| 524 | return; |
| 525 | } |
| 526 | |
| 527 | yield* Effect.forEach( |
| 528 | routeTables, |
| 529 | (routeTable: any) => |
| 530 | Effect.gen(function* () { |
| 531 | for (const association of routeTable.Associations ?? []) { |
| 532 | if (!association.Main && association.RouteTableAssociationId) { |
| 533 | yield* ignoreFailure( |
| 534 | `route table association ${association.RouteTableAssociationId}`, |
| 535 | ec2.disassociateRouteTable({ |
| 536 | AssociationId: association.RouteTableAssociationId, |
| 537 | } as any), |
| 538 | ); |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | yield* ignoreFailure( |
| 543 | `route table ${routeTable.RouteTableId}`, |
| 544 | ec2.deleteRouteTable({ |
| 545 | RouteTableId: routeTable.RouteTableId, |
| 546 | } as any), |
| 547 | ); |
| 548 | }), |
| 549 | { concurrency: 1, discard: true }, |
| 550 | ); |
| 551 | }); |
| 552 | |
| 553 | const deleteSubnets = Effect.gen(function* () { |
| 554 | const ids = uniq( |
| 555 | (yield* ec2.describeSubnets({} as any)).Subnets?.filter((subnet: any) => |
| 556 | includeDefaultVpcs ? true : !subnet.DefaultForAz, |
| 557 | ).map((subnet: any) => subnet.SubnetId), |
| 558 | ); |
| 559 | |
| 560 | yield* deleteEach("subnet(s)", ids, (id) => ec2.deleteSubnet({ SubnetId: id } as any)); |
| 561 | }); |
| 562 | |
| 563 | const deleteSecurityGroups = Effect.gen(function* () { |
| 564 | const ids = uniq( |
| 565 | (yield* ec2.describeSecurityGroups({} as any)).SecurityGroups?.filter( |
| 566 | (group: any) => group.GroupName !== "default", |
| 567 | ).map((group: any) => group.GroupId), |
| 568 | ); |
| 569 | |
| 570 | yield* deleteEach("security group(s)", ids, (id) => |
| 571 | ec2.deleteSecurityGroup({ GroupId: id } as any), |
| 572 | ); |
| 573 | }); |
| 574 | |
| 575 | const deleteNetworkAcls = Effect.gen(function* () { |
| 576 | const ids = uniq( |
| 577 | (yield* ec2.describeNetworkAcls({} as any)).NetworkAcls?.filter( |
| 578 | (acl: any) => !acl.IsDefault, |
| 579 | ).map((acl: any) => acl.NetworkAclId), |
| 580 | ); |
| 581 | |
| 582 | yield* deleteEach("network ACL(s)", ids, (id) => |
| 583 | ec2.deleteNetworkAcl({ NetworkAclId: id } as any), |
| 584 | ); |
| 585 | }); |
| 586 | |
| 587 | const deleteAvailableVolumes = Effect.gen(function* () { |
| 588 | const ids = uniq( |
| 589 | (yield* ec2.describeVolumes({} as any)).Volumes?.filter( |
| 590 | (volume: any) => volume.State === "available", |
| 591 | ).map((volume: any) => volume.VolumeId), |
| 592 | ); |
| 593 | |
| 594 | yield* deleteEach("available volume(s)", ids, (id) => ec2.deleteVolume({ VolumeId: id } as any)); |
| 595 | }); |
| 596 | |
| 597 | const deregisterImages = Effect.gen(function* () { |
| 598 | const ids = uniq( |
| 599 | (yield* ec2.describeImages({ Owners: ["self"] } as any)).Images?.map( |
| 600 | (image: any) => image.ImageId, |
| 601 | ), |
| 602 | ); |
| 603 | |
| 604 | yield* deleteEach("AMI(s)", ids, (id) => ec2.deregisterImage({ ImageId: id } as any)); |
| 605 | }); |
| 606 | |
| 607 | const deleteSnapshots = Effect.gen(function* () { |
| 608 | const ids = uniq( |
| 609 | (yield* ec2.describeSnapshots({ |
| 610 | OwnerIds: ["self"], |
| 611 | } as any)).Snapshots?.map((snapshot: any) => snapshot.SnapshotId), |
| 612 | ); |
| 613 | |
| 614 | yield* deleteEach("snapshot(s)", ids, (id) => ec2.deleteSnapshot({ SnapshotId: id } as any)); |
| 615 | }); |
| 616 | |
| 617 | const deleteLaunchTemplates = Effect.gen(function* () { |
| 618 | const ids = uniq( |
| 619 | (yield* ec2.describeLaunchTemplates({} as any)).LaunchTemplates?.map( |
| 620 | (template: any) => template.LaunchTemplateId, |
| 621 | ), |
| 622 | ); |
| 623 | |
| 624 | yield* deleteEach("launch template(s)", ids, (id) => |
| 625 | ec2.deleteLaunchTemplate({ LaunchTemplateId: id } as any), |
| 626 | ); |
| 627 | }); |
| 628 | |
| 629 | const deletePlacementGroups = Effect.gen(function* () { |
| 630 | const ids = uniq( |
| 631 | (yield* ec2.describePlacementGroups({} as any)).PlacementGroups?.map( |
| 632 | (group: any) => group.GroupName, |
| 633 | ), |
| 634 | ); |
| 635 | |
| 636 | yield* deleteEach("placement group(s)", ids, (id) => |
| 637 | ec2.deletePlacementGroup({ GroupName: id } as any), |
| 638 | ); |
| 639 | }); |
| 640 | |
| 641 | const deleteKeyPairs = Effect.gen(function* () { |
| 642 | const ids = uniq( |
| 643 | (yield* ec2.describeKeyPairs({} as any)).KeyPairs?.map((keyPair: any) => keyPair.KeyPairId), |
| 644 | ); |
| 645 | |
| 646 | yield* deleteEach("key pair(s)", ids, (id) => ec2.deleteKeyPair({ KeyPairId: id } as any)); |
| 647 | }); |
| 648 | |
| 649 | const deleteVpcs = Effect.gen(function* () { |
| 650 | const ids = uniq( |
| 651 | (yield* ec2.describeVpcs({} as any)).Vpcs?.filter((vpc: any) => |
| 652 | includeDefaultVpcs ? true : !vpc.IsDefault, |
| 653 | ).map((vpc: any) => vpc.VpcId), |
| 654 | ); |
| 655 | |
| 656 | yield* deleteEach("VPC(s)", ids, (id) => ec2.deleteVpc({ VpcId: id } as any)); |
| 657 | }); |
| 658 | |
| 659 | const deleteDhcpOptions = Effect.gen(function* () { |
| 660 | const associatedDhcpOptionsIds = new Set( |
| 661 | uniq((yield* ec2.describeVpcs({} as any)).Vpcs?.map((vpc: any) => vpc.DhcpOptionsId)), |
| 662 | ); |
| 663 | |
| 664 | const ids = uniq( |
| 665 | (yield* ec2.describeDhcpOptions({} as any)).DhcpOptions?.map( |
| 666 | (dhcpOptions: any) => dhcpOptions.DhcpOptionsId, |
| 667 | ).filter((id: string) => id !== "default" && !associatedDhcpOptionsIds.has(id)), |
| 668 | ); |
| 669 | |
| 670 | yield* deleteEach("DHCP options set(s)", ids, (id) => |
| 671 | ec2.deleteDhcpOptions({ DhcpOptionsId: id } as any), |
| 672 | ); |
| 673 | }); |
| 674 | |
| 675 | const main = Effect.gen(function* () { |
| 676 | yield* log( |
| 677 | [ |
| 678 | `Mode=${execute ? "execute" : "dry-run"}`, |
| 679 | `Region=${region}`, |
| 680 | values.profile ? `Profile=${values.profile}` : undefined, |
| 681 | includeDefaultVpcs ? "Including default VPCs" : "Skipping default VPCs", |
| 682 | ] |
| 683 | .filter((value): value is string => !!value) |
| 684 | .join(" | "), |
| 685 | ); |
| 686 | |
| 687 | for (let pass = 1; pass <= maxPasses; pass++) { |
| 688 | yield* log(`\n=== Cleanup pass ${pass}/${maxPasses} ===`); |
| 689 | |
| 690 | yield* terminateInstances; |
| 691 | yield* deleteVpcEndpoints; |
| 692 | yield* deleteNatGateways; |
| 693 | yield* deleteNetworkInterfaces; |
| 694 | yield* releaseElasticIps; |
| 695 | yield* deleteVpnConnections; |
| 696 | yield* deleteVpnGateways; |
| 697 | yield* deleteCustomerGateways; |
| 698 | yield* deleteVpcPeeringConnections; |
| 699 | yield* deleteInternetGateways; |
| 700 | yield* deleteEgressOnlyInternetGateways; |
| 701 | yield* deleteRouteTables; |
| 702 | yield* deleteSubnets; |
| 703 | yield* deleteSecurityGroups; |
| 704 | yield* deleteNetworkAcls; |
| 705 | yield* deleteAvailableVolumes; |
| 706 | yield* deregisterImages; |
| 707 | yield* deleteSnapshots; |
| 708 | yield* deleteLaunchTemplates; |
| 709 | yield* deletePlacementGroups; |
| 710 | yield* deleteKeyPairs; |
| 711 | yield* deleteVpcs; |
| 712 | yield* deleteDhcpOptions; |
| 713 | |
| 714 | if (!execute) { |
| 715 | yield* log("\nDry-run complete. Re-run with --execute to perform deletions."); |
| 716 | return; |
| 717 | } |
| 718 | } |
| 719 | |
| 720 | yield* log("\nCleanup passes complete."); |
| 721 | }); |
| 722 | |
| 723 | Effect.runPromise(main.pipe(Effect.provide(runtime))).catch((error) => { |
| 724 | console.error(formatError(error)); |
| 725 | process.exit(1); |
| 726 | }); |