Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

powertools-lambda

БесплатноБез исполняемых скриптовНе проверен

Powertools for AWS Lambda is an open-source toolkit that adds structured JSON logging, X-Ray tracing, CloudWatch metrics (EMF), idempotency, batch processing…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

Powertools for AWS Lambda

Overview

Powertools for AWS Lambda is maintained by AWS. Core utilities: Logger (JSON logs with Lambda context and correlation ids), Tracer (X-Ray), Metrics (CloudWatch Embedded Metric Format: metrics are written as a log line, no API call), Idempotency (DynamoDB-backed), Batch (SQS, Kinesis and DynamoDB Streams partial failures), Parameters (SSM, Secrets Manager, AppConfig with caching) and Event Handler (API Gateway, ALB and Function URL routing, Python). The Python package is aws-lambda-powertools (3.x, Python 3.10+; the 3.37 release metadata says <4.0.0,>=3.10). The TypeScript packages are @aws-lambda-powertools/<utility> (2.x). Java and .NET versions exist with the same concepts.

Instructions

Install

pip install "aws-lambda-powertools[tracer]"          # tracer extra adds aws-xray-sdk; boto3 is in the Lambda runtime
npm install @aws-lambda-powertools/logger @aws-lambda-powertools/tracer @aws-lambda-powertools/metrics @aws-lambda-powertools/idempotency @aws-lambda-powertools/jmespath @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb @middy/core

Alternatively use the AWS-published Powertools Lambda layer (Python); ARNs per region are in the documentation. The idempotency package needs @aws-lambda-powertools/jmespath and the two DynamoDB SDK clients as peer dependencies (the Node.js Lambda runtime already ships the SDK clients). Middy 7 is ESM-only and needs Node.js 22+, so write the TypeScript handler as an ES module ("type": "module").

Enable tracing on the function (Tracing: Active in SAM, tracing: lambda.Tracing.ACTIVE in CDK) and give the role xray:PutTraceSegments and xray:PutTelemetryRecords. Set POWERTOOLS_SERVICE_NAME and POWERTOOLS_METRICS_NAMESPACE as environment variables instead of repeating them in code.

Python: logger, tracer, metrics and a REST resolver

from aws_lambda_powertools import Logger, Metrics, Tracer
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.metrics import MetricUnit
from aws_lambda_powertools.utilities.typing import LambdaContext

logger = Logger(service="user-service")
tracer = Tracer(service="user-service")
metrics = Metrics(namespace="UserService")
app = APIGatewayRestResolver()

@app.get("/users/<uid>")
@tracer.capture_method
def get_user(uid: str):
    logger.info("Fetching user", user_id=uid)          # extra keys become JSON fields
    metrics.add_metric(name="UserFetched", unit=MetricUnit.Count, value=1)
    return {"user": load_user(uid)}                    # your own data access

@app.post("/users")
@tracer.capture_method
def create_user():
    body = app.current_event.json_body
    metrics.add_metric(name="UserCreated", unit=MetricUnit.Count, value=1)
    return {"user": save_user(body)}, 201                  # (body, status code) tuple

@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
@tracer.capture_lambda_handler
@metrics.log_metrics(capture_cold_start_metric=True)
def lambda_handler(event: dict, context: LambdaContext) -> dict:
    return app.resolve(event, context)

@metrics.log_metrics must wrap the handler, otherwise metrics are never flushed. Use APIGatewayHttpResolver for HTTP APIs and ALBResolver for load balancers.

Python: SQS partial batch failures and idempotency

import json

from aws_lambda_powertools.utilities.batch import BatchProcessor, EventType, process_partial_response
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.idempotency import DynamoDBPersistenceLayer, IdempotencyConfig, idempotent, idempotent_function

processor = BatchProcessor(event_type=EventType.SQS)
persistence = DynamoDBPersistenceLayer(table_name="idempotency-table")

@idempotent_function(data_keyword_argument="order", config=IdempotencyConfig(event_key_jmespath="orderId"), persistence_store=persistence)
def charge_order(order: dict):                             # your own charge call; call it with order=...
    ...

def record_handler(record: SQSRecord):
    charge_order(order=record.json_body)                   # raises on failure; a redelivered orderId is not charged twice

def lambda_handler(event, context):
    # returns {"batchItemFailures": [{"itemIdentifier": "<messageId>"}]} for records that raised
    return process_partial_response(event=event, record_handler=record_handler, processor=processor, context=context)

# Whole-handler idempotency for an API Gateway event, whose "body" is a JSON string
config = IdempotencyConfig(event_key_jmespath="powertools_json(body).orderId", expires_after_seconds=3600)

@idempotent(config=config, persistence_store=persistence)
def payment_handler(event, context):
    return {"statusCode": 200, "body": json.dumps(take_payment(json.loads(event["body"])["orderId"]))}  # your own call
`
Полный SKILL.md на GitHub

Установить powertools-lambda в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл powertools-lambda?

Powertools for AWS Lambda is an open-source toolkit that adds structured JSON logging, X-Ray tracing, CloudWatch metrics (EMF), idempotency, batch processing, parameter fetching and API event handlers to Lambda functions in Python, TypeScript, Java and .NET. Use when a user wants better Lambda observability, retry-safe handlers, SQS partial batch failures, or asks about "aws-lambda-powertools", "Powertools logger", "Lambda idempotency" or "EMF metrics".

Как установить скилл powertools-lambda?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл powertools-lambda запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить powertools-lambda с