简体   繁体   中英

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!

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': '***.***.***.***'
         }
      }
    });

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': '***.***.***.***'
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM