Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Granting access to S3 resources based on role name

IAM policy variables are quite cool and let you create generic policys to, for example, give users access to paths in an S3 bucket based on their username, like this:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": ["s3:GetObject","s3:PutObject","s3:DeleteObject"],
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::fooCorp-user-files/${aws:username}/*"
        },
        {
            "Action": "s3:ListBucket",
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::fooCorp-user-files"
        }
    ]
}

My question is, how can this be done using roles (attached to EC2 instances) instead of user accounts?

I have a number of app servers with unique IAM user accounts that are linked to a generic policy similar to the one above. This isolates the files accessible by each user/app without creating multiple policies.

I want switch these servers to use roles instead but there doesn't seem to be an equivalent IAM variable like aws:rolename.

The docs indicate that when using a role assigned to an EC2 instance the aws:username variable isn't set and aws:userid is [role-id]:[ec2-instance-id] (which isn't helpful either).

This really seems like something you should be able to do.. or am I coming at this the wrong way?

like image 570
Molomby Avatar asked Oct 16 '25 19:10

Molomby


1 Answers

I've been looking for the same and after a lot of searching my conclusion was that it is not possible to use the role name as a variable in a IAM policy (I'd love to be proven wrong though).

Instead, I tagged my role with a name and ended up with this:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": ["s3:GetObject","s3:PutObject","s3:DeleteObject"],
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::fooCorp-user-files/${aws:PrincipalTag/name}/*"
        },
        {
            "Action": "s3:ListBucket",
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::fooCorp-user-files"
        }
    ]
}
like image 68
Niklas Ekman Avatar answered Oct 18 '25 13:10

Niklas Ekman