Hf Cloud Sagemaker Iam Preflight
Hugging FaceOfficialPublished by Hugging Face
- Skill
- Tool integration
- Cloud and DevOps
- Apache-2.0
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a set of Python-based helpers to manage AWS SageMaker execution roles. It is designed to prevent common deployment failures by verifying that a valid IAM role exists before attempting to create resources like endpoints, models, or training jobs. The skill follows a strict order of operations: it first validates a user-provided role, then attempts to discover existing roles based on usage and creation date, and only suggests role creation if no suitable role is found. It specifically addresses issues encountered by SSO principals who may lack the necessary IAM permissions to create roles.
What it does
- Validates specific IAM role ARNs provided by the user.
- Discovers existing SageMaker execution roles by ranking them based on last-used date and creation date.
- Verifies that a role's trust policy allows SageMaker to assume the role.
- Provides a mechanism to create new roles with scoped S3 access when no suitable role is found.
- Offers guidance on applying minimum required permissions instead of broad managed policies.
- Provides native AWS CLI fallback commands for manual verification.
When to use it
- Before deploying SageMaker endpoints, models, or training jobs.
- When a deployment script fails due to missing IAM permissions or an invalid execution role.
- When working as an SSO principal that lacks broad IAM creation privileges.
- When you need to ensure an existing role is correctly configured for SageMaker operations.
Advantages
- Prevents common AccessDenied errors during SageMaker resource creation.
- Promotes the use of existing, actively maintained roles over creating new ones.
- Enforces the principle of least privilege by using scoped inline policies.
- Provides clear error messaging when the user lacks sufficient permissions to create roles.
Usage examples
- “Check if there is a usable SageMaker execution role available in my current AWS environment.”
- The agent runs the discovery script to identify and return the most recently used or newest valid SageMaker execution role.
- “I need to create a new SageMaker role for my model bucket named my-model-data.”
- The agent executes the creation script to generate a role with the necessary trust policy and scoped S3 access to the specified bucket.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/huggingface/hf-cloud-sagemaker-iam-preflight/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip hf-cloud-sagemaker-iam-preflight.zip -d .agents/skills
Documentation by Hugging Face
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:
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-identityfails inside Bash even when it works natively in PowerShell. (This is exactly why the old.shhelpers failed on Windows and were replaced with Python.) If you're in PowerShell, runpython ...\check_role.pydirectly 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 whereaws sts get-caller-identityreturns your ARN.
Order of operations
Step 1 — Did the user provide a role?
Validate that one specifically:
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
python3 scripts/check_role.pyLists 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):
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:ListBucketon the model artifact bucketECR 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:
# 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 textPick 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.
Files
- ATTRIBUTION.mdAdded by AutoGineer908 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md6.9 KiB
- references/minimum-permissions.json1.0 KiB
- references/trust-policy.json197 B
- scripts/check_role.pyScript6.7 KiB
- scripts/create_role.pyScript3.8 KiB
scripts/check_role.py
#!/usr/bin/env python3
"""Discover and validate a SageMaker execution role. Cross-platform (Windows/macOS/Linux).
Without args: searches the account for usable roles, ranks by last-used date
(newest creation date when last-used is unrecorded), returns the first one
with a valid trust policy.
With arg: validates the named role.
Does NOT create roles — see create_role.py.
Why Python (not a shell script): this runs `aws` from the *same* shell the user
launched it in, inheriting their AWS profile, region, SSO session, proxy, and
credential chain. A bundled Bash helper on Windows (Git Bash/WSL/MSYS) often
does NOT share that context, so `aws sts get-caller-identity` fails there even
when the native CLI works fine. Run this from the shell where `aws sts
get-caller-identity` already succeeds.
Usage:
python check_role.py # discover
python check_role.py <role-name-or-arn> # validate a specific role
(On Windows the launcher is usually `python`; on macOS/Linux it's `python3`.)
Exit: 0 = usable role found (ARN printed to stdout)
1 = no usable role
2 = AWS CLI / credentials error
"""
from __future__ import annotations
import fnmatch
import json
import shutil
import subprocess
import sys
ROLE_NAME_PATTERNS = [
"AmazonSageMaker-ExecutionRole-*",
"SageMakerExecutionRole*",
"*SageMaker*Execution*",
"*sagemaker*execution*",
]
def log(msg: str) -> None:
print(f"[check_role] {msg}", file=sys.stderr, flush=True)
def aws_bin() -> str:
"""Resolve the `aws` executable, honoring PATHEXT (finds aws.exe/aws.cmd on Windows)."""
exe = shutil.which("aws")
if not exe:
log("ERROR: the 'aws' CLI was not found on PATH.")
log("Install AWS CLI v2 and confirm `aws sts get-caller-identity` works in this shell.")
sys.exit(2)
return exe
def run_aws(args: list[str]) -> subprocess.CompletedProcess:
"""Run an aws CLI command, capturing output. Never raises on nonzero exit."""
return subprocess.run(
[aws_bin(), *args],
capture_output=True,
text=True,
)
def get_role(role_name: str) -> dict | None:
"""Return the Role dict from `aws iam get-role`, or None if it can't be read."""
proc = run_aws(["iam", "get-role", "--role-name", role_name, "--output", "json"])
if proc.returncode != 0:
return None
try:
return json.loads(proc.stdout)["Role"]
except (json.JSONDecodeError, KeyError):
return None
def trust_allows_sagemaker(role: dict) -> bool:
"""True if the trust policy lets sagemaker.amazonaws.com assume the role."""
trust = role.get("AssumeRolePolicyDocument", {})
# Substring check over the serialized doc — matches the original shell helper
# and is robust to single/list Principal.Service shapes.
return "sagemaker.amazonaws.com" in json.dumps(trust)
def validate_role(role_name: str, quiet: bool = False) -> str | None:
"""Return the role ARN if it exists and trusts SageMaker, else None."""
role = get_role(role_name)
if role is None:
if not quiet:
log(f"Role '{role_name}' does not exist or you cannot describe it.")
return None
if not trust_allows_sagemaker(role):
if not quiet:
log(f"Role '{role_name}': trust policy does not allow sagemaker.amazonaws.com")
return None
return role.get("Arn")
def main() -> int:
if run_aws(["sts", "get-caller-identity"]).returncode != 0:
log("ERROR: 'aws sts get-caller-identity' failed. Run hf-cloud-aws-context-discovery first.")
log("Run this helper from the shell where the AWS CLI is configured (e.g. PowerShell on Windows).")
return 2
# Path 1: validate a user-supplied role
if len(sys.argv) >= 2:
supplied = sys.argv[1]
role_name = supplied.rsplit("/", 1)[-1] if supplied.startswith("arn:aws:iam::") else supplied
log(f"Validating: {role_name}")
arn = validate_role(role_name)
if arn:
log(f"OK: {arn}")
print(arn)
return 0
return 1
# Path 2: discover candidates
log("Searching for SageMaker execution roles in the account...")
proc = run_aws(["iam", "list-roles", "--query", "Roles[*].RoleName", "--output", "json"])
if proc.returncode != 0:
log("Could not list roles (caller likely lacks iam:ListRoles).")
log("Ask the user for an existing role ARN, or have someone with IAM access run this.")
return 1
try:
all_roles = json.loads(proc.stdout) or []
except json.JSONDecodeError:
all_roles = []
candidates = [
name
for name in all_roles
if any(fnmatch.fnmatchcase(name, pat) for pat in ROLE_NAME_PATTERNS)
]
if not candidates:
log("No matching roles. Options:")
log(" 1. Ask the user for an ARN (role might have an unusual name)")
log(" 2. Create one (see create_role.py, requires iam:CreateRole)")
return 1
log(f"Found {len(candidates)} candidate(s): {' '.join(candidates)}")
# Rank by RoleLastUsed (most recent first) — alphabetical order rarely picks
# the actively-maintained role in accounts with multiple SageMaker roles.
# Fetch each role once and reuse the result for both ranking and validation.
log("Ranking by last-used date (fallback: creation date)...")
roles_by_name: dict[str, dict] = {}
ranked: list[tuple[str, str, str]] = [] # (last_used, create_date, role_name)
for name in candidates:
role = get_role(name)
if role is None:
continue
roles_by_name[name] = role
last_used = (role.get("RoleLastUsed") or {}).get("LastUsedDate") or ""
# IAM often reports no RoleLastUsed at all (tracking only covers recent
# activity); when every candidate ties at "", newest CreateDate wins.
create_date = str(role.get("CreateDate") or "")
# ISO-8601 timestamps sort chronologically as strings; "" (never used)
# sorts before any timestamp, so descending order puts it last.
ranked.append((last_used, create_date, name))
ranked.sort(reverse=True)
log("Ranking (most recent first):")
for last_used, create_date, name in ranked:
when = f"last used {last_used}" if last_used else f"never used, created {create_date or '?'}"
log(f" - {name} ({when})")
for _, _, name in ranked:
if trust_allows_sagemaker(roles_by_name[name]):
arn = roles_by_name[name].get("Arn")
log(f"Using: {arn}")
print(arn)
return 0
log("No candidate passed validation (they exist but lack correct trust policy).")
log("Fix the trust policy or create a new role (see create_role.py).")
return 1
if __name__ == "__main__":
sys.exit(main())
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs a command-line tool, Needs Python
Security
What our scanner noticed· Low risk
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Hugging Face
- Publisher
- Hugging Face (Official)
- Source
- huggingface/skills · skills/hf-cloud-sagemaker-iam-preflight · commit 25910b3
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Hugging Face.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download hf-cloud-sagemaker-iam-preflight.zip