How can i create bucket and objects with not public access using boto3 in aws?

Viewed 3087

I want to create a bucket and objects with not public access i.e it should be private using boto3 python code how can I achieve it?

s3_client = boto3.client('s3', aws_access_key_id=accessKey,
                       aws_secret_access_key=secretKey,
                       region_name=region)
   

 s3_bucket= s3_client.create_bucket(Bucket=bucket_name)
    print('bucket created')
    print(s3_bucket)
    bucket_name = 'bucket123'
    response_public = s3_client.put_public_access_block(
        Bucket=bucket_name,
        PublicAccessBlockConfiguration={
            'BlockPublicAcls': True,
            'IgnorePublicAcls': True,
            'BlockPublicPolicy': True,
            'RestrictPublicBuckets': True
        },
    )
    print("pubic",response_public)

Bucket created but getting

error: in public access as 'S3' object has no attribute 'put_public_access_block'

2 Answers

Edit

As thought originally the boto3 version was a legacy version (1.9.42), this function is not available in that version as you can see from this documentation.

Original

I ran it like so and everything successfully applied, I would suggest looking at indentation and verifying the version of Boto3 you're running.

s3_client = boto3.client('s3', region_name='eu-west-1')
    bucket_name= 'ohfihfhfeuhehfuhfeih'
    
    s3_bucket= s3_client.create_bucket(Bucket=bucket_name, CreateBucketConfiguration={'LocationConstraint': 'eu-west-1'})

    response_public = s3_client.put_public_access_block(
        Bucket=bucket_name,
        PublicAccessBlockConfiguration={
            'BlockPublicAcls': True,
            'IgnorePublicAcls': True,
            'BlockPublicPolicy': True,
            'RestrictPublicBuckets': True
        },
    )

In short your code is fine (I added the region configuration because certain regions require this), there is another factor. Fix the indentation, check your boto3 version (and update if its old, the current version is 1.14.7).

The reason is probably due to the fact that you are creating bucket called

bucket_name= 's3buck123'

but then you use different name to set put_public_access_block

bucket_name = 'bucket123'

Also the indentation is wrong, but I assume this is due to copy and paste to SO.

Related