Define Bucket Policy
Using this option, you can change the access policies of the bucket. Setting specific policies for the bucket has many benefits, for example:
1- You can change the access policy for some objects of a bucket.
2- You can provide access to the bucket for other users.
Components
- Credentials
- Bucket Name
- Bucket Policy
Bucket Policy
It is a set of conditions and propositions that are used to determine the levels of access to the bucket.
- .NET
- PHP
- Python
- Javascript
- GO
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX - License - Identifier: Apache - 2.0
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Reflection;
namespace PutBucketPolicy
{
class PutBucketPolicy
{
// This example shows how to check a bucket existence.
// The examples uses AWS SDK for .NET 3.5 and .NET 5.0.
private static IAmazonS3 _s3Client;
// Specify the name of the bucket to check.
private const string BUCKET_NAME = "<BUCKET_NAME>";
static async Task Main()
{
var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY>");
var config = new AmazonS3Config { ServiceURL = "<ENDPOINT>" };
_s3Client = new AmazonS3Client(awsCredentials, config);
await PutBucketPolicyAsync(_s3Client, BUCKET_NAME);
}
/// <summary>
/// PutBucketPolicyAsync calls the DoesS3BucketExistV2Async method
/// to set bucket's policies.
/// </summary>
/// <param name="client">The Amazon S3 client object.</param>
/// <param name="bucketName">The name of the bucket to check.</param>
static async Task PutBucketPolicyAsync(IAmazonS3 client, string bucketName)
{
string newPolicy = @"{
""Statement"":[{
""Sid"":""PolicyName"",
""Effect"":""Allow"",
""Principal"": { ""AWS"": ""*"" },
""Action"":[""s3:PutObject"",""s3:GetObject""],
""Resource"":[""arn:aws:s3:::rezvani/user_*""]
}]}";
PutBucketPolicyRequest putRequest = new PutBucketPolicyRequest
{
BucketName = bucketName,
Policy = newPolicy
};
Object policy = await client.PutBucketPolicyAsync(putRequest);
foreach (PropertyInfo prop in policy.GetType().GetProperties())
{
Console.WriteLine($"{prop.Name}: {prop.GetValue(policy, null)}");
}
Console.WriteLine($"Policy successfully added to {bucketName} bucket");
}
}
}
<?php
require('client.php');
$bucket = $config['sample_bucket'];
$policy = json_encode([
"Version" => "2012-10-17",
"Statement" => [
[
"Sid" => "id-1",
"Effect" => "Allow",
"Principal" => "*",
"Action" => ["s3:GetObject"],
"Resource" => ["arn:aws:s3:::$bucket/*"]
]
]
]);
$result = $client->putBucketPolicy([
'Bucket' => $config['sample_bucket'],
'Policy' => $policy,
]);
import boto3
import logging
import json
from botocore.exceptions import ClientError
# Configure logging
logging.basicConfig(level=logging.INFO)
try:
s3_resource = boto3.resource(
's3',
endpoint_url='endpoint_url',
aws_access_key_id='access_key',
aws_secret_access_key='secret_key'
)
except Exception as exc:
logging.error(exc)
else:
try:
bucket_name = 'sample_bucket'
bucket_policy = s3_resource.BucketPolicy(bucket_name)
policy = {
'Version': '2012-10-17',
'Statement': [{
'Sid': 'PolicyName',
'Effect': 'Allow',
'Principal': '*',
'Action': ['s3:GetObject'],
'Resource': f'arn:aws:s3:::{bucket_name}/user_*'
}]
}
# Convert the policy from JSON dict to string
policy = json.dumps(policy)
bucket_policy.put(Policy=policy)
logging.info(bucket_policy.policy)
except ClientError as e:
logging.error(e)
// Import required AWS SDK clients and commands for Node.js
const { S3Client, PutBucketPolicyCommand } = require('@aws-sdk/client-s3');
// Create an S3 client service object
const s3 = new S3Client({
region: 'default',
endpoint: 'endpoint_url',
credentials: {
accessKeyId: 'access_key',
secretAccessKey: 'secret_key',
},
});
const BUCKET_NAME = 'sample_bucket';
// Create the policy
const readOnlyAnonUserPolicy = {
Version: '2012-10-17',
Statement: [
{
Sid: 'AddPerm',
Effect: 'Allow',
Principal: '*',
Action: ['s3:GetObject'],
Resource: [''],
},
],
};
// create selected bucket resource string for bucket policy
const bucketResource = 'arn:aws:s3:::' + BUCKET_NAME + '/*'; //BUCKET_NAME
readOnlyAnonUserPolicy.Statement[0].Resource[0] = bucketResource;
// // convert policy JSON into string and assign into params
const bucketPolicyParams = {
Bucket: BUCKET_NAME,
Policy: JSON.stringify(readOnlyAnonUserPolicy),
};
const run = async () => {
try {
const response = await s3.send(
new PutBucketPolicyCommand(bucketPolicyParams)
);
console.log('Success, permissions added to bucket', response);
} catch (err) {
console.log('Error', err);
}
};
run();
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
// Sets a read only anonymous user policy for a bucket. If the bucket doesn't
// exist, or there was and error an error message will be printed instead.
//
// Usage:
// go run s3_put_bucket_policy.go BUCKET_NAME
func main() {
if len(os.Args) != 2 {
exitErrorf("bucket name required\nUsage: %s bucket_name",
filepath.Base(os.Args[0]))
}
bucket := os.Args[1]
sess, err := session.NewSession(&aws.Config{
Credentials: credentials.NewStaticCredentials("<ACCESS_KEY>", "<SECRET_KEY>", ""),
})
svc := s3.New(sess, &aws.Config{
Region: aws.String("default"),
Endpoint: aws.String("<ENDPOINT_URL>"),
})
// Create a policy using map interface. Filling in the bucket as the
// resource.
readOnlyAnonUserPolicy := map[string]interface{}{
"Version": "2012-10-17",
"Statement": []map[string]interface{}{
{
"Sid": "PolicyName",
"Effect": "Allow",
"Principal": "*",
"Action": []string{
"s3:GetObject",
},
"Resource": []string{
fmt.Sprintf("arn:aws:s3:::%s/user_*", bucket),
},
},
},
}
// Marshal the policy into a JSON value so that it can be sent to S3.
policy, err := json.Marshal(readOnlyAnonUserPolicy)
if err != nil {
exitErrorf("Failed to marshal policy, %v", err)
}
// Call S3 to put the policy for the bucket.
_, err = svc.PutBucketPolicy(&s3.PutBucketPolicyInput{
Bucket: aws.String(bucket),
Policy: aws.String(string(policy)),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok && aerr.Code() == s3.ErrCodeNoSuchBucket {
// Special error handling for the when the bucket doesn't
// exists so we can give a more direct error message from the CLI.
exitErrorf("Bucket %q does not exist", bucket)
}
exitErrorf("Unable to set bucket %q policy, %v", bucket, err)
}
fmt.Printf("Successfully set bucket %q's policy\n", bucket)
}
func exitErrorf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}
The following command can be used to execute the aforementioned code, presuming the code file is called s3_put_bucket_policy.go:
go run s3_put_bucket_policy.go BUCKET_NAME