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

hf-cloud-sagemaker-iam-preflight — скилл для Claude Code: установка

Проверяет и подбирает IAM-роль для SageMaker перед деплоем или обучением. Предотвращает ошибки AccessDenied при работе через SSO.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add huggingface/skills --skill hf-cloud-sagemaker-iam-preflight -a claude-code
Открыть на GitHub

Что делает hf-cloud-sagemaker-iam-preflight

Скрипты scripts/check_role.py и scripts/create_role.py проверяют наличие подходящей роли исполнения SageMaker в аккаунте AWS. Скилл ищет роли по типовым шаблонам имён, сортирует их по дате недавнего использования и валидирует доверительную политику на sagemaker.amazonaws.com. Если данные об активности отсутствуют, выбор переключается на дату создания роли.

Создание новой роли запускается только тогда, когда поиск не дал результатов, а у пользователя есть права IAM. Если вы вошли через AWS SSO без прав на запись в IAM, попытка вызвать iam:CreateRole сломает процесс деплоя. Скилл вовремя останавливает операцию и сообщает, каких конкретно прав не хватает для продолжения.

На Windows хелперы нужно запускать прямо в PowerShell или cmd. Оболочки WSL или Git Bash часто теряют переменные окружения и активную сессию SSO из Windows.

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

  • найти готовую execution role для SageMaker перед запуском обучения
  • проверить trust policy существующей IAM-роли
  • создать роль с минимальной политикой доступа к бакету S3
  • предотвратить сбой деплоя из-за нехватки прав у SSO-пользователя

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

  • Проверь, есть ли в AWS подходящая роль для запуска эндпоинта SageMaker
  • Валидируй IAM-роль my-custom-sagemaker-role перед началом деплоя
  • Создай execution role для SageMaker с доступом к бакету my-models-bucket

Как установить hf-cloud-sagemaker-iam-preflight

1Через Skills CLI (Vercel)

npx skills add huggingface/skills --skill hf-cloud-sagemaker-iam-preflight -a claude-code

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

~/.claude/skills/hf-cloud-sagemaker-iam-preflight/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/hf-cloud-sagemaker-iam-preflight/

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

Вопросы о hf-cloud-sagemaker-iam-preflight

Как установить hf-cloud-sagemaker-iam-preflight в Claude Code?

Выполните команду npx skills add huggingface/skills --skill hf-cloud-sagemaker-iam-preflight -a claude-code в терминале. Также можно сохранить файл вручную по пути ~/.claude/skills/hf-cloud-sagemaker-iam-preflight/SKILL.md.

Зачем проверять роли перед деплоем в SageMaker?

Каждому ресурсу SageMaker нужна роль исполнения для чтения артефактов из S3 и записи логов. Скрипт находит актуальную рабочую роль вместо создания дубликатов.

Что произойдёт, если у пользователя нет прав на создание ролей?

При входе через SSO без прав на iam:CreateRole скилл остановит выполнение и выдаст чёткие инструкции для администратора AWS вместо сбоя с общей ошибкой доступа.

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

SKILL.md · Apache-2.0
---
name: hf-cloud-sagemaker-iam-preflight
description: 'Ensure a usable SageMaker execution role exists before deploying or training. Use this skill whenever about to create a SageMaker endpoint, model, training job, or any resource that requires an execution role. Use it especially when the user has not provided a role ARN explicitly, when scripts are about to call `iam:CreateRole`, or when an AccessDenied error mentions an IAM action. Never blindly call `iam:CreateRole` — always check for existing roles first. This skill prevents the most common SageMaker deployment failure: trying to create IAM resources from an SSO principal that has no IAM write permissions.'
---

# SageMaker IAM Preflight

Every SageMaker resource needs an **execution role** — the IAM role SageMaker assumes to read model artifacts from S3, pull serving containers from ECR, and write logs. Most deployments fail here because the script tried to create a new role without checking if a usable one already existed, then blew up because the caller is an SSO principal.

This skill encodes the right order: discover, validate, only create if necessary.

## Running the helpers (cross-platform)

The helpers are Python so they run identically on Windows, macOS, and Linux:

```bash
python3 scripts/check_role.py        # macOS / Linux
python  scripts/check_role.py        # Windows (PowerShell / cmd)
```

**Run them from the shell where the AWS CLI already works** — i.e. wherever `aws sts get-caller-identity` succeeds. The script shells out to that same `aws` binary and inherits the shell's profile, region, SSO session, proxy, and credential chain.

> **Windows / WSL / Git Bash caveat.** Do **not** invoke these through a Bash shim (WSL, Git Bash, MSYS) on Windows. Those Bash environments frequently do **not** share the Windows AWS config, credentials, SSO sessions, environment variables, or proxy settings — so `aws sts get-caller-identity` fails inside Bash even when it works natively in PowerShell. (This is exactly why the old `.sh` helpers failed on Windows and were replaced with Python.) If you're in PowerShell, run `python ...\check_role.py` directly in PowerShell. If the helper still can't see your identity, run the same discovery natively (see "Native AWS CLI equivalent" below) in the shell where `aws sts get-caller-identity` returns your ARN.

## Order of operations

### Step 1 — Did the user provide a role?

Validate that one specifically:

```bash
python3 scripts/check_role.py "<role-name-or-arn>"
```

On success it prints the ARN to stdout (exit 0). On failure it logs why on stderr. Don't try to silently fix a broken role — surface the problem.

### Step 2 — Discover existing roles

```bash
python3 scripts/check_role.py
```

Lists roles matching common SageMaker patterns (`AmazonSageMaker-ExecutionRole-*`, `SageMakerExecutionRole*`, etc.), **ranks by last-used date** (most recent first), validates trust policy in that order, returns the first usable ARN. Most accounts that have used SageMaker before already have one.

Why rank by last-used: in accounts with multiple roles (auto-generated 2021 role + manual project role + etc.), the alphabetically-first one is rarely the actively-maintained one. The most-recently-used role is more likely to have current policies — including cross-account ECR pull. The script prints the ranking so you can see which got picked.

IAM frequently reports **no** `RoleLastUsed` at all (tracking only covers recent activity). When every candidate ties at "never used", the script falls back to **newest creation date** — a newer role is more likely to have current policies than a 2021 leftover.

### Step 3 — Create, only if discovery found nothing

**If the user can create** (has IAM permissions):

```bash
python3 scripts/create_role.py "<role-name>" "<model-bucket>"
```

Second arg scopes S3 access to a specific bucket. Omit if unknown; script warns and the user can update the policy later.

**If the user cannot create** (SSO principal — `hf-cloud-aws-context-discovery` will have flagged this):

Stop and surface this clearly. Don't retry alternative IAM operations hoping one works:

> I can't find an existing SageMaker execution role, and you're authenticated via SSO so you can't create one directly. Please either:
>   - Ask your AWS admin for a SageMaker execution role ARN, or
>   - Have them grant your SSO permission set `iam:CreateRole`, `iam:PutRolePolicy`

Specific instructions get unblocked fast; vague "permission denied" messages don't.

## What "validated" means

A role is usable when (1) it exists, (2) its trust policy allows `sagemaker.amazonaws.com` to `sts:AssumeRole`, and (3) its permissions grant only the actions and resources this deployment needs. See `references/trust-policy.json` for the canonical trust policy.

`check_role.py` verifies existence and trust because policy evaluation depends on the deployment's exact S3, ECR, logging, and optional output resources. Before deployment, inspect the selected role's policies and compare them with `references/minimum-permissions.json`; add only missing actions and scope them to the required resources. Do not attach `AmazonSageMakerFullAccess` or defer permission review until an `AccessDenied` failure.

## Minimum permissions

`references/minimum-permissions.json` is the standalone inline policy for endpoint execution:
- `s3:GetObject` + `s3:ListBucket` on the model artifact bucket
- ECR pull permissions
- CloudWatch logs and metrics

`create_role.py` installs this inline policy without attaching a managed FullAccess policy. Replace `REPLACE_WITH_MODEL_BUCKET` in the template with the actual bucket name — `create_role.py` does this automatically when given a bucket as its second argument. Add narrowly scoped permissions separately for optional features such as async output or data capture.

## Native AWS CLI equivalent (fallback)

If the Python helper can't run or can't see your identity (rare — usually a broken PATH or running under a Bash shim that lacks AWS context), do the same preflight by hand in the shell where `aws sts get-caller-identity` works. The logic is just AWS CLI calls; the helper exists only to bundle and rank them.

PowerShell:

```powershell
# 1. List candidate SageMaker roles
aws iam list-roles --query "Roles[?contains(RoleName,'SageMaker') || contains(RoleName,'sagemaker')]" --output json

# 2. For each candidate, confirm the trust policy allows sagemaker.amazonaws.com
aws iam get-role --role-name <role-name> --query "Role.AssumeRolePolicyDocument" --output json

# 3. Prefer the most-recently-used role with SageMaker-execution naming
#    (LastUsedDate is often None for every role — then prefer newest CreateDate)
aws iam get-role --role-name <role-name> --query "Role.[RoleLastUsed.LastUsedDate, CreateDate]" --output text
```

Pick the most-recently-used role whose trust policy contains `sagemaker.amazonaws.com`. Use the resulting ARN exactly as if `check_role.py` had returned it. Bash/macOS/Linux use the same commands.

© huggingface · Apache-2.0 · huggingface/skills

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

Всё по теме «Облака: AWS, Azure, GCP» →
sagemaker-ai awslabs Плагин для Claude, который ведёт от постановки задачи до деплоя модели на Amazon SageMaker AI и разбирает сбои кластеров HyperPod. ★ 927звёзд репо querying-aws-sagemaker-catalog aws Скилл запускает SQL-аналитику по метаданным SageMaker Catalog в таблицах Apache Iceberg. Помогает проверять владельцев данных, отслеживать рост ассетов и находить пропуски в описаниях. CX Codex +1 4 900установок aws-iam aws Проверенные поправки к типичным ошибкам агентов в AWS IAM плюс рабочие процессы для ролей и baseline-политик. CX Codex +1 10 200установок iam-audit briiirussell Проводит аудит доступов в облаках и IdP, проектирует роли с нуля и готовит миграцию на SSO. Пригодится при расчистке старых прав и подготовке к аттестации. CX Codex +1 351установок cloud-audit briiirussell Скилл проверяет конфигурации AWS, GCP и Azure на ошибки, лишние права и публичный доступ. Пригодится перед релизом или после инцидента. CX Codex +1 352установок huawei-cloud-iam-query huaweicloud Опрашивает пользователей, группы, роли и ключи доступа в Huawei Cloud IAM через локальный Python SDK. Пригодится при аудите прав и проверке политик безопасности. CX Codex +1 16 900установок

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

hf-mem Считает, сколько памяти займёт модель с Hugging Face Hub при инференсе, и не скачивает веса. Пригодится, когда надо понять, влезет ли модель в GPU. CX Codex +1 858установок huggingface-lora-space-builder Создаёт и публикует веб-демо на Gradio в Hugging Face Spaces для весов LoRA. Подбирает пайплайн diffusers и интерфейс под задачу генерации на ZeroGPU. CX Codex +1 810установок hf-cloud-sagemaker-production-defaults Скилл создаёт SageMaker endpoint с автоскейлингом, CloudWatch-алармами и тегами. Он нужен для финального шага деплоя модели. CX Codex +1 549установок hf-cloud-python-env-setup Скилл разворачивает изолированное окружение Python для работы с AWS и SageMaker. Он помогает избежать сбоев из-за несовместимых версий Python и устаревшего SDK boto3. CX Codex +1 548установок hf-cloud-sagemaker-deployment-planner Помогает выбрать способ развёртывания модели на Amazon SageMaker: real-time, async, serverless или batch. Пригодится, когда модель уже обучена, а с эндпоинтом ещё не решено. CX Codex +1 544установок hf-cloud-serving-image-selection Подбирает контейнер для деплоя модели на SageMaker и находит актуальный image URI. Пригодится, когда в коде деплоя нужно указать образ. CX Codex +1 544установок hf-cloud-aws-context-discovery Скилл определяет активный AWS-профиль, регион, аккаунт и ARN перед задачами с AWS. Нужен, чтобы агент не угадывал параметры окружения. CX Codex +1 541установок huggingface-skills Набор скиллов для обучения моделей, работы с датасетами и запуска Spaces прямо из агента. Пригодится, если вы живёте в Hugging Face Hub. ★ 11 213звёзд репо

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

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