diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 339607c..ba07b96 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -64,7 +64,6 @@ jobs: docker run -i --rm \ -v /var/run/docker.sock:/var/run/docker.sock \ --add-host host.docker.internal:host-gateway \ - --add-host s3.host.docker.internal:host-gateway \ --add-host snowflake.localhost.localstack.cloud:host-gateway \ -e LOCALSTACK_AUTH_TOKEN \ -e LOCALSTACK_HOSTNAME=host.docker.internal \ diff --git a/Dockerfile b/Dockerfile index a49381e..8210e86 100644 --- a/Dockerfile +++ b/Dockerfile @@ -31,35 +31,17 @@ RUN set -eux; \ RUN python3 -m venv /opt/venv \ && pip install --no-cache-dir --upgrade pip \ && pip install --no-cache-dir --no-compile \ - terraform-local \ aws-sam-cli \ - aws-sam-cli-local \ snowflake-cli \ && find /opt/venv/lib \ \( -type d \( -name __pycache__ -o -name tests -o -name test \) -o -type f \( -name '*.pyc' -o -name '*.pyo' \) \) \ -prune -exec rm -rf '{}' + -RUN npm install -g aws-cdk@2.1133.0 aws-cdk-local \ +# lstk wraps terraform, cdk, and sam for the deployer tool. aws-cdk >= 2.1138 honors the +# CDK_S3_FORCE_PATH_STYLE that lstk sets, so S3 assets reach host.docker.internal path-style. +RUN npm install -g aws-cdk@2.1145.0 @localstack/lstk@1.4.2 \ && npm cache clean --force -RUN node <<'NODE' -const fs = require("fs"); -const path = require("path"); -const { execSync } = require("child_process"); -const globalRoot = execSync("npm root -g").toString().trim(); -const file = path.join(globalRoot, "aws-cdk/lib/index.js"); -const source = fs.readFileSync(file, "utf8"); -const target = ` s3() {\n const client = new import_client_s33.S3Client(this.config);`; -const replacement = ` s3() {\n if (/^(1|true|yes)$/i.test(process.env.AWS_S3_FORCE_PATH_STYLE || "")) {\n this.config.forcePathStyle = true;\n }\n const client = new import_client_s33.S3Client(this.config);`; - -if (!source.includes(replacement)) { - if (!source.includes(target)) { - throw new Error("Could not patch aws-cdk S3 forcePathStyle hook"); - } - fs.writeFileSync(file, source.replace(target, replacement)); -} -NODE - WORKDIR /app RUN mkdir -p /tmp/dockerode-deps \ && npm install --prefix /tmp/dockerode-deps --omit=dev --ignore-scripts --no-audit --no-fund dockerode@5.0.1 \ @@ -71,11 +53,10 @@ COPY --from=builder /app/dist ./dist COPY --from=builder /app/package.json ./package.json RUN set -eux; \ + lstk --version; \ terraform version; \ - tflocal --version; \ sam --version; \ - command -v samlocal; \ - cdklocal --version; \ + cdk --version; \ snow --version; \ node dist/cli.js version; \ node -e "require('dockerode'); console.log('dockerode ok')" diff --git a/README.md b/README.md index 17a2f8c..4ab0b40 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ This server provides your AI with dedicated tools for managing your LocalStack e | Tool Name | Description | Key Features | | :-------------------------------------------------------------------------------- | :------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`localstack-management`](./src/tools/localstack-management.ts) | Manages LocalStack runtime operations for AWS, Snowflake and Azure stacks | - Execute start, stop, restart, and status checks
- Integrate LocalStack authentication tokens
- Inject custom environment variables
- Verify real-time status and perform health monitoring | -| [`localstack-deployer`](./src/tools/localstack-deployer.ts) | Handles infrastructure deployment to LocalStack for AWS environments | - Automatically run CDK, Terraform, and SAM tooling to deploy infrastructure locally
- Enable parameterized deployments with variable support
- Process and present deployment results
- Requires you to have [`cdklocal`](https://github.com/localstack/aws-cdk-local), [`tflocal`](https://github.com/localstack/terraform-local), or [`samlocal`](https://github.com/localstack/aws-sam-cli-local) installed in your system path | +| [`localstack-deployer`](./src/tools/localstack-deployer.ts) | Handles infrastructure deployment to LocalStack for AWS environments | - Automatically run CDK, Terraform, and SAM tooling to deploy infrastructure locally
- Enable parameterized deployments with variable support
- Process and present deployment results
- Runs `lstk terraform`, `lstk cdk`, or `lstk sam`, so it requires [`lstk`](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/) plus `terraform`, `cdk`, or `sam` in your system path | | [`localstack-logs-analysis`](./src/tools/localstack-logs-analysis.ts) | Analyzes LocalStack for AWS logs for troubleshooting and insights | - Offer multiple analysis options including summaries, errors, requests, and raw data
- Filter by specific services and operations
- Generate API call metrics and failure breakdowns
- Group errors intelligently and identify patterns | | [`localstack-iam-policy-analyzer`](./src/tools/localstack-iam-policy-analyzer.ts) | Handles IAM policy management and violation remediation | - Set IAM enforcement levels including `enforced`, `soft`, and `disabled` modes
- Search logs for permission-related violations
- Generate IAM policies automatically from detected access failures
- Requires a valid LocalStack Auth Token | | [`localstack-chaos-injector`](./src/tools/localstack-chaos-injector.ts) | Injects and manages chaos experiment faults for system resilience testing | - Inject, add, remove, and clear service fault rules
- Configure network latency effects
- Comprehensive fault targeting by service, region, and operation
- Built-in workflow guidance for chaos experiments
- Requires a valid LocalStack Auth Token | @@ -124,7 +124,7 @@ Run `npx -y @localstack/localstack-mcp-server init --help` for all options. ### Prerequisites - Docker installed and running. The MCP server manages the LocalStack container directly through the Docker API. -- [`cdklocal`](https://github.com/localstack/aws-cdk-local), [`tflocal`](https://github.com/localstack/terraform-local), or [`samlocal`](https://github.com/localstack/aws-sam-cli-local) installed in your system path if you want to deploy CDK, Terraform, or SAM projects +- [`lstk`](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/) (`npm install -g @localstack/lstk`) plus the Terraform, AWS CDK (2.177.0 or newer), or AWS SAM (1.95.0 or newer) CLI in your system path if you want to deploy Terraform, CDK, or SAM projects - Snowflake CLI (`snow`) installed in your system path if you want to use the Snowflake tool - Azure CLI (`az`) installed in your system path if you want to use the Azure tool (see [docs/AZURE.md](./docs/AZURE.md)) - A [valid LocalStack Auth Token](https://docs.localstack.cloud/aws/getting-started/auth-token/) configured as `LOCALSTACK_AUTH_TOKEN` (**required for all MCP tools**) @@ -170,7 +170,7 @@ If you installed from source, change `command` and `args` to point to your local ### Run with Docker -The `localstack/localstack-mcp-server` Docker image bundles Terraform/`tflocal`, CDK/`cdklocal`, SAM/`samlocal`, and the Snowflake CLI. The only required host dependency is Docker. The container uses the mounted Docker socket to run LocalStack as a sibling container on the host; state lives in a named Docker volume (`localstack-mcp`) unless `LOCALSTACK_VOLUME_DIR` points at a host directory. +The `localstack/localstack-mcp-server` Docker image bundles `lstk` with Terraform, CDK, and SAM, and the Snowflake CLI. The only required host dependency is Docker. The container uses the mounted Docker socket to run LocalStack as a sibling container on the host; state lives in a named Docker volume (`localstack-mcp`) unless `LOCALSTACK_VOLUME_DIR` points at a host directory. If you use the deployer tool with local Terraform, CDK, or SAM projects, bind-mount those project paths into the MCP container and pass the in-container path to the tool. The simplest convention is to mount projects at the same absolute path they use on the host. @@ -188,8 +188,6 @@ If you use the deployer tool with local Terraform, CDK, or SAM projects, bind-mo "--add-host", "host.docker.internal:host-gateway", "--add-host", - "s3.host.docker.internal:host-gateway", - "--add-host", "snowflake.localhost.localstack.cloud:host-gateway", "-e", "LOCALSTACK_AUTH_TOKEN", diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 96657c8..ec8c63f 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -1,7 +1,7 @@ # Running the LocalStack MCP Server in Docker -The published image bundles everything the server shells out to — Terraform + -`tflocal`, AWS CDK + `cdklocal`, AWS SAM + `samlocal`, and the Snowflake `snow` +The published image bundles everything the server shells out to — `lstk` with +Terraform, AWS CDK, and AWS SAM, and the Snowflake `snow` CLI — so the **only dependency on your machine is Docker itself**. LocalStack lifecycle, logs, and `awslocal` run through the Docker Engine API and LocalStack's REST APIs. @@ -47,21 +47,19 @@ interpreted by the **host** daemon). docker run -i --rm \ -v /var/run/docker.sock:/var/run/docker.sock \ --add-host host.docker.internal:host-gateway \ - --add-host s3.host.docker.internal:host-gateway \ --add-host snowflake.localhost.localstack.cloud:host-gateway \ -e LOCALSTACK_AUTH_TOKEN="" \ -e LOCALSTACK_HOSTNAME=host.docker.internal \ localstack/localstack-mcp-server:latest ``` -| Flag | Why it's needed | -| -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | -| `-v /var/run/docker.sock:/var/run/docker.sock` | Lets the server create/stop/restart the sibling LocalStack container, read its logs, and run `awslocal` inside it. | -| `--add-host host.docker.internal:host-gateway` | Resolves `host.docker.internal` on Linux. Harmless on Docker Desktop (Mac/Windows), where it already resolves. | -| `--add-host s3.host.docker.internal:host-gateway` | Lets CDK's virtual-hosted S3 endpoint resolve when `cdklocal` uses `AWS_ENDPOINT_URL_S3=http://s3.host.docker.internal:4566`. | -| `--add-host snowflake.localhost.localstack.cloud:host-gateway` | Lets the Snowflake CLI reach the sibling Snowflake emulator through the hostname the emulator expects for routing. | -| `-e LOCALSTACK_AUTH_TOKEN` | Required by **every** tool in this server. | -| `-e LOCALSTACK_HOSTNAME=host.docker.internal` | Tells the server + IaC CLIs where the sibling LocalStack lives. | +| Flag | Why it's needed | +| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | +| `-v /var/run/docker.sock:/var/run/docker.sock` | Lets the server create/stop/restart the sibling LocalStack container, read its logs, and run `awslocal` inside it. | +| `--add-host host.docker.internal:host-gateway` | Resolves `host.docker.internal` on Linux. Harmless on Docker Desktop (Mac/Windows), where it already resolves. | +| `--add-host snowflake.localhost.localstack.cloud:host-gateway` | Lets the Snowflake CLI reach the sibling Snowflake emulator through the hostname the emulator expects for routing. | +| `-e LOCALSTACK_AUTH_TOKEN` | Required by **every** tool in this server. | +| `-e LOCALSTACK_HOSTNAME=host.docker.internal` | Tells the server + IaC CLIs where the sibling LocalStack lives. | ## MCP client configuration @@ -82,8 +80,6 @@ expand `$HOME`/`$PWD` — use absolute paths. "--add-host", "host.docker.internal:host-gateway", "--add-host", - "s3.host.docker.internal:host-gateway", - "--add-host", "snowflake.localhost.localstack.cloud:host-gateway", "-e", "LOCALSTACK_AUTH_TOKEN", @@ -111,10 +107,11 @@ The simplest convention is to mount it at the same absolute path: Then tell the tool `directory: /Users/you/projects/my-infra`. -Terraform, SAM, and CDK receive the LocalStack endpoint automatically when -`LOCALSTACK_HOSTNAME=host.docker.internal` is set. CDK asset publishing is forced -to path-style S3 inside the Docker image, so the single `s3.host.docker.internal` -alias covers bootstrap asset uploads. +The deployer runs Terraform, SAM, and CDK through `lstk terraform|sam|cdk`, which +receives the LocalStack endpoint automatically when +`LOCALSTACK_HOSTNAME=host.docker.internal` is set. `lstk` forces CDK asset +publishing to path-style S3, so no extra S3 host alias is needed. Existing configs +that still pass `--add-host s3.host.docker.internal:host-gateway` keep working. ## Known limitations @@ -153,7 +150,6 @@ node tests/docker/validate-image.mjs -- \ docker run -i --rm \ -v /var/run/docker.sock:/var/run/docker.sock \ --add-host host.docker.internal:host-gateway \ - --add-host s3.host.docker.internal:host-gateway \ --add-host snowflake.localhost.localstack.cloud:host-gateway \ -e LOCALSTACK_AUTH_TOKEN \ -e LOCALSTACK_HOSTNAME=host.docker.internal \ diff --git a/src/core/localstack-env.test.ts b/src/core/localstack-env.test.ts index 9dc65ea..99fdd09 100644 --- a/src/core/localstack-env.test.ts +++ b/src/core/localstack-env.test.ts @@ -20,11 +20,17 @@ describe("buildIacCliEnv", () => { expect(env.AWS_REGION).toBe("us-east-1"); expect(env.CDK_DEFAULT_ACCOUNT).toBe("000000000000"); expect(env.CDK_DEFAULT_REGION).toBe("us-east-1"); - expect(env.AWS_ENVAR_ALLOWLIST).toContain("AWS_ACCESS_KEY_ID"); - expect(env.AWS_ENDPOINT_URL).toBeUndefined(); + expect(env.CI).toBe("true"); }); - it("adds Docker endpoint overrides when LocalStack runs through the host gateway", () => { + it("points lstk at localhost.localstack.cloud for a local LocalStack", () => { + const env = buildIacCliEnv(); + + expect(env.AWS_ENDPOINT_URL).toBe("http://localhost.localstack.cloud:4566"); + expect(env.AWS_ENDPOINT_URL_S3).toBeUndefined(); + }); + + it("points lstk at the host gateway when LocalStack runs outside the container", () => { process.env.LOCALSTACK_HOSTNAME = "host.docker.internal"; const env = buildIacCliEnv(); @@ -32,10 +38,16 @@ describe("buildIacCliEnv", () => { expect(env.AWS_ACCESS_KEY_ID).toBe("test"); expect(env.AWS_SECRET_ACCESS_KEY).toBe("test"); expect(env.AWS_ENDPOINT_URL).toBe("http://host.docker.internal:4566"); - expect(env.AWS_ENDPOINT_URL_S3).toBe("http://s3.host.docker.internal:4566"); - expect(env.S3_ENDPOINT).toBe("http://host.docker.internal:4566"); - expect(env.AWS_S3_FORCE_PATH_STYLE).toBe("1"); - expect(env.LOCALSTACK_HOSTNAME).toBe("host.docker.internal"); + // lstk derives the S3 endpoint and path-style addressing itself. + expect(env.AWS_ENDPOINT_URL_S3).toBeUndefined(); + }); + + it("preserves an explicit endpoint", () => { + process.env.LOCALSTACK_HOSTNAME = "host.docker.internal"; + + const env = buildIacCliEnv({ AWS_ENDPOINT_URL: "https://example.localstack.cloud" }); + + expect(env.AWS_ENDPOINT_URL).toBe("https://example.localstack.cloud"); }); it("preserves explicit credentials and regions", () => { diff --git a/src/core/localstack-env.ts b/src/core/localstack-env.ts index e1e3f0f..7e473a8 100644 --- a/src/core/localstack-env.ts +++ b/src/core/localstack-env.ts @@ -1,65 +1,44 @@ import { LOCALSTACK_PORT } from "./config"; /** - * Build the environment for spawned LocalStack IaC CLIs (tflocal, cdklocal, samlocal) - * so they target the right LocalStack endpoint when the server runs in a container - * and LocalStack is reachable at a non-default host (e.g. host.docker.internal). + * Build the environment for the spawned `lstk terraform|cdk|sam` proxies so they + * target the LocalStack endpoint this server is configured for. * - * Why this is needed (verified against the wrapper sources): - * - tflocal / samlocal honor LOCALSTACK_HOSTNAME + EDGE_PORT (AWS_ENDPOINT_URL wins). - * - cdklocal (aws-cdk >= 2.177) IGNORES LOCALSTACK_HOSTNAME and REQUIRES - * AWS_ENDPOINT_URL together with AWS_ENDPOINT_URL_S3 (the S3 URL keeps an `s3.` - * component so CDK routes S3 traffic). Setting AWS_ENDPOINT_URL without the S3 - * one makes cdklocal throw. + * Why this is needed (verified against the lstk sources): + * - Without AWS_ENDPOINT_URL, lstk only accepts the AWS container named in its own + * config.toml, so a container this server started or found under another name + * (e.g. `localstack-main`), or LocalStack behind host.docker.internal, is + * rejected. With it, lstk probes `/_localstack/health` and uses that endpoint. + * - AWS_ENDPOINT_URL_S3 is left unset: lstk derives it and, for CDK >= 2.1138, + * forces path-style S3. A preset S3 endpoint turns that off. * * This env is injected ONLY into the IaC CLI child processes — never globally and * never into the LocalStack container, because a container-side AWS_ENDPOINT_URL * would redirect LocalStack's own internal service-to-service calls and break them. * - * When LOCALSTACK_HOSTNAME is unset / localhost (the default `npx` workflow), the - * endpoint variables are left unchanged so the wrappers use their built-in - * localhost.localstack.cloud defaults. Dummy credentials and CDK defaults are - * still injected because CDK bootstrap requires them even for LocalStack. + * A local LocalStack (LOCALSTACK_HOSTNAME unset / localhost, the default `npx` + * workflow) is addressed as localhost.localstack.cloud, lstk's own default, so CDK + * versions without path-style support still reach S3 through `s3.` virtual hosts. + * Dummy credentials and CDK defaults are injected because CDK bootstrap requires + * them even for LocalStack. */ export function buildIacCliEnv(extra: Record = {}): NodeJS.ProcessEnv { const base: NodeJS.ProcessEnv = { ...process.env, ...extra }; - const commonEnv: NodeJS.ProcessEnv = { + const explicitHost = process.env.LOCALSTACK_HOSTNAME?.trim(); + const host = + !explicitHost || explicitHost === "localhost" || explicitHost === "127.0.0.1" + ? "localhost.localstack.cloud" + : explicitHost; + + return { ...base, - AWS_ENVAR_ALLOWLIST: [ - "AWS_ACCESS_KEY_ID", - "AWS_SECRET_ACCESS_KEY", - "AWS_SESSION_TOKEN", - "AWS_DEFAULT_REGION", - "AWS_REGION", - "AWS_S3_FORCE_PATH_STYLE", - "CDK_DEFAULT_ACCOUNT", - "CDK_DEFAULT_REGION", - ].join(","), AWS_ACCESS_KEY_ID: base.AWS_ACCESS_KEY_ID || "test", AWS_SECRET_ACCESS_KEY: base.AWS_SECRET_ACCESS_KEY || "test", AWS_DEFAULT_REGION: base.AWS_DEFAULT_REGION || "us-east-1", AWS_REGION: base.AWS_REGION || base.AWS_DEFAULT_REGION || "us-east-1", CDK_DEFAULT_ACCOUNT: base.CDK_DEFAULT_ACCOUNT || "000000000000", CDK_DEFAULT_REGION: base.CDK_DEFAULT_REGION || base.AWS_DEFAULT_REGION || "us-east-1", - }; - - const explicitHost = process.env.LOCALSTACK_HOSTNAME?.trim(); - if (!explicitHost || explicitHost === "localhost" || explicitHost === "127.0.0.1") { - return commonEnv; - } - - const port = String(LOCALSTACK_PORT); - const endpoint = `http://${explicitHost}:${port}`; - const s3Endpoint = `http://s3.${explicitHost}:${port}`; - - return { - ...commonEnv, - AWS_ENDPOINT_URL: base.AWS_ENDPOINT_URL || endpoint, - AWS_ENDPOINT_URL_S3: base.AWS_ENDPOINT_URL_S3 || s3Endpoint, - S3_ENDPOINT: base.S3_ENDPOINT || endpoint, - AWS_S3_FORCE_PATH_STYLE: base.AWS_S3_FORCE_PATH_STYLE || "1", - LOCALSTACK_HOSTNAME: explicitHost, - EDGE_PORT: base.EDGE_PORT || port, + AWS_ENDPOINT_URL: base.AWS_ENDPOINT_URL || `http://${host}:${LOCALSTACK_PORT}`, }; } diff --git a/src/lib/deployment/deployment-utils.test.ts b/src/lib/deployment/deployment-utils.test.ts index caa4f84..7a2eb84 100644 --- a/src/lib/deployment/deployment-utils.test.ts +++ b/src/lib/deployment/deployment-utils.test.ts @@ -1,14 +1,72 @@ import fs from "fs"; import os from "os"; import path from "path"; +import { runCommand, CommandResult } from "../../core/command-runner"; import { + checkDependencies, inferProjectType, parseCdkOutputs, parseTerraformOutputs, validateVariables, } from "./deployment-utils"; +jest.mock("../../core/command-runner", () => ({ + runCommand: jest.fn(), +})); + +const mockedRunCommand = runCommand as jest.MockedFunction; + +function result(overrides: Partial = {}): CommandResult { + return { stdout: "", stderr: "", exitCode: 0, ...overrides }; +} + describe("deployment-utils", () => { + describe("checkDependencies", () => { + beforeEach(() => mockedRunCommand.mockReset()); + + it("requires lstk before the wrapped IaC CLI", async () => { + mockedRunCommand.mockResolvedValueOnce(result({ error: new Error("spawn lstk ENOENT") })); + + const check = await checkDependencies("terraform"); + + expect(check.isAvailable).toBe(false); + expect(check.tool).toBe("lstk"); + expect(check.errorMessage).toContain("npm install -g @localstack/lstk"); + expect(mockedRunCommand).toHaveBeenCalledTimes(1); + }); + + it("requires the IaC CLI lstk wraps", async () => { + mockedRunCommand + .mockResolvedValueOnce(result({ stdout: "lstk 1.4.2\n" })) + .mockResolvedValueOnce(result({ error: new Error("spawn sam ENOENT") })); + + const check = await checkDependencies("sam"); + + expect(check.isAvailable).toBe(false); + expect(check.tool).toBe("sam"); + expect(mockedRunCommand).toHaveBeenLastCalledWith("sam", ["--version"], expect.anything()); + }); + + it("reports both versions when lstk and the IaC CLI are installed", async () => { + mockedRunCommand + .mockResolvedValueOnce(result({ stdout: "lstk 1.4.2\n" })) + .mockResolvedValueOnce(result({ stdout: "Terraform v1.13.0\non darwin_arm64\n" })); + + const check = await checkDependencies("terraform"); + + expect(check).toEqual({ + isAvailable: true, + tool: "lstk terraform", + version: "lstk 1.4.2; Terraform v1.13.0", + }); + expect(mockedRunCommand).toHaveBeenLastCalledWith( + "terraform", + ["version"], + expect.anything() + ); + }); + }); + describe("validateVariables", () => { it("should allow valid variables", () => { const errors = validateVariables({ key: "value", ANOTHER_KEY: "some-value-123" }); diff --git a/src/lib/deployment/deployment-utils.ts b/src/lib/deployment/deployment-utils.ts index 6105398..d6ab9be 100644 --- a/src/lib/deployment/deployment-utils.ts +++ b/src/lib/deployment/deployment-utils.ts @@ -11,64 +11,77 @@ export interface DependencyCheckResult { export type ProjectType = "cdk" | "terraform" | "sam" | "cloudformation" | "ambiguous" | "unknown"; +const LSTK_INSTALL_MESSAGE = `❌ lstk is not installed or not available in PATH. + +The deployer runs Terraform, CDK, and SAM through the lstk CLI. Please install it by following the official documentation: +https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/ + +Installation: +npm install -g @localstack/lstk +# or: brew install localstack/tap/lstk + +After installation, make sure the 'lstk' command is available in your PATH.`; + +const IAC_TOOLS: Record< + "cdk" | "terraform" | "sam", + { binary: string; versionArgs: string[]; errorMessage: string } +> = { + terraform: { + binary: "terraform", + versionArgs: ["version"], + errorMessage: `❌ terraform is not installed or not available in PATH. + +lstk runs your own Terraform CLI. Please install it by following the official documentation: +https://developer.hashicorp.com/terraform/install + +After installation, make sure the 'terraform' command is available in your PATH.`, + }, + cdk: { + binary: "cdk", + versionArgs: ["--version"], + errorMessage: `❌ cdk is not installed or not available in PATH. + +lstk runs your own AWS CDK CLI (2.177.0 or newer). Please install it: +npm install -g aws-cdk + +After installation, make sure the 'cdk' command is available in your PATH.`, + }, + sam: { + binary: "sam", + versionArgs: ["--version"], + errorMessage: `❌ sam is not installed or not available in PATH. + +lstk runs your own AWS SAM CLI (1.95.0 or newer). Please install it by following the official documentation: +https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html + +After installation, make sure the 'sam' command is available in your PATH.`, + }, +}; + /** - * Check if the required deployment tool (cdklocal or tflocal) is available in the system PATH - * @param projectType The type of project requiring either 'cdk' or 'terraform' tooling + * Check that lstk and the IaC CLI it wraps (terraform, cdk, or sam) are available in the system PATH + * @param projectType The type of project requiring 'cdk', 'terraform', or 'sam' tooling * @returns Promise with availability status and tool information */ export async function checkDependencies( projectType: "cdk" | "terraform" | "sam" ): Promise { - const tool = - projectType === "cdk" ? "cdklocal" : projectType === "terraform" ? "tflocal" : "samlocal"; - - try { - const { stdout, error } = await runCommand(tool, ["--version"], { timeout: 10000 }); - if (error) throw error; - - return { - isAvailable: true, - tool, - version: stdout.trim(), - }; - } catch (error) { - const errorMessage = - projectType === "cdk" - ? `❌ cdklocal is not installed or not available in PATH. - -Please install aws-cdk-local by following the official documentation: -https://github.com/localstack/aws-cdk-local - -Installation: -npm install -g aws-cdk-local aws-cdk - -After installation, make sure the 'cdklocal' command is available in your PATH.` - : projectType === "terraform" - ? `❌ tflocal is not installed or not available in PATH. - -Please install terraform-local by following the official documentation: -https://github.com/localstack/terraform-local - -Installation: -pip install terraform-local - -After installation, make sure the 'tflocal' command is available in your PATH.` - : `❌ samlocal is not installed or not available in PATH. - -Please install aws-sam-cli-local by following the official documentation: -https://github.com/localstack/aws-sam-cli-local - -Installation: -pip install aws-sam-cli-local - -After installation, make sure the 'samlocal' command is available in your PATH.`; + const lstk = await runCommand("lstk", ["--version"], { timeout: 10000 }); + if (lstk.error) { + return { isAvailable: false, tool: "lstk", errorMessage: LSTK_INSTALL_MESSAGE }; + } - return { - isAvailable: false, - tool, - errorMessage, - }; + const { binary, versionArgs, errorMessage } = IAC_TOOLS[projectType]; + const wrapped = await runCommand(binary, versionArgs, { timeout: 10000 }); + if (wrapped.error) { + return { isAvailable: false, tool: binary, errorMessage }; } + + return { + isAvailable: true, + tool: `lstk ${projectType}`, + version: `${lstk.stdout.trim()}; ${wrapped.stdout.trim().split("\n")[0]}`, + }; } /** @@ -215,7 +228,7 @@ export function parseTerraformOutputs(outputJson: string): string { /** * Parse CDK outputs from deploy command stdout - * @param stdout The stdout from cdklocal deploy command + * @param stdout The stdout from the lstk cdk deploy command * @returns Formatted markdown string of outputs */ export function parseCdkOutputs(stdout: string): string { diff --git a/src/lib/wizard/server-config.logic.test.ts b/src/lib/wizard/server-config.logic.test.ts index 06c10d3..571aa2b 100644 --- a/src/lib/wizard/server-config.logic.test.ts +++ b/src/lib/wizard/server-config.logic.test.ts @@ -40,8 +40,6 @@ describe("buildDockerServerSpec", () => { "--add-host", "host.docker.internal:host-gateway", "--add-host", - "s3.host.docker.internal:host-gateway", - "--add-host", "snowflake.localhost.localstack.cloud:host-gateway", "-e", "LOCALSTACK_AUTH_TOKEN", diff --git a/src/lib/wizard/server-config.logic.ts b/src/lib/wizard/server-config.logic.ts index 87d7948..71d883a 100644 --- a/src/lib/wizard/server-config.logic.ts +++ b/src/lib/wizard/server-config.logic.ts @@ -36,8 +36,6 @@ export function buildDockerServerSpec( "--add-host", "host.docker.internal:host-gateway", "--add-host", - "s3.host.docker.internal:host-gateway", - "--add-host", "snowflake.localhost.localstack.cloud:host-gateway", "-e", AUTH_TOKEN_ENV, diff --git a/src/tools/localstack-deployer.ts b/src/tools/localstack-deployer.ts index e96e4cc..4bdd18f 100644 --- a/src/tools/localstack-deployer.ts +++ b/src/tools/localstack-deployer.ts @@ -266,7 +266,7 @@ export default async function localstackDeployer({ const nonNullDirectory = directory as string; // Validate the directory up front; a missing cwd otherwise surfaces as a misleading - // "spawn cdklocal/tflocal/samlocal ENOENT". Hint differs by run mode (Docker vs npx). + // "spawn lstk ENOENT". Hint differs by run mode (Docker vs npx). const resolvedDir = path.resolve(nonNullDirectory); const dirExists = await fs.promises .stat(resolvedDir) @@ -394,14 +394,14 @@ async function executeTerraformCommands( variables?: Record ): Promise { const events: DeploymentEvent[] = []; - const baseCommand = "tflocal"; + const baseCommand = "lstk"; const varArgs = variables ? Object.entries(variables).flatMap(([k, v]) => ["-var", `${k}=${v}`]) : []; if (action === "deploy") { events.push({ type: "header", title: "📦 Initializing Terraform", content: "" }); - const initRes = await runCommand(baseCommand, ["init"], { + const initRes = await runCommand(baseCommand, ["terraform", "init"], { cwd: directory, env: buildIacCliEnv(), }); @@ -410,14 +410,14 @@ async function executeTerraformCommands( if (initRes.error) { events.push({ type: "error", - title: "Error during `tflocal init`", + title: "Error during `lstk terraform init`", content: initRes.error.message, }); return events; } events.push({ type: "header", title: "🔨 Applying Terraform Configuration", content: "" }); - const applyArgs = ["apply", "-auto-approve", ...varArgs]; + const applyArgs = ["terraform", "apply", "-auto-approve", ...varArgs]; const applyRes = await runCommand(baseCommand, applyArgs, { cwd: directory, env: buildIacCliEnv(), @@ -427,13 +427,13 @@ async function executeTerraformCommands( if (applyRes.error) { events.push({ type: "error", - title: "Error during `tflocal apply`", + title: "Error during `lstk terraform apply`", content: applyRes.error.message, }); return events; } - const outputRes = await runCommand(baseCommand, ["output", "-json"], { + const outputRes = await runCommand(baseCommand, ["terraform", "output", "-json"], { cwd: directory, env: buildIacCliEnv(), }); @@ -444,7 +444,7 @@ async function executeTerraformCommands( events.push({ type: "success", content: "Terraform deployment completed successfully!" }); } else { events.push({ type: "header", title: "💥 Destroying Terraform Resources", content: "" }); - const destroyArgs = ["destroy", "-auto-approve", ...varArgs]; + const destroyArgs = ["terraform", "destroy", "-auto-approve", ...varArgs]; const destroyRes = await runCommand(baseCommand, destroyArgs, { cwd: directory, env: buildIacCliEnv(), @@ -455,7 +455,7 @@ async function executeTerraformCommands( if (destroyRes.error) { events.push({ type: "error", - title: "Error during `tflocal destroy`", + title: "Error during `lstk terraform destroy`", content: destroyRes.error.message, }); return events; @@ -515,7 +515,7 @@ async function executeSamCommands( } ): Promise { const events: DeploymentEvent[] = []; - const baseCommand = "samlocal"; + const baseCommand = "lstk"; const defaults = await loadSamConfigDefaults(directory); const inferredStackName = `${path.basename(directory).replace(/[^a-zA-Z0-9-]/g, "-")}-stack`; @@ -528,7 +528,7 @@ async function executeSamCommands( if (action === "deploy") { events.push({ type: "header", title: "🏗️ Building SAM Application", content: "" }); - const buildArgs = ["build", "--cached"]; + const buildArgs = ["sam", "build", "--cached"]; if (resolvedTemplatePath) { buildArgs.push("--template-file", resolvedTemplatePath); } @@ -542,7 +542,7 @@ async function executeSamCommands( if (buildRes.error) { events.push({ type: "error", - title: "Error during `samlocal build`", + title: "Error during `lstk sam build`", content: buildRes.error.message, }); return events; @@ -550,6 +550,7 @@ async function executeSamCommands( events.push({ type: "header", title: "🚀 Deploying SAM Application", content: "" }); const deployArgs = [ + "sam", "deploy", "--no-confirm-changeset", "--no-fail-on-empty-changeset", @@ -590,7 +591,7 @@ async function executeSamCommands( if (deployRes.error) { events.push({ type: "error", - title: "Error during `samlocal deploy`", + title: "Error during `lstk sam deploy`", content: deployRes.error.message, }); return events; @@ -599,6 +600,7 @@ async function executeSamCommands( } else { events.push({ type: "header", title: "💥 Deleting SAM Application", content: "" }); const deleteArgs = [ + "sam", "delete", "--no-prompts", "--region", @@ -617,7 +619,7 @@ async function executeSamCommands( if (deleteRes.error) { events.push({ type: "error", - title: "Error during `samlocal delete`", + title: "Error during `lstk sam delete`", content: deleteRes.error.message, }); return events; @@ -637,14 +639,14 @@ async function executeCdkCommands( variables?: Record ): Promise { const events: DeploymentEvent[] = []; - const baseCommand = "cdklocal"; + const baseCommand = "lstk"; const contextArgs = variables ? Object.entries(variables).flatMap(([key, value]) => ["--context", `${key}=${value}`]) : []; if (action === "deploy") { events.push({ type: "header", title: "🥾 Bootstrapping CDK for LocalStack", content: "" }); - const bootstrapRes = await runCommand(baseCommand, ["bootstrap"], { + const bootstrapRes = await runCommand(baseCommand, ["cdk", "bootstrap"], { cwd: directory, env: buildIacCliEnv({ CI: "true" }), }); @@ -654,7 +656,7 @@ async function executeCdkCommands( if (bootstrapRes.error) { events.push({ type: "error", - title: "Error during `cdklocal bootstrap`", + title: "Error during `lstk cdk bootstrap`", content: bootstrapRes.error.message, }); return events; @@ -663,7 +665,7 @@ async function executeCdkCommands( events.push({ type: "header", title: "🚀 Deploying CDK Stack", content: "" }); const deployRes = await runCommand( baseCommand, - ["deploy", "--require-approval", "never", "--all", ...contextArgs], + ["cdk", "deploy", "--require-approval", "never", "--all", ...contextArgs], { cwd: directory, env: buildIacCliEnv({ CI: "true" }) } ); const cleanDeployOutput = stripAnsiCodes(deployRes.stdout); @@ -679,7 +681,7 @@ async function executeCdkCommands( if (deployRes.error) { events.push({ type: "error", - title: "Error during `cdklocal deploy`", + title: "Error during `lstk cdk deploy`", content: deployRes.error.message, }); return events; @@ -689,7 +691,7 @@ async function executeCdkCommands( events.push({ type: "header", title: "💥 Destroying CDK Stack", content: "" }); const destroyRes = await runCommand( baseCommand, - ["destroy", "--force", "--all", ...contextArgs], + ["cdk", "destroy", "--force", "--all", ...contextArgs], { cwd: directory, env: buildIacCliEnv({ CI: "true" }) } ); events.push({ type: "output", content: stripAnsiCodes(destroyRes.stdout) }); @@ -698,7 +700,7 @@ async function executeCdkCommands( if (destroyRes.error) { events.push({ type: "error", - title: "Error during `cdklocal destroy`", + title: "Error during `lstk cdk destroy`", content: destroyRes.error.message, }); return events; diff --git a/tests/docker/validate-image.mjs b/tests/docker/validate-image.mjs index 5dce96f..2795be9 100644 --- a/tests/docker/validate-image.mjs +++ b/tests/docker/validate-image.mjs @@ -14,7 +14,6 @@ * docker run -i --rm \ * -v /var/run/docker.sock:/var/run/docker.sock \ * --add-host host.docker.internal:host-gateway \ - * --add-host s3.host.docker.internal:host-gateway \ * --add-host snowflake.localhost.localstack.cloud:host-gateway \ * -e LOCALSTACK_AUTH_TOKEN -e LOCALSTACK_HOSTNAME=host.docker.internal \ * -v "$PWD/data:/work/data" \ @@ -843,7 +842,7 @@ async function main() { /(completed successfully|Apply complete|bucket_name|Terraform Outputs)/i.test(r.text); record( "deploy", - "localstack-deployer terraform deploy (tflocal -> LS)", + "localstack-deployer terraform deploy (lstk terraform -> LS)", ok, snip(r.text, 600) ); @@ -852,7 +851,7 @@ async function main() { } } - // 7b. deployer CDK — validates cdklocal endpoint injection and path-style S3 asset uploads. + // 7b. deployer CDK — validates lstk cdk endpoint injection and path-style S3 asset uploads. if (!SKIP.has("deploy-cdk")) { try { const r = await callTool( @@ -866,10 +865,10 @@ async function main() { !ls.isError && /CDK stack deployed successfully/i.test(r.text) && ls.text.includes("mcp-cdk-sample-bucket") && - !/Error during `cdklocal/i.test(r.text); + !/Error during `lstk cdk/i.test(r.text); record( "deploy-cdk", - "localstack-deployer CDK deploy (cdklocal -> LS)", + "localstack-deployer CDK deploy (lstk cdk -> LS)", ok, `deploy: ${snip(r.text, 500)} | s3 ls: ${snip(ls.text, 160)}` );