Can configuring a bucket to host a static website be automated, from bucket creation to uploading of files, using just boto3?
I managed to create scripts for these steps:
- Create a bucket
client = boto3.client('s3')
client.create_bucket(
Bucket=bucket_name,
CreateBucketConfiguration={
'LocationConstraint': self.client.meta.region_name
},
)
- Enable static website hosting
client.put_bucket_website(
Bucket=bucket_name,
WebsiteConfiguration={
'ErrorDocument': {'Key': 'error.html'},
'IndexDocument': {'Suffix': 'index.html'},
},
)
- Change permissions and bucket policy
bucket_policy = {
'Version': '2012-10-17',
'Statement': [
{
'Sid': 'PublicReadGetObject',
'Effect': 'Allow',
'Principal': '*',
'Action': 's3:GetObject',
'Resource': BUCKET_ARN,
}
],
}
bucket_policy = json.dumps(bucket_policy)
client.put_bucket_policy(Bucket=bucket_name, Policy=bucket_policy)
- Upload file
for subdir, dirs, files in os.walk(base_dir):
for file in files:
key = file
if subdir != base_dir:
rel_path = os.path.relpath(subdir, base_dir)
key = os.path.join(rel_path, file)
full_path = os.path.join(subdir, file)
mime_type = mimetypes.guess_type(full_path)[0]
if mime_type:
with open(full_path, 'rb') as data:
self.client.put_object(
Bucket=bucket_name,
Key=key,
Body=data,
ContentType=mime_type,
)
However the website is not hosted properly. For one, when typing the endpoint in the address bar, instead of displaying the page it downloads the content of index.html file. Did I miss any steps here? Are there other things to consider?
Already did this but still not working. I updated my question to include the source code.
If you do some debugging - what is the
mime_type
variable set to? Is it actuallytext/html
? You can also check the content type in the AWS Console by looking at the object metadata.