Python in AWS : Create S3 Bucket & Assign Bucket Policy

Introduction:

Hi Everyone, I have stared a series called “Python in AWS” wherein I will release blogs related to Infrastructure as Code (IaC) using Python in AWS environment.

We will see how to manage AWS resources via Python code. This series will be very interesting so please follow me.

In the very first blog of this series we will see how to create a S3 bucket and assign a bucket policy via code.

So lets start..

Pre-requisites:

  1. You must be able to login to AWS console.
  2. Install Python 3.x (latest) on your laptop/desktop
  3. Install AWS CLI (Optional but recommended)
  4. Configure AWS profile to connect to AWS console
  5. Install boto3 module using pip command

Later, I will write a blog on how to set up your machine for AWS development using Python. 🙂

Create a Bucket:

Let’s see how to create a single bucket using Python.

Run the following code to create a single bucket using Python

# Author: Jagat Pradhan
# Disclaimer : Use at your own risk. this is tested in LAB environment
# This script is to create a single bucket in a region

import boto3

# connect to AWS console
aws_console = boto3.session.Session(profile_name="boto3")
# connect to S3
s3_console = aws_console.client(service_name='s3', region_name='us-east-1')

# bucket name
BUCKET_NAME = 'jagat-test-bucket-2021'


def create_bucket(bucket_name):

    s3_console.create_bucket(
        Bucket=bucket_name,
        # CreateBucketConfiguration={
        # if u use 'us-east-1' lcoation validation error wil occur, bcoz it creates bucket in us-east-1 by default.
        # 'LocationConstraint': 'us-east-2'
        # }
    )


def main():
    create_bucket(BUCKET_NAME)


if __name__ == '__main__':
    main()

Create Bucket & Assign Bucket Policy:

Now lets add and combine the 2 blocks of code: Bucket creation + Assign Bucket Policy

run following Python code to create the bucket + Assign the bucket policy in a single run

Note: Here I have used Bucket policy for Public access

# Author: Jagat Pradhan
# Disclaimer : Use at your own risk. this is tested in LAB environment
# This script is to create a single bucket in a region and assign a bucket policy

import boto3
import json

# connect to AWS console
aws_console = boto3.session.Session(profile_name="boto3")
# connect to S3
s3_console = aws_console.client(service_name='s3', region_name='us-east-1')

# bucket name
BUCKET_NAME = 'jagat-test-bucket-2021'


def create_bucket(bucket_name):

    s3_console.create_bucket(
        Bucket=bucket_name

    )


def assign_bucket_policy():
    bucket_name = BUCKET_NAME
    bucket_policy = {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Sid": "AddPerm",
                "Effect": "Allow",
                "Principal": "*",
                "Action": ["s3:*"],
                "Resource": f'arn:aws:s3:::{bucket_name}/*'
            }
        ]
    }

    policy_string = json.dumps(bucket_policy)

    s3_console.put_bucket_policy(
        Bucket=BUCKET_NAME,
        Policy=policy_string
    )


def main():
    create_bucket(BUCKET_NAME)
    assign_bucket_policy()


if __name__ == '__main__':
    main()

Conclusion:

That’s it for today. Use the code and experiment as per your need.

Yo can also add user input to the code to take the bucket name while running the code. 🙂

Thank’s for reading. Please share if you liked it !!!