BKO
BKO

Reputation: 141

How Do I Allow GetObject for Public, GetObject+PutObject+DeleteObject for EC2 Instance?

I am trying to set a policy that allows GetObject for public, and GetObject, PutObject, DeleteObject for my Django application in an EC2 Instance.

According to this answer, it seems that the following bucket policy should do the job:

{
    "Version": "2012-10-17",
    "Id": "Policy1683280060839",
    "Statement": [
        {
            "Sid": "Stmt1683280008173",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::my-project-bucket-2023/*"
        },
        {
            "Sid": "Stmt1683280057104",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::667802944954:role/MyProject"
            },
            "Action": [
                "s3:DeleteObject",
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::my-project-bucket-2023/*"
        }
    ]
}

It allows GetObject for all, and in addition to that, allows DeleteObject and PutObject to IAM Role. I have assigned this role to the EC2 Instance. All public access is blocked.

But I can still put objects to my bucket from localhost where I have not provided ACCESS_KEY. I have set up storage information in settings.py, but as you can see below, ACCESS_KEY is commented out.

# AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID')
# AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY')

AWS_STORAGE_BUCKET_NAME = "my-project-bucket-2023"

DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"

STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"

AWS_S3_CUSTOM_DOMAIN = AWS_STORAGE_BUCKET_NAME + ".s3.us-east-2.amazonaws.com"
AWS_S3_FILE_OVERWRITE = False
AWS_QUERYSTRING_AUTH = False

I have tried a lot of other policies, and they all were not successful.

How can I allow GetObject to public, deny all others, and allow GetObject, PutObject, DeleteObject to my django project in an EC2 Instance?

Upvotes: 0

Views: 76

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 270144

If an IAM Role has been assigned to the instance, then any code running on the instance that uses an AWS SDK (eg boto3) will retrieve access credentials from the EC2 Instance Metadata Service.

There is no need for your code to retrieve credentials from Environment Variables, unless you have specifically added credentials to Environment Variables and you wish to use those credentials instead of the IAM Role.

By the way, when granting permission for an IAM User or an IAM Role to use an Amazon S3 bucket, it is preferable to put those permissions directly on the IAM User / IAM Role rather than using a Bucket Policy. Bucket Policies are typically used for granting Public or Cross-account permissions rather than granting user-specific permission.

Upvotes: 3

Related Questions