AWS IAM: Create a Role with Trust Policy

Create an IAM role using aws iam create-role with a trust policy document. Covers Lambda execution roles, EC2 instance profiles, and cross-account roles.

IAM Operations

Detailed Explanation

Creating IAM Roles from the CLI

IAM roles define who can assume the role (trust policy) and what the role can do (permission policies). The create-role command establishes the role with its trust policy.

Lambda Execution Role

aws iam create-role \
  --role-name lambda-exec-role \
  --assume-role-policy-document '{
    "Version": "2012-10-17",
    "Statement": [{
      "Effect": "Allow",
      "Principal": {"Service": "lambda.amazonaws.com"},
      "Action": "sts:AssumeRole"
    }]
  }' \
  --description "Execution role for Lambda functions"

EC2 Instance Role

aws iam create-role \
  --role-name ec2-app-role \
  --assume-role-policy-document '{
    "Version": "2012-10-17",
    "Statement": [{
      "Effect": "Allow",
      "Principal": {"Service": "ec2.amazonaws.com"},
      "Action": "sts:AssumeRole"
    }]
  }'

Trust Policy from File

aws iam create-role \
  --role-name my-role \
  --assume-role-policy-document file://trust-policy.json

For complex trust policies, using file:// is cleaner than inline JSON.

Cross-Account Role

aws iam create-role \
  --role-name cross-account-reader \
  --assume-role-policy-document '{
    "Version": "2012-10-17",
    "Statement": [{
      "Effect": "Allow",
      "Principal": {"AWS": "arn:aws:iam::987654321098:root"},
      "Action": "sts:AssumeRole",
      "Condition": {"StringEquals": {"sts:ExternalId": "unique-external-id"}}
    }]
  }'

Complete Workflow

After creating the role, attach permission policies:

# 1. Create the role
aws iam create-role --role-name my-role --assume-role-policy-document file://trust.json

# 2. Attach managed policies
aws iam attach-role-policy --role-name my-role --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

# 3. (Optional) Add inline policy
aws iam put-role-policy --role-name my-role --policy-name custom-policy --policy-document file://policy.json

Use Case

Setting up execution roles for Lambda functions, creating service-linked roles for EC2 or ECS, establishing cross-account access patterns, or configuring roles for CI/CD service principals.

Try It — AWS CLI Command Builder

Open full tool