diff --git a/localstack/POWER.md b/localstack/POWER.md new file mode 100644 index 0000000..ea7da58 --- /dev/null +++ b/localstack/POWER.md @@ -0,0 +1,218 @@ +--- +name: 'localstack' +displayName: 'Develop AWS apps with LocalStack' +description: 'Build, test, and debug AWS applications locally and in CI/CD using LocalStack. Manage the local cloud environment, deploy infrastructure with CDK/Terraform/SAM, analyze logs, enforce IAM policies, inject chaos faults, and manage state snapshots.' +keywords: + [ + 'localstack', + 'aws', + 'local', + 'cloud', + 'emulation', + 'testing', + 'lambda', + 's3', + 'dynamodb', + 'terraform', + 'cdk', + 'cloudformation', + 'iam', + 'chaos', + 'cloud-pods', + 'ephemeral', + 'mocking', + 'local-dev', + ] +author: 'LocalStack' +--- + +# LocalStack Power + +## Non-negotiable: MCP auth token handling (read before onboarding) + +Agents often try to **probe** `LOCALSTACK_AUTH_TOKEN` in the shell (“is it set?”). That leaks whether a secret exists in the environment and violates how this power configures auth (via MCP `env`, not your login shell). + +**Throughout onboarding until the Step 4 `localstack-docs` MCP call succeeds:** + +- **Never use the shell to probe MCP’s token** (`LOCALSTACK_AUTH_TOKEN` as wired into MCP `env`). +- Steps 3+ may use the terminal **only for LocalStack CLI** (`localstack auth show-token`, etc.) — never to test MCP’s injected env vars. + +**Banned examples — MCP token probing via shell (including but not limited to):** + +```bash +# NEVER run any of these (or variants) to “validate” MCP configuration: +echo "$LOCALSTACK_AUTH_TOKEN" +echo "LOCALSTACK_AUTH_TOKEN is set: $([ -n "$LOCALSTACK_AUTH_TOKEN" ] && echo YES || echo NO)" +test -n "$LOCALSTACK_AUTH_TOKEN" +[ -z "$LOCALSTACK_AUTH_TOKEN" ] +printenv LOCALSTACK_AUTH_TOKEN +env | grep LOCALSTACK +``` + +**What to do instead:** + +- **Step 2:** Ask the user in chat whether their IDE/MCP config supplies a **real** token for `LOCALSTACK_AUTH_TOKEN` (see Step 2 text below). Do not use the terminal for this step. +- **Step 4:** Call the **`localstack-docs`** MCP tool. That success or failure **is** the token/connectivity check. Do not pre-check via shell first. + +--- + +## Overview + +LocalStack is a fully functional local cloud stack that emulates AWS services on your machine. The LocalStack Power gives you intelligent tooling to manage your local cloud environment, deploy infrastructure, debug issues, and simulate real-world failure conditions — with no cloud waste. + +Every developer must use a LocalStack auth token (including free Hobby accounts); your plan tier determines which product features and MCP tools you can use. + +## Onboarding + +**CRITICAL: You MUST complete every step below in order. Do NOT skip ahead. After each step, mark it done before proceeding to the next.** + +### Onboarding Checklist + +- [ ] **Step 1 — Validate prerequisites are installed** +- [ ] **Step 2 — Validate auth token is configured for MCP (chat only; no terminal)** +- [ ] **Step 3 — Validate auth token is configured for CLI** +- [ ] **Step 4 — Confirm MCP connectivity** +- [ ] **Step 5 — Start LocalStack** + +--- + +### Step 1: Validate prerequisites are installed + +Run each check command. If a tool is missing, show the user the install link and STOP. Do NOT attempt to install anything automatically. + +| Tool | Check command | Install reference | +|------|--------------|-------------------| +| Docker | `docker --version` | https://docs.docker.com/get-docker/ | +| LocalStack CLI | `localstack --version` | `pip install localstack` or `brew install localstack/tap/localstack-cli` | +| Node.js v22+ | `node --version` | https://nodejs.org/ | +| awslocal | `which awslocal` | `pip install awscli-local` | + +**IMPORTANT validation rules:** +- `which awslocal` is the correct check. `awslocal --version` is NOT a valid command and will fail even when awslocal is installed correctly. +- If ALL tools are present, mark Step 1 done and proceed. +- If ANY tool is missing, tell the user what to install and STOP. Do not proceed until the user confirms installation. + +Optional IaC wrappers (only validate if user's project uses them): +- Terraform → `which tflocal` → `pip install terraform-local` +- CDK → `which cdklocal` → `npm install -g aws-cdk-local aws-cdk` +- SAM → `which samlocal` → `pip install aws-sam-cli-local` +- Pulumi → `which pulumilocal` → `pip install pulumi-local` + +--- + +### Step 2: Validate auth token is configured for MCP (**chat only — no terminal**) + +This step **must not** use the terminal at all — not even to print YES/NO. Shell profiles do not define what Kiro passes to MCP; probing `$LOCALSTACK_AUTH_TOKEN` trained the wrong workflow. + +The MCP server receives its auth token from the `env.LOCALSTACK_AUTH_TOKEN` entry in MCP config (bundled power `mcp.json` typically uses `${LOCALSTACK_AUTH_TOKEN}`; the user’s IDE **must** resolve that placeholder to a literal token when the server starts). + +**STOP if you touched the terminal for Step 2.** Close the terminal step sheet and redo Step 2 in chat only. + +**DO NOT (Step 2):** +- Run **any** shell command that expands, tests, or prints `LOCALSTACK_AUTH_TOKEN`, including `$([ -n "$LOCALSTACK_AUTH_TOKEN" ] && echo YES || echo NO)` and `grep`/`printenv`/`env` snippets +- Ask the user to export the token in their shell profile **as the MCP fix** +- Attempt to read or overwrite the user's token yourself + +**DO (Step 2), in order:** + +1. Ask the user (paraphrasing is fine): + + > "LocalStack MCP needs your auth token at `env.LOCALSTACK_AUTH_TOKEN` in your MCP server config — not only in `.zshrc` / `.bashrc`. Did you configure your IDE so **`${LOCALSTACK_AUTH_TOKEN}` resolves to your real token** when the MCP server starts? Tokens are issued at https://app.localstack.cloud/workspace/auth-token — please confirm yes/no." + +2. If **yes** → mark Step 2 done **without** probing the shell. Proceed to Step 3. You will validate MCP connectivity in Step 4. +3. If **no / unsure** → show them the intended shape of `env` once they’ve wired secrets in their IDE (**do not** ask them to paste the token here). STOP until they confirm they’ve configured and restarted MCP: + +```json +{ + "mcpServers": { + "localstack": { + "command": "npx", + "args": ["-y", "@localstack/localstack-mcp-server"], + "env": { + "LOCALSTACK_AUTH_TOKEN": "ls-your-actual-token-here" + } + } + } +} +``` + +--- + +### Step 3: Validate auth token is configured for CLI + +The CLI stores its own token separately from MCP. Run: + +```bash +localstack auth show-token +``` + +- If output shows `Valid: True` → mark Step 3 done. +- If output shows the token is not set or invalid → tell the user to run `localstack auth set-token ` and STOP until they confirm it's done. + +**DO NOT** run `localstack auth set-token` yourself or ask the user to paste their token into chat. + +--- + +### Step 4: Confirm MCP connectivity + +Do **not** run shell probes of `LOCALSTACK_AUTH_TOKEN` before or after failure — troubleshoot by explaining IDE/MCP wiring and restarting the server only. + +Call the **`localstack-docs`** MCP tool with a simple query (e.g., `"LocalStack overview"`). + +- If the tool responds successfully → mark Step 4 done. This confirms the MCP server is running and the token is accepted. +- If the tool fails → the MCP server is not connected. Tell the user to check their `mcp.json` configuration and restart the MCP server. STOP until resolved. + +**DO NOT** use `localstack-management` for this check — it requires Docker/LocalStack to be running. `localstack-docs` works without a running instance. + +--- + +### Step 5: Start LocalStack + +```bash +localstack start -d +``` + +Verify it's running: + +```bash +localstack status +``` + +- If status shows "running" → mark Step 5 done. Onboarding is complete. +- If it fails → check Docker is running (`docker info`) and port 4566 is free (`lsof -i :4566`). + +--- + +## Available Steering Files + +This power ships with focused steering files. Load only what the current task needs — do NOT read them all upfront. + +| Steering file | Load when the user is… | +|---------------|------------------------| +| `localstack-best-practices.md` | Doing day-to-day LocalStack development, running health checks, choosing between MCP tools and CLI, setting environment variables, or calling AWS services with `awslocal` | +| `iac-deployment.md` | Deploying infrastructure with Terraform, CDK, SAM, CloudFormation, or Pulumi (including `tflocal`, `cdklocal`, `samlocal`, `pulumilocal` workflows) | +| `state-management.md` | Working with Cloud Pods, `localstack state export/import`, or `PERSISTENCE=1` | +| `mcp-tools-reference.md` | Looking up an MCP tool signature, or working with chaos injection, IAM policy analysis, extensions, or ephemeral instances | +| `troubleshooting.md` | Debugging: LocalStack won't start, MCP server won't connect, services unhealthy, `awslocal` missing, Lambda/SQS misbehaving | + +Use the `readSteering` action to load a file on demand. If a task spans multiple areas, load the files in order of relevance rather than loading everything. + +## Quick Start (post-onboarding) + +Once onboarding is complete, try: + +``` +"Create an S3 bucket called my-test-bucket" +"Deploy my Terraform configuration to LocalStack" +"Show me any errors in the LocalStack logs" +"Save the current state as a Cloud Pod" +``` + +## Learn More + +- LocalStack Documentation: https://docs.localstack.cloud +- LocalStack GitHub: https://github.com/localstack/localstack +- LocalStack MCP Server: https://github.com/localstack/localstack-mcp-server +- Community Slack: https://localstack.cloud/slack +- LocalStack Extensions: https://docs.localstack.cloud/user-guide/extensions/ +- Cloud Pods Guide: https://docs.localstack.cloud/user-guide/state-management/cloud-pods/ diff --git a/localstack/mcp.json b/localstack/mcp.json new file mode 100644 index 0000000..629f9c4 --- /dev/null +++ b/localstack/mcp.json @@ -0,0 +1,18 @@ +{ + "mcpServers": { + "localstack": { + "command": "npx", + "args": ["-y", "@localstack/localstack-mcp-server"], + "env": { + "LOCALSTACK_AUTH_TOKEN": "${LOCALSTACK_AUTH_TOKEN}" + }, + "disabled": false, + "autoApprove": [ + "localstack-docs", + "localstack-logs-analysis", + "localstack-aws-client", + "localstack-management" + ] + } + } +} diff --git a/localstack/steering/iac-deployment.md b/localstack/steering/iac-deployment.md new file mode 100644 index 0000000..4b44643 --- /dev/null +++ b/localstack/steering/iac-deployment.md @@ -0,0 +1,235 @@ +# Infrastructure as Code Deployment with LocalStack + +Guidelines for deploying Terraform, CDK, CloudFormation, and Pulumi against LocalStack. + +## MCP: `localstack-deployer` + +In Kiro, use the **`localstack-deployer`** tool when the user wants to deploy from a project directory and the repo already uses `cdklocal`, `tflocal`, or `samlocal`. It runs the same wrappers the [LocalStack MCP server](https://github.com/localstack/localstack-mcp-server) documents, with automatic configuration detection where possible. + +```javascript +usePower('localstack', 'localstack', 'localstack-deployer', { + action: 'deploy', + projectType: 'terraform', + directory: './infra', +}); +``` + +Use terminal `tflocal` / `cdklocal` / `samlocal` when the user is iterating in their own shell, when paths or env are highly custom, or when `localstack-deployer` is not available. Combine with **`localstack-logs-analysis`** if deploys fail and you need structured errors. + +## Core Principle: Always Use Wrapper Tools + +LocalStack provides drop-in wrapper tools that automatically configure all AWS provider endpoints to point to `http://localhost:4566`. **ALWAYS** use these wrappers — they require zero changes to your existing IaC code. + +| Tool | Wrapper | Install | +|------|---------|---------| +| Terraform | `tflocal` | `pip install terraform-local` | +| AWS CDK | `cdklocal` | `npm install -g aws-cdk-local aws-cdk` | +| AWS SAM | `samlocal` | `pip install aws-sam-cli-local` | +| Pulumi | `pulumilocal` | `pip install pulumi-local` | +| AWS CLI | `awslocal` | `pip install awscli-local` | + +Only fall back to manual provider configuration if a wrapper tool cannot be installed (e.g., package manager unavailable in environment). + +--- + +## Terraform + +### Using tflocal (PREFERRED) + +```bash +# Install once +pip install terraform-local + +# Use exactly like terraform — no provider changes needed +tflocal init +tflocal plan +tflocal apply -auto-approve +tflocal destroy -auto-approve +``` + +### Manual Provider Configuration (FALLBACK ONLY) + +Only modify provider config if `tflocal` is unavailable. When using manual config, list endpoints for **every** AWS service used: + +```hcl +provider "aws" { + access_key = "test" + secret_key = "test" + region = "us-east-1" + + skip_credentials_validation = true + skip_metadata_api_check = true + skip_requesting_account_id = true + + endpoints { + s3 = "http://localhost:4566" + dynamodb = "http://localhost:4566" + lambda = "http://localhost:4566" + iam = "http://localhost:4566" + sqs = "http://localhost:4566" + sns = "http://localhost:4566" + # Add all other services used in your configuration + } +} +``` + +### Terraform Best Practices for LocalStack + +- **ALWAYS** use `tflocal` to avoid manual provider changes +- Run `tflocal plan` before `tflocal apply` to review changes +- Use `PERSISTENCE=1` with LocalStack to retain state across restarts +- Use Cloud Pods to save Terraform-deployed state for team sharing +- Test `tflocal destroy` to ensure cleanup works correctly + +--- + +## AWS CDK + +### Setup and Deployment + +```bash +# Install cdklocal (installs aws-cdk too) +npm install -g aws-cdk-local aws-cdk + +# Bootstrap LocalStack (first time per environment) +cdklocal bootstrap + +# Deploy all stacks (no approval needed locally) +cdklocal deploy --all --require-approval never + +# Deploy a specific stack +cdklocal deploy MyStack --require-approval never + +# Preview changes (equivalent to diff) +cdklocal diff + +# Synthesize to CloudFormation without deploying +cdklocal synth + +# Destroy all stacks +cdklocal destroy --all --force +``` + +### CDK Best Practices for LocalStack + +- **ALWAYS** run `cdklocal bootstrap` before the first deploy in a new environment +- Use `cdklocal synth` to validate CDK code generates valid CloudFormation before deploying +- Use `--require-approval never` for local development to skip manual confirmation prompts +- Use `cdklocal diff` to review what changes will be applied before deploying + +--- + +## CloudFormation + +### Deploy with awslocal + +```bash +# Create a new stack +awslocal cloudformation create-stack \ + --stack-name my-stack \ + --template-body file://template.yaml \ + --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM + +# Wait for stack creation to complete +awslocal cloudformation wait stack-create-complete \ + --stack-name my-stack + +# Update an existing stack +awslocal cloudformation update-stack \ + --stack-name my-stack \ + --template-body file://template.yaml \ + --capabilities CAPABILITY_IAM + +# Describe a stack and its outputs +awslocal cloudformation describe-stacks --stack-name my-stack | jq '.Stacks[0].Outputs' + +# List all stack resources +awslocal cloudformation list-stack-resources --stack-name my-stack + +# Delete a stack +awslocal cloudformation delete-stack --stack-name my-stack +``` + +### CloudFormation Best Practices for LocalStack + +- Use `--capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM` when templates create IAM resources +- Always `describe-stacks` after deployment to confirm stack status and retrieve outputs +- Use `wait` commands to ensure operations complete before proceeding + +--- + +## Pulumi + +### Using pulumilocal (PREFERRED) + +```bash +# Install once +pip install pulumi-local + +# Use exactly like pulumi — no config changes needed +pulumilocal preview +pulumilocal up --yes +pulumilocal destroy --yes +``` + +### Manual Configuration (FALLBACK ONLY) + +```bash +# Configure Pulumi to target LocalStack +pulumi config set aws:accessKey test +pulumi config set aws:secretKey test +pulumi config set aws:region us-east-1 +pulumi config set aws:skipCredentialsValidation true +pulumi config set aws:skipRequestingAccountId true +pulumi config set aws:s3UsePathStyle true +pulumi config set aws:endpoints '[{"s3":"http://localhost:4566","dynamodb":"http://localhost:4566","lambda":"http://localhost:4566"}]' +``` + +--- + +## General IaC Workflow with LocalStack + +### Recommended Development Loop + +1. **Start LocalStack with persistence**: + ```bash + PERSISTENCE=1 localstack start -d + ``` + +2. **Deploy your infrastructure**: + ```bash + tflocal apply -auto-approve + # or + cdklocal deploy --all --require-approval never + ``` + +3. **Verify resources were created**: + ```bash + awslocal s3 ls + awslocal dynamodb list-tables + awslocal lambda list-functions + ``` + +4. **Run your application or tests** against LocalStack. + +5. **Save state as a Cloud Pod** if you want to share it: + ```bash + localstack pod save my-feature-state + ``` + +6. **Iterate**: Make changes and re-deploy. + +7. **Clean up when done**: + ```bash + tflocal destroy -auto-approve + # or + cdklocal destroy --all --force + ``` + +### Troubleshooting Deployments + +- **Deployment fails immediately**: Check `localstack status` — LocalStack may not be running +- **Resources not created**: Review `localstack logs | grep -i error` for service-level errors +- **IAM errors with `ENFORCE_IAM=1`**: Switch to `ENFORCE_IAM=soft` to discover required permissions +- **CDK bootstrap errors**: Run `cdklocal bootstrap` before deploying for the first time +- **Terraform state issues**: The `tflocal` wrapper stores state locally; ensure it isn't referencing stale remote state diff --git a/localstack/steering/localstack-best-practices.md b/localstack/steering/localstack-best-practices.md new file mode 100644 index 0000000..f076f71 --- /dev/null +++ b/localstack/steering/localstack-best-practices.md @@ -0,0 +1,191 @@ +# LocalStack Development Best Practices + +Auto-loaded when working on LocalStack-related projects. + +## MCP tools in Kiro (prefer these first) + +The LocalStack Power wires the [LocalStack MCP Server](https://github.com/localstack/localstack-mcp-server). Use tools by name when they fit the task: + +- **`localstack-docs`** — Coverage, configuration, and how-to questions (works without a running LocalStack instance; good sanity check after auth setup). +- **`localstack-management`** — Start, stop, restart, and status of the LocalStack container; health-style checks without scripting Docker by hand. +- **`localstack-logs-analysis`** — Structured summaries, errors-by-service, and metrics from logs instead of asking the user to paste raw `localstack logs`. +- **`localstack-aws-client`** — Safe `awslocal` execution inside the configured container context (sanitized; avoids accidental real-AWS calls). +- **`localstack-iam-policy-analyzer`** — IAM enforcement modes, violations from logs, and generated policies when your plan tier includes this capability. + +Fall back to terminal commands when the user explicitly wants local scripts, CI logs, or the MCP server is unavailable — but default to MCP for interactive assistance. + +## General Principles + +- **ALWAYS** use `awslocal` instead of `aws` CLI when interacting with LocalStack. `awslocal` is a thin wrapper that automatically routes requests to `http://localhost:4566`. +- **ALWAYS** prefer LocalStack wrapper tools over vanilla IaC tools: `tflocal` over `terraform`, `cdklocal` over `cdk`, `samlocal` over `sam`, `pulumilocal` over `pulumi`. +- **NEVER** use real AWS credentials when working against LocalStack. Use dummy credentials: + ```bash + AWS_ACCESS_KEY_ID=test + AWS_SECRET_ACCESS_KEY=test + AWS_DEFAULT_REGION=us-east-1 + ``` +- **ALWAYS** verify LocalStack is running before executing commands: `localstack status` or `curl http://localhost:4566/_localstack/health`. +- **Test against LocalStack before AWS**: Catch configuration errors, IAM issues, and logic bugs locally before running up cloud costs. + +## Environment Configuration + +### Recommended Development Settings + +```bash +# Enable persistence so state survives restarts +PERSISTENCE=1 localstack start -d + +# Enable debug logging when troubleshooting +DEBUG=1 localstack start -d + +# Enable IAM soft enforcement to detect permission issues +ENFORCE_IAM=soft localstack start -d + +# Combine multiple settings +DEBUG=1 PERSISTENCE=1 ENFORCE_IAM=soft localstack start -d +``` + +### Key Environment Variables + +| Variable | Description | Recommended Value | +| --------------------- | -------------------------------------- | ---------------------------------------- | +| `DEBUG` | Enable verbose debug logging | `1` when troubleshooting | +| `PERSISTENCE` | Retain state across container restarts | `1` during development | +| `ENFORCE_IAM` | IAM policy enforcement mode | `soft` for discovery, `1` for validation | +| `GATEWAY_LISTEN` | LocalStack port | `4566` (default) | +| `LS_LOG` | Log level | `trace` for maximum verbosity | +| `LAMBDA_DEBUG` | Enable Lambda debug mode | `1` when debugging functions | +| `MAIN_CONTAINER_NAME` | Docker container name | `localstack-main` (default) | + +## AWS Service Interaction + +### Using awslocal + +```bash +# S3 operations +awslocal s3 mb s3://my-bucket +awslocal s3 cp file.txt s3://my-bucket/ +awslocal s3 ls s3://my-bucket/ + +# DynamoDB operations +awslocal dynamodb create-table \ + --table-name Users \ + --attribute-definitions AttributeName=id,AttributeType=S \ + --key-schema AttributeName=id,KeyType=HASH \ + --billing-mode PAY_PER_REQUEST +awslocal dynamodb put-item --table-name Users --item '{"id": {"S": "123"}}' + +# Lambda operations +awslocal lambda list-functions +awslocal lambda invoke \ + --function-name my-function \ + --payload '{"key": "value"}' \ + response.json + +# SQS operations +awslocal sqs create-queue --queue-name my-queue +awslocal sqs send-message --queue-url http://localhost:4566/000000000000/my-queue --message-body "hello" + +# CloudFormation +awslocal cloudformation create-stack \ + --stack-name my-stack \ + --template-body file://template.yaml +``` + +### Resource Naming + +- Use descriptive, consistent resource names that reflect their purpose +- Append environment suffixes where applicable: `my-table-dev`, `my-bucket-test` +- LocalStack uses account ID `000000000000` by default in resource ARNs + +## Health & Monitoring + +### Verifying Service Health + +```bash +# Check all services +curl http://localhost:4566/_localstack/health | jq + +# Check a specific service +curl http://localhost:4566/_localstack/health | jq '.services.s3' +curl http://localhost:4566/_localstack/health | jq '.services.lambda' + +# View LocalStack version info +curl http://localhost:4566/_localstack/info | jq +``` + +### Viewing Logs + +**In Kiro:** Prefer **`localstack-logs-analysis`** (modes such as errors, summary, or raw segments) before asking for full log dumps. + +**In a terminal:** + +```bash +# Follow logs in real time +localstack logs -f + +# View last N lines +localstack logs --tail 100 + +# Filter for a specific service +localstack logs | grep -i lambda + +# Filter for errors only +localstack logs | grep -i "error\|exception\|traceback" +``` + +## Container Lifecycle + +```bash +# Start LocalStack (detached) +localstack start -d + +# Check running status +localstack status + +# Stop gracefully +localstack stop + +# Restart (picks up new environment variables) +localstack restart + +# Force restart via Docker +docker restart localstack-main +``` + +## Endpoint Configuration + +All LocalStack services are available at `http://localhost:4566`. When manually configuring SDKs or clients: + +```python +# Python (boto3) +import boto3 +client = boto3.client( + "s3", + endpoint_url="http://localhost:4566", + aws_access_key_id="test", + aws_secret_access_key="test", + region_name="us-east-1" +) +``` + +```javascript +// JavaScript (AWS SDK v3) +import { S3Client } from '@aws-sdk/client-s3'; +const client = new S3Client({ + endpoint: 'http://localhost:4566', + region: 'us-east-1', + credentials: { accessKeyId: 'test', secretAccessKey: 'test' }, + forcePathStyle: true, // Required for S3 +}); +``` + +## Troubleshooting Checklist + +1. **Is LocalStack running?** → `localstack status`, or **`localstack-management`** with a status action in Kiro +2. **Are the services initialized?** → `curl http://localhost:4566/_localstack/health | jq` +3. **Are you using the right endpoint?** → `http://localhost:4566` +4. **Are you using awslocal/wrapper tools?** → Not bare `aws`, `terraform`, `cdk` +5. **Is your auth token configured (MCP and CLI)?** → **Do not** use `echo $LOCALSTACK_AUTH_TOKEN` — the MCP token lives in Power `mcp.json`. For CLI, run `localstack auth show-token` and expect `Valid: True`, or use **`localstack-docs`** in Kiro to confirm MCP auth. If the token is valid but a feature still fails, check whether your **plan tier** includes that capability. +6. **Are there errors in the logs?** → **`localstack-logs-analysis`** in Kiro, or `localstack logs | grep -i error` in a terminal +7. **Does the resource exist?** → **`localstack-aws-client`** or `awslocal list-` diff --git a/localstack/steering/mcp-tools-reference.md b/localstack/steering/mcp-tools-reference.md new file mode 100644 index 0000000..786a775 --- /dev/null +++ b/localstack/steering/mcp-tools-reference.md @@ -0,0 +1,183 @@ +# MCP Tools Reference + +Complete reference for all LocalStack MCP tools available through this Power. + +## MCP-First Principle + +When helping in Kiro, **prefer MCP tools** over unstructured shell commands so behavior stays consistent with the [LocalStack MCP Server](https://github.com/localstack/localstack-mcp-server): + +| Goal | Prefer | Instead of | +|------|--------|------------| +| Start/stop/restart or health | `localstack-management` | Raw `docker` commands | +| Deploy CDK/Terraform/SAM | `localstack-deployer` | Manual `tflocal`/`cdklocal` without project detection | +| Read or summarize logs | `localstack-logs-analysis` | Pasting huge `localstack logs` output | +| Run AWS API calls against LocalStack | `localstack-aws-client` | Unsanitized `aws` against real AWS endpoints | +| IAM violations / least-privilege drafts | `localstack-iam-policy-analyzer` | Hand-written IAM from guesses | +| Cloud Pods snapshots | `localstack-cloud-pods` | Only CLI `localstack pod` when MCP fits | +| Chaos / faults | `localstack-chaos-injector` | Ad hoc failure injection scripts | +| Docs and coverage questions | `localstack-docs` | Generic web search only | + +Tools that depend on your subscription tier still require a valid auth token and the right plan for that capability. + +--- + +## Container Management + +**`localstack-management`** — Start, stop, restart, and check the status of your LocalStack container. Injects environment variables and monitors health. + +```javascript +usePower('localstack', 'localstack', 'localstack-management', { + action: 'start', + envVars: { DEBUG: '1', PERSISTENCE: '1' }, +}); +``` + +--- + +## Infrastructure Deployment + +**`localstack-deployer`** — Deploy CDK, Terraform, and SAM infrastructure to LocalStack automatically using the `cdklocal`, `tflocal`, and `samlocal` wrapper tools. + +```javascript +usePower('localstack', 'localstack', 'localstack-deployer', { + action: 'deploy', + projectType: 'terraform', + directory: './infra', +}); +``` + +--- + +## AWS CLI Execution + +**`localstack-aws-client`** — Execute `awslocal` CLI commands inside the running LocalStack container. Commands are sanitized to prevent shell injection. + +```javascript +usePower('localstack', 'localstack', 'localstack-aws-client', { + command: 's3 ls', +}); +``` + +--- + +## Log Analysis + +**`localstack-logs-analysis`** — Analyze LocalStack logs for errors, API request patterns, service call metrics, and failure summaries. Supports filtering by service and operation. + +```javascript +usePower('localstack', 'localstack', 'localstack-logs-analysis', { + analysisType: 'errors', + service: 'lambda', +}); +``` + +--- + +## IAM Policy Analyzer + +**`localstack-iam-policy-analyzer`** — Set IAM enforcement levels, detect permission violations, and auto-generate least-privilege IAM policies based on actual access patterns. **Plan tier:** may require a higher tier than Hobby. + +```javascript +usePower('localstack', 'localstack', 'localstack-iam-policy-analyzer', { + action: 'set-mode', + mode: 'SOFT_MODE', +}); +``` + +```javascript +usePower('localstack', 'localstack', 'localstack-iam-policy-analyzer', { + action: 'analyze-policies', +}); +``` + +### IAM Workflows + +- **Start with soft enforcement**: Use `ENFORCE_IAM=soft` to discover required permissions without breaking your application. +- **Generate policies from usage**: Let LocalStack observe actual API calls in soft mode, then use the analyzer to generate a least-privilege policy. +- **Mirror production IAM**: Configure LocalStack IAM to match production roles and policies to catch permission issues before deploying. + +--- + +## Chaos Engineering + +**`localstack-chaos-injector`** — Inject network latency, service errors, and fault rules to simulate real-world failure conditions. **Plan tier:** may require a higher tier than Hobby. + +```javascript +usePower('localstack', 'localstack', 'localstack-chaos-injector', { + action: 'inject-latency', + latency_ms: 500, +}); +``` + +```javascript +usePower('localstack', 'localstack', 'localstack-chaos-injector', { + action: 'inject-faults', + rules: [ + { + service: 'dynamodb', + region: 'us-east-1', + operation: 'PutItem', + probability: 0.2, + error: { statusCode: 503, code: 'ServiceUnavailable' }, + }, + ], +}); +``` + +### Chaos Best Practices + +- **Always clean up faults**: Use `action: 'clear-all-faults'` (and `clear-latency`) before running functional tests. +- **Test one failure mode at a time**: Isolate how your application responds to a single service or operation failure. +- **Combine with Cloud Pods**: Save a known-good state before injecting chaos so you can quickly restore after testing. + +--- + +## Cloud Pods (State Snapshots) + +**`localstack-cloud-pods`** — Save and load state snapshots to reproduce environments, share state across team members, and preload CI/CD pipelines. **Plan tier:** Cloud Pods often require a paid or team tier. + +```javascript +usePower('localstack', 'localstack', 'localstack-cloud-pods', { + action: 'save', + pod_name: 'my-feature-branch-state', +}); +``` + +--- + +## Extensions + +**`localstack-extensions`** — Install, list, and uninstall LocalStack Extensions from the marketplace (e.g., MailHog for SES email capture). **Plan tier:** may require a higher tier than Hobby. + +```javascript +usePower('localstack', 'localstack', 'localstack-extensions', { + action: 'install', + name: 'localstack-extension-mailhog', +}); +``` + +--- + +## Ephemeral Instances + +**`localstack-ephemeral-instances`** — Launch and manage temporary cloud-hosted LocalStack instances for CI/CD pipelines, demos, and isolated testing. **Plan tier:** may require a higher tier than Hobby. + +```javascript +usePower('localstack', 'localstack', 'localstack-ephemeral-instances', { + action: 'create', + name: 'ci-preview-1', + lifetime: 60, +}); +``` + +--- + +## Documentation Search + +**`localstack-docs`** — Search the official LocalStack documentation. No running LocalStack instance required. Also useful as a lightweight connectivity check after auth setup. + +```javascript +usePower('localstack', 'localstack', 'localstack-docs', { + query: 'how to configure SQS with LocalStack', +}); +``` diff --git a/localstack/steering/state-management.md b/localstack/steering/state-management.md new file mode 100644 index 0000000..d9ad793 --- /dev/null +++ b/localstack/steering/state-management.md @@ -0,0 +1,194 @@ +# LocalStack State Management + +Guidelines for managing LocalStack state with local snapshots, Cloud Pods, and persistence. + +## MCP: `localstack-cloud-pods` + +For Cloud Pod workflows inside Kiro (where your plan allows), use **`localstack-cloud-pods`** to save, load, list, or reset state when the user wants snapshot operations without hand-rolling CLI flags. It aligns with the [LocalStack MCP server](https://github.com/localstack/localstack-mcp-server) implementation. Local **`localstack state export` / `import`** remains the right choice for file-based snapshots that stay entirely on disk. + +```javascript +usePower('localstack', 'localstack', 'localstack-cloud-pods', { + action: 'save', + pod_name: 'my-feature-branch-state', +}); +``` + +## Overview + +LocalStack provides three mechanisms for state management: + +| Mechanism | Storage | Typical plan access | Best For | +|-----------|---------|----------------------|----------| +| Local Persistence (`PERSISTENCE=1`) | Local disk | Any authenticated user | Simple dev-loop state retention | +| Local Snapshots (`state export/import`) | Local files | Any authenticated user | CI/CD, backups, version control | +| Cloud Pods (`pod save/load`) | LocalStack cloud | Often a paid or team tier—confirm in workspace | Team sharing, cross-machine access | + +--- + +## Local Persistence + +Enable automatic state retention across LocalStack restarts with no extra steps: + +```bash +# Start with persistence enabled +PERSISTENCE=1 localstack start -d + +# State is stored in .localstack/ in the current directory +# All resources survive container stop/start +``` + +**Use when**: You want resources to automatically survive `localstack restart` during development. + +--- + +## Local Snapshots (State Export/Import) + +Export and import LocalStack state to/from local zip files. Available to all authenticated users; does not use Cloud Pod cloud storage. + +### Exporting State + +```bash +# Export current state to a file +localstack state export my-state.zip + +# Export to a specific path +localstack state export /path/to/backups/state-$(date +%Y%m%d).zip +``` + +### Importing State + +```bash +# Import state from a file (replaces current state) +localstack state import my-state.zip + +# Import from a specific path +localstack state import /path/to/backups/state-20250101.zip +``` + +### Use Cases for Local Snapshots + +- **CI/CD pipelines**: Commit state files to the repo so tests always start from a known baseline +- **Pre-destructive backups**: Export before running `tflocal destroy` or mass deletes +- **Offline development**: Share state files via Git, email, or USB when cloud connectivity isn't available + +--- + +## Cloud Pods + +Cloud Pods store state in LocalStack's cloud platform for team collaboration and remote access. **Availability depends on your plan tier**—confirm Cloud Pods are enabled for your account before relying on them. + +### Prerequisites + +Authenticate once on the machine (preferred over ad hoc `export` in every shell): + +```bash +localstack auth set-token +``` + +Confirm: `localstack auth show-token` should report `Valid: True`. For Kiro-only workflows, ensure the Power's `mcp.json` also supplies `LOCALSTACK_AUTH_TOKEN` to the MCP server. + +### Saving State + +```bash +# Save current state to a named Cloud Pod +localstack pod save my-pod-name + +# Save with a descriptive message +localstack pod save sprint-42-demo --message "Demo state: S3, DynamoDB, and Lambda configured" +``` + +### Loading State + +```bash +# Load state from a Cloud Pod (replaces current state) +localstack pod load my-pod-name + +# Load and merge with existing state (preserves current resources) +localstack pod load my-pod-name --merge +``` + +### Managing Cloud Pods + +```bash +# List all available Cloud Pods +localstack pod list + +# View details of a specific Cloud Pod +localstack pod inspect my-pod-name + +# Delete a Cloud Pod +localstack pod delete my-pod-name +``` + +### Cloud Pod Use Cases + +- **Team baseline environments**: Save a configured state that all developers load when starting work +- **Feature branch isolation**: Each branch saves its own Cloud Pod (`pod save feature-auth-rework`) +- **Demo preparation**: Prepare a demo-ready state and load it on any machine before presenting +- **Cross-machine development**: Access the same state from your laptop and CI/CD runner + +--- + +## Recommended Workflows + +### Individual developer (persistence and local snapshots) + +```bash +# Start with persistence for basic state retention +PERSISTENCE=1 localstack start -d + +# Deploy your infrastructure +tflocal apply -auto-approve + +# Save a snapshot before risky operations +localstack state export before-migration.zip + +# After testing, restore if needed +localstack state import before-migration.zip +``` + +### Team collaboration (Cloud Pods) + +```bash +# Team lead sets up baseline environment +localstack start -d +# ... creates resources, deploys infrastructure ... +localstack pod save team-dev-baseline --message "S3 buckets, DynamoDB tables, Lambda functions for sprint 42" + +# Each developer loads the shared baseline (token via CLI config, not per-session export) +localstack auth set-token +localstack start -d +localstack pod load team-dev-baseline + +# Developer saves their branch state before sharing +localstack pod save feature-user-auth --message "User auth Lambda + DynamoDB table" +``` + +### CI/CD Pipeline + +```bash +# Option 1: Use exported state file (committed to repo) +localstack start -d +localstack state import ./ci/baseline-state.zip +# Run tests +pytest tests/ + +# Option 2: Load a Cloud Pod (no state file in repo; requires Cloud Pods on your plan) +# In CI, set token once via `localstack auth set-token` in the job image, or inject LOCALSTACK_AUTH_TOKEN for that process only +localstack start -d +localstack pod load ci-test-baseline +# Run tests +pytest tests/ +``` + +--- + +## Best Practices + +- **ALWAYS** use descriptive names for Cloud Pods and snapshot files: `feature-auth-sprint42` not `state1` +- **ALWAYS** add messages to Cloud Pod saves: `--message "What resources are in this state"` +- **Use `state export` before destructive operations**: Create a checkpoint you can restore from +- **Commit baseline state files to version control** for reproducible CI/CD pipelines +- **Use Cloud Pods for team collaboration**, local snapshots for personal backups +- **Combine with `PERSISTENCE=1`** during active development to avoid accidentally losing state on restarts +- **Keep Cloud Pods current**: Delete outdated pods to avoid confusion (`localstack pod list` then `localstack pod delete old-pod-name`) diff --git a/localstack/steering/troubleshooting.md b/localstack/steering/troubleshooting.md new file mode 100644 index 0000000..79a01ac --- /dev/null +++ b/localstack/steering/troubleshooting.md @@ -0,0 +1,94 @@ +# LocalStack Troubleshooting + +Debugging guide for common LocalStack issues. + +## LocalStack Won't Start + +```bash +# Check if port 4566 is already in use +lsof -i :4566 + +# Check Docker is running +docker info + +# View startup logs +localstack start 2>&1 | head -50 + +# Force stop and restart +localstack stop +localstack start -d +``` + +## MCP Server Not Connecting + +1. Confirm the token in the Power's `mcp.json` is a real value (not `${LOCALSTACK_AUTH_TOKEN}` unless your IDE resolves it at launch). +2. Ensure Node.js v22+ is installed: `node --version` +3. Test MCP connectivity by calling `localstack-docs` with any query — this does NOT require LocalStack to be running. +4. If `localstack-docs` fails, the MCP server itself is not starting. Check Kiro's MCP server logs. +5. As a last resort, smoke-test the MCP package outside Kiro by running it with the token inline for one process: `LOCALSTACK_AUTH_TOKEN=your-token npx -y @localstack/localstack-mcp-server`. Prefer verifying from inside Kiro via `localstack-docs` whenever possible. + +**DO NOT** use the shell to verify MCP auth, including `$([ -n "$LOCALSTACK_AUTH_TOKEN" ] && echo YES || echo NO)`, `echo`, `printenv`, or `grep` on `LOCALSTACK`. The MCP token is injected from IDE/MCP configuration, which is unrelated to interactive shell profiles. Prefer a **`localstack-docs`** MCP call as the smoke test. + +## Services Not Available + +```bash +# Check service health +curl http://localhost:4566/_localstack/health | jq '.services' + +# Restart with debug mode +localstack stop && DEBUG=1 localstack start -d +``` + +## awslocal Command Not Found + +```bash +pip install awscli-local +# Verify installation (use 'which', not '--version') +which awslocal +``` + +`awslocal --version` will fail even when correctly installed — always use `which awslocal`. + +## Feature or MCP Tool Not Available + +1. Verify your auth token is valid at https://app.localstack.cloud/ +2. For Kiro: confirm the MCP `env.LOCALSTACK_AUTH_TOKEN` value in `mcp.json` is correct — use an MCP tool call to confirm, not `echo` in bash. +3. For CLI: run `localstack auth show-token` and confirm `Valid: True`. +4. Confirm your **plan tier** includes the feature or MCP capability you're using (some tools need a higher tier than Hobby). + +## Common Workflow Issues + +### Deployment Fails + +- Check `localstack status` — LocalStack may not be running +- Review logs: use `localstack-logs-analysis` MCP tool or `localstack logs | grep -i error` +- IAM errors with `ENFORCE_IAM=1`: switch to `ENFORCE_IAM=soft` to discover required permissions +- CDK bootstrap errors: run `cdklocal bootstrap` before first deploy + +### Lambda Not Executing + +```bash +# Check function exists +awslocal lambda list-functions + +# Check logs for the function +awslocal logs describe-log-groups +awslocal logs get-log-events --log-group-name /aws/lambda/my-function --log-stream-name $(awslocal logs describe-log-streams --log-group-name /aws/lambda/my-function --query 'logStreams[0].logStreamName' --output text) +``` + +### SQS Not Triggering Lambda + +```bash +# Verify event source mapping exists +awslocal lambda list-event-source-mappings + +# Check queue has messages +awslocal sqs get-queue-attributes --queue-url http://localhost:4566/000000000000/my-queue --attribute-names All +``` + +## Debugging Tips + +- **Enable debug logging**: Start with `DEBUG=1` when troubleshooting. Use `LS_LOG=trace` for maximum verbosity. +- **Use the logs analysis tool**: Instead of grepping raw logs, use `localstack-logs-analysis` for structured error summaries. +- **Check health endpoints**: `curl http://localhost:4566/_localstack/health | jq` shows which services are available. +- **Container name**: Default is `localstack-main`. Use `docker logs localstack-main` for raw Docker logs.