mspahr
mspahr

Reputation: 153

Whitelist IP Address in S3 Bucket Policy in AWS CDK

I am trying to write my infrastructure using AWS CDK as opposed to building it with the console as I had previously. I am writing my S3 bucket policy and am confused on how to give conditions. My goal is to recreate this Bucket Policy from the AWS Console that works as intended:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AddPerm",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::**********/*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": "*********"
                }
            }
        }
    ]
}

My current aws cdk code for my bucket policy looks like this:

const bucketPolicy = new iam.PolicyStatement({
      actions: ['s3:GetObject'],
      resources: [`${bucket.bucketArn}/*`],
      principals: [new iam.Anyone()],
      conditions: ...
    });

Thanks for your help in advance!

Upvotes: 1

Views: 1772

Answers (2)

takezoux2
takezoux2

Reputation: 193

Small update.
iam.Anyone is deprecated. Use iam.AnyPrincipal instead

const bucketPolicy = new iam.PolicyStatement({
    actions: ['s3:GetObject'],
    resources: [bucket.arnForObjects('*')],
    principals: [new iam.AnyPrincipal()],
    conditions: { 
        'IpAddress': {
            'aws:SourceIp': '***.***.***.***'
        }
    }
});

Upvotes: 1

mspahr
mspahr

Reputation: 153

I just solved it by doing this:

const bucketPolicy = new iam.PolicyStatement({
    actions: ['s3:GetObject'],
    resources: [`${bucket.bucketArn}/*`],
    principals: [new iam.Anyone()],
    conditions: { 
        'IpAddress': {
            'aws:SourceIp': '***.***.***.***'
         }
      }
    });

Upvotes: 2

Related Questions