How To Setup S3 bucket with Python for Static Web Hosting in 2022

S3 is one of the world’s most popular storage solution providers with an option for static web hosting. This really makes S3 stand out from all other storage providers. In this article, I am going to show you how you can create an S3 bucket for static web hosting using Python along with the setup of a CloudFront distribution.

First, configure aws CLIlocally. To download AWS CLI to go the AWS official source here. Once the installation is done, then run this command to configure with your IAM user.

aws configure 

After configuring AWS CLI locally, create a python script name “create.py” with the code below.

import boto3

# Create an S3 client
s3 = boto3.client('s3')

# Set the name of the bucket that you want to create
bucket_name = 'my-static-web-hosting-bucket'

# Set the bucket's website configuration
website_configuration = {
    'ErrorDocument': {'Key': 'error.html'},
    'IndexDocument': {'Suffix': 'index.html'},
}

# Create the bucket
s3.create_bucket(Bucket=bucket_name,
                 CreateBucketConfiguration={'LocationConstraint': 'us-east-1'})

# Enable static website hosting for the bucket
s3.put_bucket_website(Bucket=bucket_name,
                      WebsiteConfiguration=website_configuration)

print(f'Bucket {bucket_name} has been created and configured for static web hosting.')

This script first imports the boto3 library, which is the AWS SDK for Python. It then creates an S3 client, which you can use to call various S3 operations.

Next, the script sets the name of the bucket that you want to create. You can replace my-static-web-hosting-bucket with your own desired bucket name.

The script then sets the bucket’s website configuration. This configuration specifies the file that will be served when an error occurs (error.html) and the file that will be served when a user visits the root of the website (index.html).

Finally, the script creates the bucket using the create_bucket method and enables static website hosting for the bucket using the put_bucket_website method.

After running this script, you should have an S3 bucket that is configured for static web hosting. You can then upload your HTML, CSS, JavaScript, and other static assets to the bucket, and access your website by visiting the bucket’s website endpoint.

Create the CloudFront Distribution

Here is a Python script that creates an Amazon CloudFront distribution with the S3 bucket that you created previously and sets index.html as the default Root object.

import boto3

# Create an S3 client
s3 = boto3.client('s3')

# Set the name of the bucket that you want to use as the source for your CloudFront distribution
bucket_name = 'my-static-web-hosting-bucket'

# Set the name of the CloudFront distribution
distribution_name = 'my-cloudfront-distribution'

# Set the bucket's website endpoint as the origin for the CloudFront distribution
origin = {
    'Id': bucket_name,
    'DomainName': s3.get_bucket_website(Bucket=bucket_name)['WebsiteConfiguration']['Endpoint'],
    'S3OriginConfig': {
        'OriginAccessIdentity': ''
    }
}

# Create the CloudFront distribution
cloudfront = boto3.client('cloudfront')
response = cloudfront.create_distribution(
    DistributionConfig={
        'CallerReference': bucket_name,
        'Origins': [origin],
        'DefaultCacheBehavior': {
            'TargetOriginId': bucket_name,
            'ViewerProtocolPolicy': 'redirect-to-https',
            'TrustedSigners': [],
            'ForwardedValues': {
                'Cookies': {'Forward': 'all'},
                'QueryString': False
            },
            'MinTTL': 0,
            'AllowedMethods': ['GET', 'HEAD'],
            'DefaultTTL': 86400,
            'MaxTTL': 31536000
        },
        'Aliases': [],
        'Comment': '',
        'Enabled': True,
        'DefaultRootObject': 'index.html'
    }
)

# Get the domain name of the CloudFront distribution
distribution_domain_name = response['Distribution']['DomainName']

print(f'CloudFront distribution {distribution_name} has been created with {bucket_name} as the source.')
print(f'You can access your website at https://{distribution_domain_name}.')

You can replace my-static-web-hosting-bucket with the name of your own S3 bucket.

The script then sets the name of the CloudFront distribution (“my-cloudfront-distribution“) and creates an origin object that specifies the bucket’s website endpoint as the origin for the CloudFront distribution.

Finally, the script creates the CloudFront distribution using the create_distribution method and prints the domain name of the distribution, which you can use to access your website.

After running this script, you should have a CloudFront distribution that is configured to serve your static content from the specified S3 bucket. You can then access your website by visiting the CloudFront distribution’s domain name.

Leave a Comment

Your email address will not be published. Required fields are marked *