An IAM role is an AWS identity used by a resource such as an EC2 instance or Lambda function. IAM checks the identity when that resource calls an AWS API, then evaluates the role’s identity policies to decide whether the action is allowed. A role has no permissions by default. section 5.3.2 section 6.3.4
Use a role instead of storing an IAM user’s access keys on an EC2 instance. Credentials based on the role are supplied automatically. The role must both trust the service that assumes it and have policies allowing the actions its workload needs. section 5.3.5
To give an EC2 instance access to Systems Manager:
- In the IAM console, create a role with AWS Service and EC2 as the trusted entity. section 3.1.1
- Attach AmazonSSMManagedInstanceCore, then select the role under IAM instance profile when configuring the instance. section 3.1.1
- With the required agent and role in place, connect through the instance’s Session Manager tab without allowing inbound SSH. section 3.1.2
Let an instance stop itself
An EC2 instance can run aws ec2 stop-instances after a delay, but its role needs permission for ec2:StopInstances. A CloudFormation configuration creates the role, places it in an instance profile, and associates that profile with the instance. In this example, a tag condition limits the permission because the action cannot be restricted to the instance itself without a cyclic dependency. section 5.3.5
Lambda uses roles for the same purpose. Temporary role credentials reach each invocation through environment variables, and the AWS SDK uses them to sign requests. In SAM, each function gets a role with CloudWatch Logs write access by default; a function that tags EC2 instances also needs a policy allowing ec2:CreateTags. Grant only the actions and resources the function needs. section 6.3.4
Listing 6.6 A custom policy for adding tags to EC2 instances
# [...]
EC2OwnerTagFunction:
Type: AWS::Serverless::Function
Properties:
Handler: lambda_function.lambda_handler
Runtime: python3.9
CodeUri: '.'
Policies: #1
- Version: '2012-10-17'
Statement:
- Effect: Allow #2
Action: 'ec2:CreateTags' #3
Resource: '*' #4
# [...]
The SAM function configuration adds an identity policy for ec2:CreateTags, an action its default logging permission does not cover. section 6.3.4










