How do I restrict S3 bucket access to specific IP addresses using ACLs?
In this guide, we’ll look at how to restrict access to an S3 bucket to specific IP addresses. This is useful for enhancing security by ensuring only designated IPs can interact with your bucket. We’ll accomplish this by creating an S3 bucket and applying a bucket policy to enforce IP whitelisting.
Here’s what we’ll set up:
- An S3 bucket.
- A bucket policy that restricts access based on specific IP addresses.
Let’s get started with the code:
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Step 1: Define an S3 bucket
const exampleBucket = new aws.s3.BucketV2("example_bucket", {
bucket: "example-bucket",
acl: "private",
});
// Step 2: Define the bucket policy to restrict access to specific IP addresses
const exampleBucketPolicy = new aws.s3.BucketPolicy("example_bucket_policy", {
bucket: exampleBucket.id,
policy: pulumi.jsonStringify({
Version: "2012-10-17",
Statement: [{
Effect: "Deny",
Principal: "*",
Action: "s3:*",
Resource: [
exampleBucket.arn,
pulumi.interpolate`${exampleBucket.arn}/*`,
],
Condition: {
NotIpAddress: {
"aws:SourceIp": [
"203.0.113.0/24",
"198.51.100.0/24",
],
},
},
}],
}),
});
export const bucketName = exampleBucket.bucket;
export const bucketArn = exampleBucket.arn;
In this setup:
- The
aws_s3_bucket "example_bucket"
resource creates an S3 bucket named “example-bucket” with a private ACL. - The
aws_s3_bucket_policy "example_bucket_policy"
resource applies a policy to the bucket that denies access unless the request originates from the specified IP addresses (“203.0.113.0/24” and “198.51.100.0/24”). - We use stack outputs to make the bucket name and ARN accessible.
In conclusion, this configuration ensures that only requests from the specified IP ranges can access your S3 bucket, enhancing your security posture.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.