IAM & STS
Secure access management: create roles and policies, manage temporary credentials via STS, and enforce least-privilege principles across your AWS infrastructure.
Busca en todas las páginas de la documentación
Secure access management: create roles and policies, manage temporary credentials via STS, and enforce least-privilege principles across your AWS infrastructure.
Define an IAM role by specifying who can assume it (trust policy) in a single CreateRole call.
# --- Python (boto3) ---
import json
import boto3
trust_policy = {
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "ec2.amazonaws.com"},
"Action": "sts:AssumeRole"
}]
}
iam = boto3.client("iam")
role = iam.create_role(
RoleName="MyEC2Role",
AssumeRolePolicyDocument=json.dumps(trust_policy)
)
print(role["Role"]["Arn"])// --- TypeScript (AWS SDK v3) ---
import { IAMClient, CreateRoleCommand } from "@aws-sdk/client-iam";
const trustPolicy = {
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Principal: { Service: "ec2.amazonaws.com" },
Action: "sts:AssumeRole"
}]
};
const iam = new IAMClient({});
const role = await iam.send(new CreateRoleCommand({
RoleName: "MyEC2Role",
AssumeRolePolicyDocument: JSON.stringify(trustPolicy)
}));
console.log(role.Role?.Arn);Link an AWS managed policy (or customer-managed) to a role for immediate permission inheritance.
# --- Python (boto3) ---
import boto3
iam = boto3.client("iam")
iam.attach_role_policy(
RoleName="MyEC2Role",
PolicyArn="arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess"
)
print("Policy attached")// --- TypeScript (AWS SDK v3) ---
import { IAMClient, AttachRolePolicyCommand } from "@aws-sdk/client-iam";
const iam = new IAMClient({});
await iam.send(new AttachRolePolicyCommand({
RoleName: "MyEC2Role",
PolicyArn: "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess"
}));
console.log("Policy attached");Embed a policy document directly in a role (avoid for complex policies; prefer customer-managed policies).
# --- Python (boto3) ---
import json
import boto3
policy_doc = {
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "dynamodb:GetItem",
"Resource": "arn:aws:dynamodb:us-east-1:111122223333:table/Users"
}]
}
iam = boto3.client("iam")
iam.put_role_policy(
RoleName="MyEC2Role",
PolicyName="DynamoDBRead",
PolicyDocument=json.dumps(policy_doc)
)// --- TypeScript (AWS SDK v3) ---
import { IAMClient, PutRolePolicyCommand } from "@aws-sdk/client-iam";
const policyDoc = {
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Action: "dynamodb:GetItem",
Resource: "arn:aws:dynamodb:us-east-1:111122223333:table/Users"
}]
};
const iam = new IAMClient({});
await iam.send(new PutRolePolicyCommand({
RoleName: "MyEC2Role",
PolicyName: "DynamoDBRead",
PolicyDocument: JSON.stringify(policyDoc)
}));Build a reusable policy that you own and can attach to multiple roles, users, or groups.
# --- Python (boto3) ---
import json
import boto3
policy_doc = {
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::my-bucket/*"
}]
}
iam = boto3.client("iam")
policy = iam.create_policy(
PolicyName="S3BucketAccess",
PolicyDocument=json.dumps(policy_doc)
)
print(policy["Policy"]["Arn"])// --- TypeScript (AWS SDK v3) ---
import { IAMClient, CreatePolicyCommand } from "@aws-sdk/client-iam";
const policyDoc = {
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Action: ["s3:GetObject", "s3:PutObject"],
Resource: "arn:aws:s3:::my-bucket/*"
}]
};
const iam = new IAMClient({});
const policy = await iam.send(new CreatePolicyCommand({
PolicyName: "S3BucketAccess",
PolicyDocument: JSON.stringify(policyDoc)
}));
console.log(policy.Policy?.Arn);Wrap a role in an instance profile so EC2 instances can assume it automatically via metadata service.
# --- Python (boto3) ---
import boto3
iam = boto3.client("iam")
profile = iam.create_instance_profile(InstanceProfileName="MyEC2Profile")
iam.add_role_to_instance_profile(
InstanceProfileName="MyEC2Profile",
RoleName="MyEC2Role"
)
print(profile["InstanceProfile"]["Arn"])// --- TypeScript (AWS SDK v3) ---
import { IAMClient, CreateInstanceProfileCommand, AddRoleToInstanceProfileCommand } from "@aws-sdk/client-iam";
const iam = new IAMClient({});
const profile = await iam.send(new CreateInstanceProfileCommand({
InstanceProfileName: "MyEC2Profile"
}));
await iam.send(new AddRoleToInstanceProfileCommand({
InstanceProfileName: "MyEC2Profile",
RoleName: "MyEC2Role"
}));
console.log(profile.InstanceProfile?.Arn);Provision an IAM user and generate long-lived programmatic access credentials.
# --- Python (boto3) ---
import boto3
iam = boto3.client("iam")
user = iam.create_user(UserName="alice")
access_key = iam.create_access_key(UserName="alice")
print(access_key["AccessKey"]["AccessKeyId"])
print(access_key["AccessKey"]["SecretAccessKey"])// --- TypeScript (AWS SDK v3) ---
import { IAMClient, CreateUserCommand, CreateAccessKeyCommand } from "@aws-sdk/client-iam";
const iam = new IAMClient({});
await iam.send(new CreateUserCommand({ UserName: "alice" }));
const accessKey = await iam.send(new CreateAccessKeyCommand({ UserName: "alice" }));
console.log(accessKey.AccessKey?.AccessKeyId);
console.log(accessKey.AccessKey?.SecretAccessKey);Confirm which principal your current credentials resolve to (useful for debugging permission issues).
# --- Python (boto3) ---
import boto3
sts = boto3.client("sts")
who = sts.get_caller_identity()
print(who["Arn"]) # arn:aws:iam::111122223333:user/alice
print(who["Account"]) # 111122223333// --- TypeScript (AWS SDK v3) ---
import { STSClient, GetCallerIdentityCommand } from "@aws-sdk/client-sts";
const sts = new STSClient({});
const who = await sts.send(new GetCallerIdentityCommand({}));
console.log(who.Arn); // arn:aws:iam::111122223333:user/alice
console.log(who.Account); // 111122223333Exchange your credentials for temporary credentials under a different role (cross-account, service role delegation).
# --- Python (boto3) ---
import boto3
sts = boto3.client("sts")
creds = sts.assume_role(
RoleArn="arn:aws:iam::111122223333:role/CrossAccountRole",
RoleSessionName="MySession",
DurationSeconds=3600
)
print(creds["Credentials"]["AccessKeyId"])
print(creds["Credentials"]["SessionToken"])// --- TypeScript (AWS SDK v3) ---
import { STSClient, AssumeRoleCommand } from "@aws-sdk/client-sts";
const sts = new STSClient({});
const creds = await sts.send(new AssumeRoleCommand({
RoleArn: "arn:aws:iam::111122223333:role/CrossAccountRole",
RoleSessionName: "MySession",
DurationSeconds: 3600
}));
console.log(creds.Credentials?.AccessKeyId);
console.log(creds.Credentials?.SessionToken);Test whether a principal (user/role) has permission for specific actions without actually invoking them.
# --- Python (boto3) ---
import boto3
iam = boto3.client("iam")
result = iam.simulate_principal_policy(
PolicySourceArn="arn:aws:iam::111122223333:user/alice",
ActionNames=["s3:GetObject", "s3:PutObject"],
ResourceArns=["arn:aws:s3:::my-bucket/file.txt"]
)
for r in result["EvaluationResults"]:
print(f"{r['EvalActionName']}: {r['EvalDecision']}")// --- TypeScript (AWS SDK v3) ---
import { IAMClient, SimulatePrincipalPolicyCommand } from "@aws-sdk/client-iam";
const iam = new IAMClient({});
const result = await iam.send(new SimulatePrincipalPolicyCommand({
PolicySourceArn: "arn:aws:iam::111122223333:user/alice",
ActionNames: ["s3:GetObject", "s3:PutObject"],
ResourceArns: ["arn:aws:s3:::my-bucket/file.txt"]
}));
result.EvaluationResults?.forEach(r => {
console.log(`${r.EvalActionName}: ${r.EvalDecision}`);
});Retrieve all AWS managed and customer-managed policies attached to a role, with pagination support.
# --- Python (boto3) ---
import boto3
iam = boto3.client("iam")
paginator = iam.get_paginator("list_attached_role_policies")
for page in paginator.paginate(RoleName="MyEC2Role"):
for policy in page["AttachedPolicies"]:
print(f"{policy['PolicyName']}: {policy['PolicyArn']}")// --- TypeScript (AWS SDK v3) ---
import { IAMClient, ListAttachedRolePoliciesCommand } from "@aws-sdk/client-iam";
const iam = new IAMClient({});
const result = await iam.send(new ListAttachedRolePoliciesCommand({
RoleName: "MyEC2Role"
}));
result.AttachedPolicies?.forEach(p => {
console.log(`${p.PolicyName}: ${p.PolicyArn}`);
});Restrictive policy that grants only the specific actions and resources required for a task.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadSpecificBucket",
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::my-app-bucket",
"arn:aws:s3:::my-app-bucket/data/*"
]
},
{
"Sid": "WriteLogsOnly",
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:us-east-1:111122223333:log-group:/aws/lambda/my-function:*"
},
{
"Sid": "DenyPublicBuckets",
"Effect": "Deny",
"Action": "s3:*",
"Resource": "*",
"Condition": {
"StringEquals": {
"s3:x-amz-acl": "public-read"
}
}
}
]
}Add metadata tags to roles for cost allocation, resource organization, and ABAC-based access control.
# --- Python (boto3) ---
import boto3
iam = boto3.client("iam")
iam.tag_role(
RoleName="MyEC2Role",
Tags=[
{"Key": "Environment", "Value": "Production"},
{"Key": "Team", "Value": "Backend"}
]
)// --- TypeScript (AWS SDK v3) ---
import { IAMClient, TagRoleCommand } from "@aws-sdk/client-iam";
const iam = new IAMClient({});
await iam.send(new TagRoleCommand({
RoleName: "MyEC2Role",
Tags: [
{ Key: "Environment", Value: "Production" },
{ Key: "Team", Value: "Backend" }
]
}));Configure an OpenID Connect provider to enable workloads (EKS pods, GitHub Actions) to assume roles without long-lived credentials.
# --- Python (boto3) ---
import boto3
iam = boto3.client("iam")
provider = iam.create_open_id_connect_provider(
Url="https://token.actions.githubusercontent.com",
ClientIDList=["sts.amazonaws.com"],
ThumbprintList=["6938fd4d98bab03faadb97b34396831e3780aea1"]
)
print(provider["OpenIDConnectProviderArn"])// --- TypeScript (AWS SDK v3) ---
import { IAMClient, CreateOpenIDConnectProviderCommand } from "@aws-sdk/client-iam";
const iam = new IAMClient({});
const provider = await iam.send(new CreateOpenIDConnectProviderCommand({
Url: "https://token.actions.githubusercontent.com",
ClientIDList: ["sts.amazonaws.com"],
ThumbprintList: ["6938fd4d98bab03faadb97b34396831e3780aea1"]
}));
console.log(provider.OpenIDConnectProviderArn);Remove all inline and attached policies from a role before deleting it (required by AWS).
# --- Python (boto3) ---
import boto3
iam = boto3.client("iam")
policies = iam.list_attached_role_policies(RoleName="MyEC2Role")
for p in policies["AttachedPolicies"]:
iam.detach_role_policy(RoleName="MyEC2Role", PolicyArn=p["PolicyArn"])
iam.delete_role(RoleName="MyEC2Role")
print("Role deleted")// --- TypeScript (AWS SDK v3) ---
import { IAMClient, ListAttachedRolePoliciesCommand, DetachRolePolicyCommand, DeleteRoleCommand } from "@aws-sdk/client-iam";
const iam = new IAMClient({});
const policies = await iam.send(new ListAttachedRolePoliciesCommand({ RoleName: "MyEC2Role" }));
for (const p of policies.AttachedPolicies || []) {
await iam.send(new DetachRolePolicyCommand({ RoleName: "MyEC2Role", PolicyArn: p.PolicyArn }));
}
await iam.send(new DeleteRoleCommand({ RoleName: "MyEC2Role" }));
console.log("Role deleted");Use AWS Access Analyzer to synthesize a minimal policy from observed CloudTrail actions.
# --- Python (boto3) ---
import boto3
aa = boto3.client("accessanalyzer")
job = aa.start_policy_generation(
policyGenerationDetails={
"principalArn": "arn:aws:iam::111122223333:user/alice",
"actionFilter": {
"actions": ["s3:GetObject", "s3:ListBucket"]
}
}
)
print(job["jobId"])// --- TypeScript (AWS SDK v3) ---
import { AccessAnalyzerClient, StartPolicyGenerationCommand } from "@aws-sdk/client-accessanalyzer";
const aa = new AccessAnalyzerClient({});
const job = await aa.send(new StartPolicyGenerationCommand({
policyGenerationDetails: {
principalArn: "arn:aws:iam::111122223333:user/alice",
actionFilter: {
actions: ["s3:GetObject", "s3:ListBucket"]
}
}
}));
console.log(job.jobId);Stack versions: This page was written for boto3 1.43.x (Python 3.10+) and the AWS SDK for JavaScript v3 (Node.js 18+).
Revisado por Chris St. John·Última actualización: 23 jul 2026