EC2 instance profile VS Trust policy
Let me break this down:
EC2 Instance Profile:
A container for an IAM role specifically designed for EC2 instances
Automatically manages temporary credentials and rotates them
Credentials are automatically available to applications running on the EC2 instance
Best practice for EC2 instances accessing AWS services
Example use case: When your EC2 instance needs to access S3, DynamoDB, or other AWS services
Trust Relationship Policy (or Trust Policy):
Defines which entities can assume an IAM role
Used primarily for cross-account access or service-to-service authentication
Part of every IAM role but serves a different purpose than instance profiles
Example use cases:
Allowing AWS Lambda to assume a role to access other services
Enabling cross-account access between AWS accounts
Allowing external identity providers (like Azure AD) to assume roles
Enabling AWS services to act on your behalf (like CloudFormation)
When to use a Trust Policy:
Cross-account access:
Service-to-service authentication:
Key Distinction:
EC2 instance profiles are specifically for EC2 instances accessing AWS services within the same account
Trust relationship policies are broader and define who can assume the role, whether it's other AWS services, external identities, or cross-account access
Best Practice: For EC2 instances accessing AWS services in the same account, always use instance profiles rather than manually managing trust relationships. Trust relationship policies should be reserved for scenarios involving cross-account access or service-to-service interactions beyond simple EC2-to-AWS-service communication.
Examples
A practical examples of both approaches to help illustrate the differences.
Option A (Recommended Approach for EC2 Instances):
First, create the IAM policy for DynamoDB access:
Create the IAM role with this policy:
Create and attach the instance profile:
In your application code, you don't need to handle credentials:
Option B (Not Recommended for EC2 Instances):
Create similar IAM policy as above
Create IAM role with specific EC2 instance in trust relationship:
In your application, you'd need to explicitly assume the role:
Key differences that make Option A better:
Simpler application code - no credential management needed
Automatic credential rotation
No need to store or manage any credentials in your application
Uses AWS's built-in instance profile mechanism
Follows AWS best practices for EC2 instance permissions
Easier to maintain and more secure
With Option B, you'd need to:
Manage credential rotation yourself
Handle credential errors and refreshing
Store role ARN in your application
Deal with more complex error scenarios
Maintain more complex code
Last updated
Was this helpful?