Automation of static website hosting in S3 using boto3

0

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:

  1. Create a bucket
client = boto3.client('s3')
client.create_bucket(
            Bucket=bucket_name,
            CreateBucketConfiguration={
                'LocationConstraint': self.client.meta.region_name
            },
        )
  1. Enable static website hosting
client.put_bucket_website(
            Bucket=bucket_name,
            WebsiteConfiguration={
                'ErrorDocument': {'Key': 'error.html'},
                'IndexDocument': {'Suffix': 'index.html'},
            },
        )
  1. 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)
  1. 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?

Vince
질문됨 9달 전324회 조회
2개 답변
1

You're almost there! What you're not doing is setting the content type when uploading the file to S3. The AWS CLI does this for you automatically (and silently) but you need to set it when using boto3. Luckily that's really easy:

s3 = boto3.client('s3')

s3.put_object(Bucket='bucketNameHere', Key='index.html', Body=bodyOfFileGoesHere, ContentType='text/html')
profile pictureAWS
전문가
답변함 9달 전
profile pictureAWS
전문가
검토됨 9달 전
profile picture
전문가
Steve_M
검토됨 9달 전
  • 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 actually text/html? You can also check the content type in the AWS Console by looking at the object metadata.

1

Hi,

You have got an issue with your bucket policy,

'Action': 's3:GetObject',
'Resource': f'{BUCKET_ARN}/*'

With Action with *Object, you must add /* meaning all objects.

profile picture
Donov
답변함 9달 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠