Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install hf-cloud-sagemaker-iam-preflight@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin hf-cloud-sagemaker-iam-preflight v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install hf-cloud-sagemaker-iam-preflight

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/hf-cloud-sagemaker-iam-preflight/

Extract the ZIP to .github/skills/ in your repo. The folder name must match hf-cloud-sagemaker-iam-preflight for Copilot to auto-discover it.

Skill Files (5)

SKILL.md 6.9 KB
---
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.
references/
minimum-permissions.json 1.0 KB
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "S3ModelArtifactAccess",
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:ListBucket"
      ],
      "Resource": [
        "arn:aws:s3:::REPLACE_WITH_MODEL_BUCKET",
        "arn:aws:s3:::REPLACE_WITH_MODEL_BUCKET/*"
      ]
    },
    {
      "Sid": "ECRPullServingImages",
      "Effect": "Allow",
      "Action": [
        "ecr:GetAuthorizationToken",
        "ecr:BatchCheckLayerAvailability",
        "ecr:GetDownloadUrlForLayer",
        "ecr:BatchGetImage"
      ],
      "Resource": "*"
    },
    {
      "Sid": "CloudWatchLogs",
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogStream",
        "logs:CreateLogGroup",
        "logs:PutLogEvents",
        "logs:DescribeLogStreams"
      ],
      "Resource": "arn:aws:logs:*:*:log-group:/aws/sagemaker/*"
    },
    {
      "Sid": "CloudWatchMetrics",
      "Effect": "Allow",
      "Action": [
        "cloudwatch:PutMetricData"
      ],
      "Resource": "*"
    }
  ]
}
trust-policy.json 0.2 KB
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "sagemaker.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
scripts/
check_role.py 6.7 KB
#!/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())
create_role.py 3.8 KB
#!/usr/bin/env python3
"""Create a SageMaker execution role. Cross-platform (Windows/macOS/Linux).

Run only after check_role.py confirms no usable role exists.
Requires iam:CreateRole and iam:PutRolePolicy.

SSO principals typically lack these — this script will fail with AccessDenied
in that case, and the right answer is to ask an AWS admin for a role.

Like check_role.py, this calls `aws` from the current shell so it inherits the
same AWS context (profile, region, SSO session, proxy). Policy documents are
passed inline rather than via `file://` paths, which sidesteps Windows path
translation entirely.

Usage:
    python create_role.py <role-name> [<model-s3-bucket>]

Without bucket, the inline policy keeps a placeholder for later editing.
"""

from __future__ import annotations

import json
import shutil
import subprocess
import sys
from pathlib import Path

REFERENCES = Path(__file__).resolve().parent.parent / "references"
TRUST_POLICY = REFERENCES / "trust-policy.json"
PERMISSIONS_TEMPLATE = REFERENCES / "minimum-permissions.json"



def log(msg: str) -> None:
    print(f"[create_role] {msg}", file=sys.stderr, flush=True)


def aws_bin() -> str:
    exe = shutil.which("aws")
    if not exe:
        log("ERROR: the 'aws' CLI was not found on PATH. Install AWS CLI v2.")
        sys.exit(2)
    return exe


def run_aws(args: list[str], check: bool = False) -> subprocess.CompletedProcess:
    proc = subprocess.run([aws_bin(), *args], capture_output=True, text=True)
    if check and proc.returncode != 0:
        log(f"AWS command failed: aws {' '.join(args)}")
        if proc.stderr.strip():
            log(proc.stderr.strip())
        sys.exit(1)
    return proc


def main() -> int:
    if len(sys.argv) < 2:
        log(f"Usage: {Path(sys.argv[0]).name} <role-name> [<model-s3-bucket>]")
        return 64

    role_name = sys.argv[1]
    model_bucket = sys.argv[2] if len(sys.argv) > 2 else ""

    if run_aws(["iam", "get-role", "--role-name", role_name]).returncode == 0:
        log(f"Role '{role_name}' already exists. Use check_role.py to validate it.")
        return 1

    ident = run_aws(["sts", "get-caller-identity", "--query", "Arn", "--output", "text"], check=True)
    caller_arn = ident.stdout.strip()
    if ":assumed-role/AWSReservedSSO_" in caller_arn:
        log(f"WARNING: SSO caller ({caller_arn}) — IAM creation likely to fail with AccessDenied.")
        log("If it does, ask an AWS admin to create the role.")

    trust_doc = TRUST_POLICY.read_text(encoding="utf-8")

    log(f"Creating role: {role_name}")
    run_aws(
        [
            "iam", "create-role",
            "--role-name", role_name,
            "--assume-role-policy-document", trust_doc,
            "--description", "SageMaker execution role (hf-cloud-sagemaker-iam-preflight skill)",
        ],
        check=True,
    )


    inline_policy = PERMISSIONS_TEMPLATE.read_text(encoding="utf-8")
    if model_bucket:
        inline_policy = inline_policy.replace("REPLACE_WITH_MODEL_BUCKET", model_bucket)
        log(f"Inline policy will grant S3 access to: {model_bucket}")
    else:
        log("WARNING: No model bucket specified — policy contains placeholder.")
        log("Update before deployment, or pass the bucket name as the 2nd argument.")

    log("Attaching inline policy: SageMakerDeploymentMinimum")
    run_aws(
        [
            "iam", "put-role-policy",
            "--role-name", role_name,
            "--policy-name", "SageMakerDeploymentMinimum",
            "--policy-document", inline_policy,
        ],
        check=True,
    )

    arn = run_aws(
        ["iam", "get-role", "--role-name", role_name, "--query", "Role.Arn", "--output", "text"],
        check=True,
    ).stdout.strip()
    log(f"Created: {arn}")
    print(arn)
    return 0


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

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/huggingface/skills/blob/main/LICENSE