Step 1: Create an IAM Role with S3 Access

  1. Go to the IAM Console:
    https://console.aws.amazon.com/iam/

  2. Create a new role:

    • Choose "AWS service" as the trusted entity.

    • Use case: EC2.

    • Click Next.

  3. Attach a policy:

    • Choose AmazonS3ReadOnlyAccess (or create a custom policy if you need more permissions like upload/delete).

    • Click Next, then Create role.

    • Give your role a name, e.g., EC2S3AccessRole.

Step 2: Attach the IAM Role to Your EC2 Instance

  1. Go to the EC2 Dashboard: https://console.aws.amazon.com/ec2/

  2. Select your instance.

  3. Choose Actions > Security > Modify IAM Role.

  4. Select the role you just created (EC2S3AccessRole) and click Update IAM Role.

Step 3: Verify IAM Role is Attached

SSH into your EC2 instance and run:

Bash
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/

It should return the IAM role name. This confirms it's properly attached.

Step 4: Install AWS CLI on EC2 (if not installed)

For Amazon Linux 2:

Bash
sudo yum update -y
sudo yum install aws-cli -y

For Ubuntu:

Bash
sudo apt update
sudo apt install awscli -y

Step 5: Use AWS CLI to Access S3 Bucket

Run commands like:

Bash
aws s3 ls s3://your-bucket-name/
aws s3 cp s3://your-bucket-name/filename.txt .
aws s3 sync s3://your-bucket-name/ /home/ec2-user/s3-files/

No need to configure aws configure if the IAM role is attached. The instance will automatically use the role credentials.

Optional: Create a Custom IAM Policy

If you want more control than AmazonS3ReadOnlyAccess, here’s a sample policy to allow full access to a specific bucket:

JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::your-bucket-name",
        "arn:aws:s3:::your-bucket-name/*"
      ]
    }
  ]
}

Your EC2 instance can now read from (or write to) your S3 bucket securely using the IAM role — no access keys required.