Claude Code से AWS Deployment: CDK, GitHub Actions, IAM, Logs और Rollback
Claude Code से छोटी AWS API deploy करें: CDK, OIDC, least-privilege IAM, logs, rollback और cost guardrails के साथ।
Claude Code से AWS deployment कराते समय सबसे बड़ा जोखिम यह है कि हम सिर्फ “AWS architecture बना दो” कहें और generated answer को production-ready मान लें। असली deployment में diagram से ज्यादा जरूरी चीजें होती हैं: चलने वाला infrastructure code, सीमित IAM permissions, secrets handling, logs, rollback और cost control.
इस guide में हम छोटे web app या API के लिए एक सुरक्षित path implement करेंगे: API Gateway + Lambda + AWS CDK + GitHub Actions. CDK यानी Infrastructure as Code: AWS console में manually बनने वाले resources को code में define करना। IAM वह permission system है जो तय करता है कि कौन क्या कर सकता है। OIDC से GitHub Actions temporary AWS credentials लेकर deploy कर सकता है, इसलिए long-lived AWS access keys GitHub Secrets में रखने की जरूरत नहीं होती।
Claude Code यहाँ उपयोगी है क्योंकि वह repository पढ़ सकता है, कई files edit कर सकता है, cdk synth और cdk diff चला सकता है, deployment errors समझा सकता है और workflow को documentation में बदल सकता है। Product behavior के लिए Claude Code official docs देखें। AWS details के लिए AWS CDK NodejsFunction, API Gateway Lambda proxy integration, Lambda environment variables, Lambda CloudWatch Logs और IAM best practices को source of truth रखें।
पहले AWS target चुनें
Target अस्पष्ट होगा तो Claude Code जरूरत से बड़ी architecture बना सकता है। पहले workload का आकार तय करें।
| Option | कब इस्तेमाल करें | फायदा | ध्यान रखें |
|---|---|---|---|
| Lambda + API Gateway | छोटी APIs, contact forms, webhooks, हल्का admin backend | Server management कम, low traffic में शुरुआत आसान | Long-running jobs, persistent connections या बड़े containers के लिए सही नहीं |
| ECS/Fargate + ALB | Docker APIs, always-on services, API plus workers | Container flexibility ज्यादा, existing apps migrate करना आसान | VPC, ALB, task definitions, scaling और image build manage करने होंगे |
| Amplify या S3 + CloudFront | Static sites, SPA, frontend-heavy apps | CDN delivery तेज और operation सरल | API, auth और backend jobs अलग design होंगे |
इस article में Lambda + API Gateway चुना गया है क्योंकि consulting में यह सवाल बहुत आता है: “छोटी API को AWS पर safely deploy करना है, लेकिन शुरुआत में over-engineering नहीं चाहिए.” Related reading के लिए Claude Code AWS Lambda guide, Claude Code AWS IAM guide, Claude Code API Gateway guide और Claude Code security best practices देखें।
flowchart LR
User[User] --> Api[API Gateway]
Api --> Fn[Lambda Node.js API]
Fn --> Secret[Secrets Manager]
Fn --> Logs[CloudWatch Logs]
GitHub[GitHub Actions OIDC] --> CDK[AWS CDK deploy]
CDK --> Api
CDK --> Fn
Practical use cases
पहला use case contact या lead form है। Frontend existing website पर रह सकता है और submission endpoint API Gateway + Lambda पर जाता है। API Gateway throttling, API key और CloudWatch Logs से spam और incidents debug करना आसान होता है।
दूसरा use case SaaS MVP API है। शुरुआत /v1/health, /v1/contact, /v1/webhook जैसी छोटी routes से करें। Claude Code को साफ लिखें कि VPC, RDS, queues और containers अभी नहीं चाहिए, जब तक requirement सच में न आए।
तीसरा use case internal automation webhook है: Slack alerts, CMS callbacks, approval flows या छोटी admin actions। Lambda तब अच्छा है जब हर request जल्दी खत्म हो। Retry, long processing या fan-out चाहिए तो SQS या Step Functions सोच-समझकर जोड़ें।
चौथा use case manual deployment को CI/CD में बदलना है। कई teams laptop से deploy करती हैं या AWS console में click करती हैं। Claude Code इस process को CDK और GitHub Actions में ला सकता है, लेकिन production approval, rollback और risk decision इंसानों को ही रखने चाहिए।
Claude Code के लिए deployment rules
Repository root में CLAUDE.md बनाएं। यह guardrail है ताकि छोटी API महंगी platform rewrite में न बदल जाए।
# AWS deployment rules
- Use AWS CDK v2 and TypeScript.
- Target region: ap-south-1 unless explicitly changed.
- Do not create VPC resources for this small API unless required.
- Prefer API Gateway + Lambda for the first release.
- Runtime secrets must come from AWS Secrets Manager, not plaintext env vars.
- Use IAM grants such as secret.grantRead(handler) instead of wildcard policies.
- Add CloudWatch log retention and reserved concurrency.
- Before deploy, run npm test, npx cdk synth, and npx cdk diff.
- Never paste AWS access keys into files or GitHub Secrets.
Claude Code को task ऐसे दें:
इस repository में CDK v2 SmallApiStack add करें।
API Gateway REST API और Node.js 20 Lambda बनाएं जिसमें /v1/health और /v1/contact हों।
Runtime config Secrets Manager secret prod/claude-code-demo/api से पढ़ें।
Lambda execution role को least privilege रखें, CloudWatch log retention, reserved concurrency और API Gateway throttling add करें।
GitHub Actions deploy workflow सिर्फ OIDC use करे। Long-lived AWS keys use न करें।
Edit के बाद npm test, npx cdk synth और npx cdk diff चलाएं और result explain करें।
CDK project बनाएं
आपके पास Node.js, AWS CLI v2, AWS CDK CLI और authenticated AWS profile होना चाहिए। Commands Bash के लिए हैं; Windows पर WSL या Git Bash इस्तेमाल करें।
mkdir claude-code-aws-api
cd claude-code-aws-api
npx cdk init app --language typescript
npm install @aws-sdk/client-secrets-manager
npm install --save-dev esbuild @types/aws-lambda
mkdir -p lambda
aws sts get-caller-identity
Runtime config पहले बना दें। Real API keys, database passwords और external tokens Git में या plaintext Lambda env vars में नहीं जाने चाहिए।
aws secretsmanager create-secret \
--name prod/claude-code-demo/api \
--secret-string '{"supportQueue":"aws-consulting"}' \
--region ap-south-1
Lambda handler implement करें
lambda/handler.ts बनाएं। Code सिर्फ operational metadata log करता है, पूरा request body या secrets नहीं।
import type {
APIGatewayProxyEvent,
APIGatewayProxyResult,
} from "aws-lambda";
import {
GetSecretValueCommand,
SecretsManagerClient,
} from "@aws-sdk/client-secrets-manager";
const secrets = new SecretsManagerClient({});
let cachedConfig: Record<string, string> | undefined;
async function loadConfig(): Promise<Record<string, string>> {
if (cachedConfig) return cachedConfig;
const secretArn = process.env.SECRET_ARN;
if (!secretArn) throw new Error("SECRET_ARN is not configured");
const result = await secrets.send(
new GetSecretValueCommand({ SecretId: secretArn }),
);
cachedConfig = JSON.parse(result.SecretString ?? "{}");
return cachedConfig;
}
function json(statusCode: number, body: unknown): APIGatewayProxyResult {
return {
statusCode,
headers: {
"content-type": "application/json",
"cache-control": "no-store",
},
body: JSON.stringify(body),
};
}
export async function handler(
event: APIGatewayProxyEvent,
): Promise<APIGatewayProxyResult> {
try {
if (event.httpMethod === "GET" && event.path.endsWith("/v1/health")) {
return json(200, {
ok: true,
stage: process.env.STAGE ?? "dev",
});
}
if (event.httpMethod === "POST" && event.path.endsWith("/v1/contact")) {
const body = JSON.parse(event.body ?? "{}") as {
email?: string;
message?: string;
};
if (!body.email || !body.message) {
return json(400, { ok: false, message: "email and message required" });
}
const config = await loadConfig();
const emailDomain = body.email.split("@")[1] ?? "unknown";
console.log(
JSON.stringify({
event: "contact_received",
emailDomain,
messageLength: body.message.length,
}),
);
return json(202, {
ok: true,
routedTo: config.supportQueue ?? "manual",
});
}
return json(404, { ok: false, message: "not found" });
} catch (error) {
console.error("handler_error", error);
return json(500, { ok: false, message: "internal error" });
}
}
CDK stack implement करें
lib/small-api-stack.ts को नीचे वाले code से बदलें। Important points हैं appSecret.grantRead(handler), log retention, reserved concurrency, throttling और dataTraceEnabled: false, ताकि production logs में request body न जाए।
import * as cdk from "aws-cdk-lib";
import * as apigateway from "aws-cdk-lib/aws-apigateway";
import * as iam from "aws-cdk-lib/aws-iam";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as nodejs from "aws-cdk-lib/aws-lambda-nodejs";
import * as logs from "aws-cdk-lib/aws-logs";
import * as secretsmanager from "aws-cdk-lib/aws-secretsmanager";
import { Construct } from "constructs";
import * as path from "path";
export class SmallApiStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const appSecret = secretsmanager.Secret.fromSecretNameV2(
this,
"AppSecret",
"prod/claude-code-demo/api",
);
const handler = new nodejs.NodejsFunction(this, "ApiHandler", {
functionName: "claude-code-small-api-prod",
entry: path.join(__dirname, "../lambda/handler.ts"),
handler: "handler",
runtime: lambda.Runtime.NODEJS_20_X,
architecture: lambda.Architecture.ARM_64,
memorySize: 256,
timeout: cdk.Duration.seconds(10),
logRetention: logs.RetentionDays.ONE_MONTH,
reservedConcurrentExecutions: 20,
environment: {
STAGE: "prod",
SECRET_ARN: appSecret.secretArn,
},
bundling: {
minify: true,
sourceMap: true,
externalModules: ["@aws-sdk/*"],
},
});
appSecret.grantRead(handler);
handler.addToRolePolicy(
new iam.PolicyStatement({
actions: ["cloudwatch:PutMetricData"],
resources: ["*"],
conditions: {
StringEquals: {
"cloudwatch:namespace": "ClaudeCodeLab/SmallApi",
},
},
}),
);
const api = new apigateway.RestApi(this, "SmallApi", {
restApiName: "claude-code-small-api",
cloudWatchRole: true,
deployOptions: {
stageName: "prod",
metricsEnabled: true,
loggingLevel: apigateway.MethodLoggingLevel.INFO,
dataTraceEnabled: false,
throttlingRateLimit: 20,
throttlingBurstLimit: 40,
},
});
const v1 = api.root.addResource("v1");
v1.addResource("health").addMethod(
"GET",
new apigateway.LambdaIntegration(handler),
);
v1.addResource("contact").addMethod(
"POST",
new apigateway.LambdaIntegration(handler),
{ apiKeyRequired: true },
);
const apiKey = api.addApiKey("ClientApiKey", {
apiKeyName: "claude-code-small-api-prod-client",
});
const usagePlan = api.addUsagePlan("BasicUsagePlan", {
throttle: { rateLimit: 10, burstLimit: 20 },
quota: { limit: 1000, period: apigateway.Period.MONTH },
});
usagePlan.addApiKey(apiKey);
usagePlan.addApiStage({ stage: api.deploymentStage });
new cdk.CfnOutput(this, "ApiUrl", { value: api.url });
}
}
bin/ entry file भी update करें।
#!/usr/bin/env node
import * as cdk from "aws-cdk-lib";
import { SmallApiStack } from "../lib/small-api-stack";
const app = new cdk.App();
new SmallApiStack(app, "SmallApiProdStack", {
env: {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION ?? "ap-south-1",
},
});
Deploy से पहले diff देखें
किसी account और region में CDK पहली बार deploy करने से पहले bootstrap चाहिए।
export AWS_REGION=ap-south-1
export AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
npx cdk bootstrap "aws://${AWS_ACCOUNT_ID}/${AWS_REGION}"
npm test
npx cdk synth
npx cdk diff SmallApiProdStack
npx cdk deploy SmallApiProdStack --require-approval never
Claude Code से cdk diff explain करवाएं, खासकर IAM changes। अगर वह किसी permission की जरूरत साफ नहीं बता पाता, तो production से पहले human review जरूरी है।
API test और logs
CloudFormation output से API URL लें और routes call करें।
API_URL=$(aws cloudformation describe-stacks \
--stack-name SmallApiProdStack \
--query "Stacks[0].Outputs[?OutputKey=='ApiUrl'].OutputValue" \
--output text)
curl "${API_URL}v1/health"
KEY_ID=$(aws apigateway get-api-keys \
--name-query claude-code-small-api-prod-client \
--query "items[0].id" \
--output text)
API_KEY=$(aws apigateway get-api-key \
--api-key "$KEY_ID" \
--include-value \
--query "value" \
--output text)
curl -X POST "${API_URL}v1/contact" \
-H "content-type: application/json" \
-H "x-api-key: ${API_KEY}" \
-d '{"email":"masa@example.com","message":"AWS deployment consultation"}'
Lambda logs tail करें:
aws logs tail "/aws/lambda/claude-code-small-api-prod" \
--since 1h \
--follow
CloudWatch Logs आने में कुछ मिनट लग सकते हैं। तुरंत log न दिखना deployment failure नहीं है।
GitHub Actions OIDC से deploy
AWS Access Keys को GitHub Secrets में save न करें। AWS में OIDC provider और deployment role बनाएं, फिर trust policy को exact repository और branch तक सीमित करें।
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
},
"StringLike": {
"token.actions.githubusercontent.com:sub": "repo:your-org/your-repo:ref:refs/heads/main"
}
}
}
]
}
.github/workflows/deploy-aws.yml:
name: deploy-aws-cdk
on:
push:
branches: ["main"]
workflow_dispatch:
permissions:
id-token: write
contents: read
concurrency:
group: prod-aws-cdk
cancel-in-progress: false
jobs:
deploy:
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/github-cdk-deploy-prod
aws-region: ap-south-1
- run: npm ci
- run: npm test
- run: npx cdk synth
- run: npx cdk diff SmallApiProdStack
- run: npx cdk deploy SmallApiProdStack --require-approval never
Deployment role की permission policy आपके CDK bootstrap model, CloudFormation execution role और organization guardrails पर depend करती है। Production में AdministratorAccess default न रखें। Practical approach है: OIDC trust condition narrow करें, permission boundaries use करें और stable होने के बाद IAM Access Analyzer से permissions घटाएं।
Cost guardrails जोड़ें
छोटी serverless API भी loop, spam या ज्यादा logs से bill बढ़ा सकती है। ऊपर वाला stack API throttling, usage plan और Lambda reserved concurrency रखता है। Production से पहले AWS Budgets add करें।
{
"BudgetName": "small-api-monthly-guardrail",
"BudgetLimit": {
"Amount": "20",
"Unit": "USD"
},
"TimeUnit": "MONTHLY",
"BudgetType": "COST"
}
[
{
"Notification": {
"NotificationType": "ACTUAL",
"ComparisonOperator": "GREATER_THAN",
"Threshold": 80,
"ThresholdType": "PERCENTAGE"
},
"Subscribers": [
{
"SubscriptionType": "EMAIL",
"Address": "owner@example.com"
}
]
}
]
aws budgets create-budget \
--account-id "$AWS_ACCOUNT_ID" \
--budget file://budget.json \
--notifications-with-subscribers file://notifications-with-subscribers.json
Budget graphs और notifications तुरंत नहीं दिख सकते। Launch से पहले set करें।
Rollback और common pitfalls
पहली Lambda + API Gateway service के लिए सबसे practical rollback अक्सर bad commit revert करके redeploy करना होता है।
git revert <bad-commit-sha>
git push origin main
फिर API, CloudFormation events और logs देखें।
curl "${API_URL}v1/health"
aws cloudformation describe-stack-events \
--stack-name SmallApiProdStack \
--max-items 20
aws logs tail "/aws/lambda/claude-code-small-api-prod" --since 30m
तीन failures बहुत common हैं। पहला, CDK deploy के बाद किसी ने AWS console से manual change कर दिया और diff समझना मुश्किल हो गया। दूसरा, secrets env vars या logs में आ गए। तीसरा, API Gateway request body tracing production में on कर दिया गया और sensitive payload logs में चला गया। इस stack में dataTraceEnabled: false है, लेकिन review discipline फिर भी जरूरी है।
Claude Code से pre-deploy review कराएं
Claude Code को reviewer बनाएं, पर evidence मांगें।
AWS pre-deployment review करें।
Check करें:
- CDK diff excessive IAM wildcards जोड़ता है या नहीं
- Lambda secrets सिर्फ Secrets Manager से पढ़ती है या नहीं
- API Gateway में throttling, usage plan और logging है या नहीं
- CloudWatch Logs personal data या full request body expose कर सकते हैं या नहीं
- Rollback steps documented हैं या नहीं
- npm test, cdk synth और cdk diff pass हुए या नहीं
severity, file, line और fix वाली table return करें।
Claude Code final production approver नहीं है। Account boundaries, cost exposure और security exceptions humans तय करते हैं। लेकिन यह review process को repeatable बनाता है।
निष्कर्ष
AWS deployment में Claude Code का value सिर्फ CDK code जल्दी लिखना नहीं है। असली value है architecture, IaC, CI/CD, IAM, secrets, logs, rollback और cost guardrails को एक repeatable deployment habit में बदलना।
छोटी Web API के लिए Lambda + API Gateway + CDK अक्सर पर्याप्त है। सच में long-running containers चाहिए तो ECS/Fargate पर जाएं। Static frontend workload हो तो S3 + CloudFront या Amplify चुनें। पहली boundary छोटी, reviewable और reversible रखें।
अगर आपकी team existing repository के लिए Claude Code rules, AWS CDK deployment, GitHub Actions OIDC, least-privilege IAM और operational checks design करना चाहती है, तो Claude Code consulting session book करें। Masa repository, AWS account setup और deployment failure history देखकर practical implementation plan बना सकता है।
Practical test में, AWS account तैयार हो तो इस तरह की छोटी lead API आधे दिन से एक दिन में deploy, logs और cost notification तक पहुंच सकती है। सबसे sensitive हिस्सा Lambda code नहीं, बल्कि IAM, secrets, rollback और cost visibility है। Claude Code implementation तेज करे, और humans production risk का ownership रखें।
मुफ़्त PDF: Claude Code cheatsheet
Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.
हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.
लेखक के बारे में
Masa
Claude Code workflow और team adoption पर काम करने वाला engineer.
संबंधित लेख
Claude Code Obsidian to CLAUDE.md workflow: context बार-बार न समझाएं
Obsidian notes को CLAUDE.md operating notes में बदलकर Claude Code sessions को resume करना आसान बनाएं.
Claude Code Revenue CTA Routing: article से PDF, Gumroad और consultation तक
Reader intent के आधार पर free PDF, Gumroad products और consultation तक CTA route करने वाला workflow.
Claude Code टीम हैंडऑफ नियम: review proof, permissions, rollback और revenue path
Claude Code टीम काम के लिए evidence, permission rules, rollback, free PDF, Gumroad और consultation path वाला handoff.