Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

Create an IAM Role and Policy for EC2 and Lambda Step by Step

Build least-privilege access for S3 read: one customer-managed policy, an EC2 instance role, and a Lambda execution role. Prove both, then clean up.

In this chapter

  • Create a tight S3 read policy
  • EC2 instance profile / role
  • Lambda execution role + basic logs
  • Verify with CLI and a tiny function
  • Cleanup roles and policy

Everyday example before the lab

Why this lab matters

In a fictional stationery shop, the stock-checking program should read the stock file but must not replace it. A second program reads the same file when an order arrives. One narrow read policy describes the job, while separate EC2 and Lambda roles identify which service is doing it. This lab separates the worker’s data access from the administrator’s permission to assign a role, so a denied setup step is not mistaken for a denied file read.

1. Lab: click by click

Region ap-south-1. Create a private bucket yourname-iam-lab and upload hello.txt with body ok. Replace names/account id.

A. Customer managed policy

This lab creates one reusable policy for a small S3 action. A customer managed policy is yours to edit and can be attached to more than one role. First identify the lab object and the exact operation it needs. Then set up one role that EC2 can use and a separate role that Lambda can use. Both workloads can have the same narrow S3 permission although different services must be able to assume their respective roles.

A role has an Amazon Resource Name, usually shortened to ARN. It identifies the role when you assign it to a workload. The role’s trust controls which service can assume it. The deployer’s iam:PassRole permission controls which role the deployer can assign. A deployment error referring to PassRole is about that assignment, while a running function’s S3 error concerns the role used for the request.

  1. IAM → Policies → Create policy → JSON.
  2. Paste (replace BUCKET):
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ListBucket",
      "Effect": "Allow",
      "Action": ["s3:ListBucket"],
      "Resource": "arn:aws:s3:::BUCKET"
    },
    {
      "Sid": "ReadObjects",
      "Effect": "Allow",
      "Action": ["s3:GetObject"],
      "Resource": "arn:aws:s3:::BUCKET/*"
    }
  ]
}
  1. Name: lab-s3-read-one-bucket. Create.

B. EC2 role

Follow one sample read from the server rather than from your own terminal credentials. Assign the approved EC2 role, then run the caller-identity check on the server itself. In EC2, the instance profile is the service mechanism that makes a role available to the instance. The temporary role session it supplies should appear in the caller ARN.

Use the approved read on the exact private S3 object in the policy. If that object reads correctly but an unrelated key was expected to be denied, try the negative test as the same caller and compare results. If the check instead shows your personal identity, identify the SDK or CLI provider that signed it before expanding permissions on the role. Then repeat the later Lambda exercise and compare the ARN to confirm the two workloads are using their own roles.

  1. IAM → Roles → Create role → AWS service → EC2.
  2. Attach lab-s3-read-one-bucket only (not Admin). Role name: lab-ec2-s3-read.
  3. EC2 → instance → Actions → Security → Modify IAM role → lab-ec2-s3-read.
  4. On EC2:
aws sts get-caller-identity
aws s3 cp s3://BUCKET/hello.txt -
# expect: ok
# aws s3 cp s3://SOME-OTHER-BUCKET/x .   # should fail AccessDenied

C. Lambda role

  1. IAM → Roles → Create role → Lambda. Attach lab-s3-read-one-bucket and AWSLambdaBasicExecutionRole. Name: lab-lambda-s3-read.
  2. Lambda → Create function lab-s3-get, Python 3.12, use existing role lab-lambda-s3-read.
  3. Code:
import boto3, os
def lambda_handler(event, context):
    b = os.environ["BUCKET"]
    body = boto3.client("s3").get_object(Bucket=b, Key="hello.txt")["Body"].read().decode()
    return {"ok": True, "body": body}
  1. Env BUCKET=your bucket. Deploy → Test. Expected JSON with "body": "ok".

Cleanup

  1. Delete Lambda function. Remove IAM role from EC2 (or terminate lab instance).
  2. Delete roles lab-ec2-s3-read, lab-lambda-s3-read. Delete policy lab-s3-read-one-bucket.
  3. Empty and delete the lab bucket.

Common errors: cause and safe next check

The role is absent from the EC2 dropdown

That dropdown lists instance profiles. The IAM console creates a matching profile for an EC2 role, but a role made through an API or CLI may not have one. Check that the intended EC2 role is contained in the intended profile; changing only a role name does not create a profile.

S3 read succeeds but Lambda logs are missing

S3 data permissions and CloudWatch Logs permissions are different. Read Configuration → Permissions to identify the function’s actual execution role, then inspect its logging permissions. A successful object read does not prove that log delivery is authorized.

Assigning the role fails with iam:PassRole

The person configuring the service needs permission to pass the approved role. This is separate from the S3 permissions used by the workload. Ask the administrator to review the exact role ARN and target service; do not broaden the workload’s bucket access to solve a deployer error.

Practical questions and full answers

How can I tell that the EC2 test used the intended role?

In the existing caller-identity output, inspect the Account and Arn fields locally. An assumed-role ARN should name the intended role and session. Successful S3 output alone could come from a different configured identity, so do not skip this identity check.

Must the Lambda code assume its own execution role?

No. Lambda assumes its execution role when the function runs. The SDK can use the supplied temporary credentials. An extra AssumeRole call to the same role is unnecessary for this lab and can fail without a separate self-trust configuration.

Why can the plain sample file work while a KMS-encrypted file fails?

An object encrypted with an AWS KMS customer managed key can need kms:Decrypt in addition to the S3 read permission. Ask the key administrator to inspect the applicable key access as well as the object permission. Do not switch off encryption or grant access to every key just to make a different file behave like the plain practice sample.

2. Interview angles

Q. Why instance role not access keys?

Keys get stolen from disk; role creds rotate via metadata.

Q. Why two statements List + Get?

ListBucket on bucket ARN; GetObject on object ARN.

Q. Basic execution role?

Writes CloudWatch Logs.

Q. Admin policy on Lambda?

Breaks least privilege — avoid.

Try at home

  1. Add s3:PutObject for a prefix only and test deny outside prefix.
  2. Try the same role pattern for DynamoDB GetItem.

In short

  1. Customer managed policy → attach to roles.
  2. EC2 instance role + Lambda execution role.
  3. Prove allow and deny; then delete lab artifacts.

Separate trust, role permissions and assignment

A Lambda role trusts lambda.amazonaws.com, its permissions allow the needed target resource, and the deployer needs permission to assign that role. Recheck the actual function's role and a log from one invocation after editing.

Interview check What does PassRole grant to a deployer?

It allows the deployer to pass a specified role to an approved AWS service where supported. The service assumes it; the deployer does not receive the role credentials from PassRole.

Reference documentation

Practise this chapter

Interview questions and answers

Why might Lambda deploy correctly but fail to read S3?

Deployment can succeed when the deployer may pass the role and Lambda can assume it. The function still calls S3 using that role’s permissions. I would verify the attached role and the exact bucket or object, then inspect other applicable policy or encryption controls.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. EC2 and Lambda need the same limited S3 action. What can they safely share in this exercise?

Answer and explanation

B. A customer managed permissions policy on separate appropriate roles

The same narrow policy can be reused. Each role has trust appropriate to the AWS service that assumes it.

2. The deployer gets an iam:PassRole error. Which permission should be reviewed first?

Answer and explanation

B. Caller permission to assign that exact approved role

PassRole concerns the deployer’s role assignment. S3 access concerns the identity that uses the role later.

3. How do you check which role the workload actually used?

Answer and explanation

B. Inspect caller identity from inside the workload

The requested policy and configured role are not proof of the principal signing the actual operation.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Bavaria Motors is a automobile business in Munich. Lukas Becker looks after its IT and cloud work. They count money in EUR and run their AWS resources in the eu-central-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 12

Easy List functions

See which functions exist in this Region.

List the Lambda functions in eu-central-1.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Trust policy for a Lambda role

The trust policy says WHO may take the role.

Write a trust policy that lets lambda.amazonaws.com assume the role.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Medium Invoke a function

Invoke runs the function now and saves its answer in a file.

Invoke bavariamotors-orders-fn and save the response to out.json.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Change timeout and memory

More memory also gives more CPU; timeout stops runaway runs.

Set bavariamotors-orders-fn to timeout 30 seconds and memory 512 MB.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Let a function write logs

Without these actions, Lambda logs never appear in CloudWatch.

Allow logs:CreateLogGroup, logs:CreateLogStream, logs:PutLogEvents on arn:aws:logs:*:*:* only.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Medium Trust policy for an EC2 role

The trust policy says WHO may take the role.

Write a trust policy that lets ec2.amazonaws.com assume the role.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Hard Create a Lambda function

Lambda needs the code zip, a runtime, a handler name and an execution role.

Create function bavariamotors-orders-fn: runtime python3.12, handler app.handler, role arn:aws:iam::106249807804:role/lambda-basic, code in function.zip.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Set environment variables

Keep settings like table names out of the code.

Set the environment variable TABLE=bavariamotors-orders on bavariamotors-orders-fn.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Invoke with a JSON payload

In CLI v2, raw JSON needs --cli-binary-format raw-in-base64-out.

Invoke bavariamotors-orders-fn with payload {"orderId":"o-101"} (raw JSON) and save the reply in out.json.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Lambda GB-seconds

Lambda bills memory × time.

1,000,000 invocations, 512 MB memory, 200 ms each. How many GB-seconds?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Hard Connect an SQS queue to Lambda

An event source mapping makes Lambda poll the queue and process messages in batches.

Create an event source mapping from queue arn:aws:sqs:eu-central-1:106249807804:bavariamotors-orders to bavariamotors-orders-fn with batch size 10.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Let S3 call your function

A resource-based permission is needed before S3 can invoke the function.

Add permission statement s3invoke to bavariamotors-orders-fn so s3.amazonaws.com can call lambda:InvokeFunction from bucket arn:aws:s3:::bavariamotors-uploads.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Revision, comparison and interview cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Revision card: Write a least-privilege S3 read policy. AmazonS3FullAccess on a demo role teaches the wrong habit. A customer-managed policy with s3:GetObject (and ListBucket if needed) on one bucket ARN is enough for a read lab. IAM → Policies → Create → JSON with Version 2012-10-17 and Resource arn:aws:s3:::lab-bucket/*. Policy simulator or CLI get-object succeeds; delete-object is denied.
Revision card: Write a least-privilege S3 read policy · Download PNG · Open card page
Revision card: Attach role to EC2. Putting AKIA keys on the instance is how keys leak into GitHub. Create an EC2 instance profile/role with your S3 read policy; attach to the instance; use the instance metadata credentials automatically via AWS CLI. IAM role trusted by ec2.amazonaws.com → attach policy → Modify IAM role on the instance (or launch with it). On the instance: aws s3 cp s3://lab-bucket/hi.txt - works with no keys configured.
Revision card: Attach role to EC2 · Download PNG · Open card page
Revision card: Lambda execution role. Lambda also needs a role — and basic CloudWatch Logs permissions or you see no logs. Create a Lambda execution role trusted by lambda.amazonaws.com; attach AWSLambdaBasicExecutionRole plus your S3 read policy. Function › Configuration › Permissions › use the new role; test an S3 GetObject handler. Test event succeeds; CloudWatch log stream shows START/END without AccessDenied on logs.
Revision card: Lambda execution role · Download PNG · Open card page
Comparison: AWS managed policy vs Customer managed policy. AWS managed policy: AWS maintains broad reusable policies. Customer managed policy: You write/reuse tight JSON for your ARNs.
Comparison: AWS managed policy vs Customer managed policy · Download PNG · Open card page
Interview card: How do you prove least privilege worked?. Try the allowed action and a denied one; use policy simulator or real CLI calls. Evidence beats “we attached AmazonS3FullAccess”. aws s3 cp get succeeds; aws s3 rm returns AccessDenied on the same role.
Interview card: How do you prove least privilege worked? · Download PNG · Open card page
Interview card: Why does Lambda need BasicExecutionRole too?. Without logs permissions the function may run but you cannot debug in CloudWatch. BasicExecutionRole allows creating log streams for the function. Attach AWSLambdaBasicExecutionRole plus your tight S3 policy on the execution role.
Interview card: Why does Lambda need BasicExecutionRole too? · Download PNG · Open card page

More cards: Ravi Sir's Cards.