К основному содержанию
скилл CX Codex

aws-sdk-python-usage — скилл для Claude Code: что делает

Скилл задаёт правила кодинга на Python с библиотеками boto3 и botocore. Он подсказывает агенту, когда брать client или resource, как настраивать пагинацию и перехватывать ошибки AWS.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add aws/agent-toolkit-for-aws --skill aws-sdk-python-usage -a claude-code
Открыть на GitHub

Что делает aws-sdk-python-usage

Скилл инструктирует модель по работе с библиотеками boto3 и botocore. Он разграничивает низкоуровневые клиенты (client) и объектные ресурсы (resource). Ресурсы доступны только для ряда сервисов вроде S3 или DynamoDB, зато они автоматически преобразуют типы данных. Вызовы методов требуют именования параметров строго в PascalCase, в точности по API AWS.

Внутри собраны чёткие инженерные запреты. Нельзя создавать клиенты внутри циклов: их создают один раз и переиспользуют между потоками. В скриптах запрещено вызывать sys.exit() внутри бизнес-логики, потому что это ломает модульные тесты. Для обхода списков правило обязывает использовать штатные пагинаторы с фильтрацией через JMESPath, а не крутить ручные циклы с токеном NextToken.

Ошибки нельзя глушить ради простого вывода в консоль. Скилл требует перехватывать только типизированные исключения через client.exceptions, если код действительно может что-то исправить. Общий класс ClientError из botocore остаётся только для функции main(). Также при активном скилле запрещены любые эмодзи в коде и комментариях.

Какие задачи решает

  • выбрать между интерфейсами client и resource для сервиса AWS
  • настроить пагинацию через get_paginator и выборку полей через JMESPath
  • обработать типизированные ошибки API через client.exceptions без маскировки сбоев
  • вынести разбор CLI-аргументов в main() без вызова sys.exit() в функциях
  • сконфигурировать таймауты и режим повторов через botocore.config.Config

Примеры запросов агенту

  • Напиши скрипт на boto3 для выгрузки пользователей IAM с фильтрацией по пути /admin/ через пагинатор
  • Сделай функцию на Python для чтения объекта из S3 с обработкой NoSuchKey через client.exceptions
  • Настрой клиент boto3 для DynamoDB с пулом на 50 соединений и адаптивным режимом повторов

Как установить aws-sdk-python-usage

1Через Skills CLI (Vercel)

npx skills add aws/agent-toolkit-for-aws --skill aws-sdk-python-usage -a claude-code

2Вручную: положить файлы

~/.claude/skills/aws-sdk-python-usage/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/aws-sdk-python-usage/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора133

aws-cloudformation Ведёт шаблоны CloudFormation от написания до разбора упавших стеков: валидация, проверки cfn-guard и поиск причины сбоя по событиям и CloudTrail. CX Codex +1 8 800установок amazon-bedrock Скилл помогает настраивать Amazon Bedrock, от вызовов Converse API и RAG в Knowledge Bases до развёртывания агентов в AgentCore Harness. CX Codex +1 8 500установок aws-messaging-and-streaming Помогает агенту выбрать, чем двигать данные в AWS: очередью, шиной событий или журналом. Полезно до того, как вы зафиксируете SQS или Kinesis. CX Codex +1 8 100установок aws-sdk-js-v3-usage Задаёт правила и паттерны работы с AWS SDK v3 в коде на JavaScript и TypeScript. Помогает писать вызовы сервисов AWS без устаревшего синтаксиса v2. CX Codex +1 8 000установок securing-s3-buckets Скилл проводит агента по пяти сценариям работы с S3: создание защищённого бакета, аудит, исправление находок, шифрование и мониторинг. CX Codex +1 6 900установок connecting-to-data-source Создаёт подключение AWS Glue к внешней базе — Oracle, PostgreSQL, Redshift, Snowflake или BigQuery — и проверяет его тестом перед передачей в работу. CX Codex +1 6 800установок creating-secrets-using-best-practices Ведёт агента по созданию секрета в AWS Secrets Manager: отдельный ключ KMS, узкие права IAM, ротация и аудит. Пригодится, когда секрет идёт в прод. CX Codex +1 6 700установок storing-and-querying-vectors Скилл ведёт агента по работе с Amazon S3 Vectors: создание векторного бакета и индекса, запись эмбеддингов, поиск похожих. CX Codex +1 6 600установок

Похожие

aws-sdk-java-v2-lambda giuseppe-trisciuoglio Скилл подсказывает агенту, как вызывать и обновлять функции AWS Lambda через AWS SDK for Java 2.x. Пригодится, если пишешь на Java и работаешь с Lambda. CX Codex +1 3 700установок hf-cloud-python-env-setup huggingface Скилл разворачивает изолированное окружение Python для работы с AWS и SageMaker. Он помогает избежать сбоев из-за несовместимых версий Python и устаревшего SDK boto3. CX Codex +1 548установок aws-lambda-python-integration giuseppe-trisciuoglio Подсказывает агенту, как писать и разворачивать Python-функции в AWS Lambda: Chalice или чистый Python, холодный старт, API Gateway и ALB. CX Codex +1 3 600установок django-storages-s3 https://github.com/awais786 Скилл настраивает хранение статики и медиафайлов Django в AWS S3 через django-storages и boto3: словарь STORAGES, presigned-ссылки, CloudFront, IAM. CX Codex +1 900установок aws-cdk-python-setup официальный github Скилл помогает подготовить окружение для AWS CDK на Python, создать проект и выполнить деплой в AWS. Подойдёт для старта нового CDK-приложения. 1 600установок aws-lambda devops-skills Скилл помогает развёртывать функции AWS Lambda, настраивать триггеры S3 или SQS и организовывать канареечные релизы. CX Codex +1 321установок

Рядом в теме «Облака: AWS, Azure, GCP»

Всё по теме «Облака: AWS, Azure, GCP» →

Вопросы о aws-sdk-python-usage

Как установить aws-sdk-python-usage в Claude Code?

Выполните команду npx skills add aws/agent-toolkit-for-aws --skill aws-sdk-python-usage -a claude-code. Также файл скилла можно сохранить вручную по пути ~/.claude/skills/aws-sdk-python-usage/SKILL.md.

Что делает скилл aws-sdk-python-usage?

Он задаёт шаблоны генерации кода на Python с использованием библиотек boto3 и botocore. Скилл направляет модель на выбор подходящих интерфейсов, корректную обработку исключений, применение пагинаторов и безопасное переиспользование клиентов.

Когда скилл рекомендует использовать resource вместо client?

Интерфейс resource рекомендуется, когда сервис AWS его поддерживает (например, S3 или DynamoDB), так как объектная модель автоматически преобразует типы. Для полного охвата API или сервисов без ресурсов используется client.

Исходный текст

SKILL.md · Apache-2.0
---
name: aws-sdk-python-usage
description: |
  AWS SDK for Python (boto3/botocore) development patterns. You MUST use this skill when writing Python code that uses AWS services via boto3 or botocore. This includes creating service clients or resources, configuring sessions and credentials, handling errors with ClientError, using paginators and waiters, S3 file transfers and presigned URLs, DynamoDB table operations, and any boto3/botocore client configuration. Use this skill whenever Python code imports boto3 or botocore, or when the user asks about AWS operations in Python.
---

> Do not use emojis in any code, comments, or output when this skill is active.

# AWS SDK for Python (boto3)

boto3 is the high-level Python SDK for AWS. It wraps botocore (the low-level
SDK) and provides two distinct interfaces: **clients** (low-level, 1:1 API
mapping) and **resources** (high-level, object-oriented). Understanding which to
use and when is essential.

## Client vs Resource

**Clients** map directly to AWS service APIs. Every service has a client.
Responses are plain dicts.

**Resources** provide an object-oriented interface with attributes and actions.
Only some services have resources (S3, DynamoDB, EC2, IAM, SQS, SNS,
CloudFormation, CloudWatch, Glacier). Resources auto-marshal types (especially
useful for DynamoDB).

```python
import boto3

# Client - low-level, all services
s3_client = boto3.client("s3")
response = s3_client.list_buckets()
buckets = response["Buckets"]  # plain dicts

# Resource - high-level, select services
s3_resource = boto3.resource("s3")
for bucket in s3_resource.buckets.all():
    print(bucket.name)  # attribute access, not dict keys
```

Use clients when you need full API coverage or the service has no resource
interface. Use resources when they exist and simplify your code (especially
DynamoDB and S3).

## Session and Client Creation

```python
import boto3

# Default session implicitly created
client = boto3.client("s3")
resource = boto3.resource("dynamodb")

# Explicit session use when you need to customize how
# clients are created, use an explicit profile, etc.
session = boto3.Session(
    profile_name="my-profile",
    region_name="us-west-2",
)
client = session.client("s3")
```

Do not create clients inside loops - reuse a single client instance.  Clients
are thread safe and can be shared across threads once they're instantiated.

## Making API Calls

```python
# Client - pass parameters as keyword arguments, get dicts back
response = client.get_object(Bucket="my-bucket", Key="my-key")
data = response["Body"].read()

# Resource - use object methods and attributes
obj = s3_resource.Object("my-bucket", "my-key")
response = obj.get()
data = response["Body"].read()
```

Parameter names match the exact casing of the AWS API,
which is typically PascalCase, not snake\_case.

## Error Handling

Only catch exceptions when you have something actionable to do - return a
fallback value, retry, take a different code path. Catching an exception just to
print it and swallow it is wrong: it hides the real error and prevents callers
from reacting. Let exceptions propagate by default.

When you do catch, prefer typed exceptions on the client over generic
`ClientError` with string code matching through the `client.exceptions`
attribute:

```python
lambda_client = boto3.client("lambda")

def get_function_config(name: str) -> dict | None:
    """Return function configuration, or None if it doesn't exist."""
    try:
        return lambda_client.get_function_configuration(FunctionName=name)
    except lambda_client.exceptions.ResourceNotFoundException:
        return None  # actionable: convert missing function to None
    # Everything else propagates - caller or main() handles it
```

Use generic `ClientError` only as a catch-all in a top-level error handler, not
in business logic functions. It lives in botocore, not boto3:

```python
from botocore.exceptions import ClientError

def main() -> int:
    try:
        result = do_the_work()
        print(result)
        return 0
    except ClientError as e:
        print(f"Error: {e}", file=sys.stderr)
        return 1
```

For the full error hierarchy and botocore exceptions, see `references/error-handling.md`.

## Script Structure

When asked to write a script that uses `boto3` or `botocore`, keep `if __name__
== "__main__"` to a single function call. Argument parsing, error presentation,
and exit codes belong in `main()`, not scattered across business logic
functions:

```python
def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("bucket")
    args = parser.parse_args()

    try:
        do_the_work(args.bucket)
        return 0
    except ClientError as e:
        print(f"Error: {e}", file=sys.stderr)
        return 1

if __name__ == "__main__":
    sys.exit(main())
```

Never call `sys.exit()` from a business logic function -- it makes the function
untestable and unusable as a library. Raise an exception or return an error
value instead, and let `main()` decide how to present it.

## Pagination

Never manually loop with `NextToken` -- use paginators. When you only need
specific fields, use `.search()` with a JMESPath expression to extract and
flatten across pages:

```python
paginator = iam.get_paginator("list_users")
for name in paginator.paginate().search("Users[].UserName"):
    print(name)

# Filter and project
for arn in paginator.paginate().search("Users[?Path == '/admin/'][].Arn"):
    print(arn)
```

When you need the full response object per item, or need per-page control (e.g.
counting pages, batching by page), iterate pages directly:

```python
for page in paginator.paginate():
    for user in page.get("Users", []):
        process(user)
```

For more details on pagination, see: `references/pagination.md`.

## Waiters

Wait for a resource to reach a desired state:

```python
waiter = client.get_waiter("bucket_exists")
waiter.wait(
    Bucket="my-bucket",
    WaiterConfig={"Delay": 5, "MaxAttempts": 20},
)
```

For more details on waiters, see `references/waiters.md`.

## Client Configuration

Use `botocore.config.Config` for retries, timeouts, and connection pool
settings, etc.:

```python
from botocore.config import Config

config = Config(
    retries={"total_max_attempts": 2, "mode": "adaptive"},
    connect_timeout=5,
    read_timeout=10,
    max_pool_connections=50,
)
client = boto3.client("s3", config=config)
```

When creating custom configuration for a client, see `references/configuration.md`.

## Logging

Both boto3 and botocore use the standard library `logging` module.  You can
configure logging through the standard `logging` APIs, or you can use
helpers provided by boto3 and botocore for convenience:

```python
# Quick: log all botocore wire-level details to stderr
boto3.set_stream_logger("")  # root logger -- everything
boto3.set_stream_logger("botocore")  # just botocore

# Botocore, log all botocore details
import logging

from botocore.session import Session

session = Session()

session.set_stream_logger('botocore', logging.DEBUG)
# OR: Configure logging to a file.
session.set_file_logger(logging.DEBUG, '/tmp/botocore.log')
```

`set_stream_logger(name, level=logging.DEBUG)` adds a
`StreamHandler` to the named logger. This is the idiomatic way to get
request/response debug output from the SDK.

## Common Issues

### Issue: ClientError import location

**Wrong:** `from boto3.exceptions import ClientError`
**Right:** `from botocore.exceptions import ClientError`

## Service specific customizations

When writing any Python code that uses the following services, you MUST load
these additional reference files for best practices and custom high level APIs:

* S3 - you MUST load `references/s3.md`.
* Dynamodb - you MUST load `references/dynamodb.md`.

## References

* Client configuration (retries, timeouts, endpoints): `references/configuration.md`
* Credentials and sessions: `references/credentials.md`
* Error handling patterns: `references/error-handling.md`
* Pagination: `references/pagination.md`
* Waiters: `references/waiters.md`
* S3 transfers and presigned URLs: `references/s3.md`
* DynamoDB operations: `references/dynamodb.md`

© aws · Apache-2.0 · aws/agent-toolkit-for-aws

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой