What are IAM Roles?
IAM roles are like temporary visitor badges. Instead of giving someone a permanent keycard (access keys), you give them a badge that works for a limited time and only in specific areas. When the time's up, the badge stops working.
Roles are used by AWS services (like EC2 or Lambda) to access other services, and by users who need temporary access. They're more secure than long-lived credentials because they automatically expire.
Roles vs Policies
Policies define what's allowed or denied. Roles are entities that can assume policies. Think of it this way: a policy is the rulebook, and a role is a player who follows those rules.
You can attach policies to roles, and then assign roles to users or AWS services. The role provides temporary credentials that the service uses to make AWS API calls. It's like a relay race — the role passes the baton (credentials) to whoever needs it.
When to Use Roles
EC2 instances that need to access S3 should use an instance role instead of hard-coded credentials. If the instance is compromised, the attacker only gets temporary access, not permanent keys.
Lambda functions that read from DynamoDB should use execution roles. This is the standard pattern for serverless applications — each function gets exactly the permissions it needs.
Cross-account access uses roles to let users in one AWS account access resources in another. It's like having a guest pass for a different building in a corporate campus.
Creating a Role
Creating a role involves specifying who can assume it (the trusted entity) and what permissions it grants. For example, to create a role for an EC2 instance:
aws iam create-role \
--role-name EC2-S3-Access \
--assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "ec2.amazonaws.com"},
"Action": "sts:AssumeRole"
}]
}'
This creates a role that EC2 instances can assume. Then attach a policy to give it S3 access.
Role Best Practices
Use roles instead of access keys whenever possible. They're more secure, easier to manage, and follow AWS best practices. If you're hard-coding credentials in your code, you're doing it wrong.
Give roles the minimum permissions needed. Use condition keys to restrict when and how a role can be assumed. Regularly audit your roles and remove any that are no longer needed. Roles are powerful, but only if managed carefully.