あめがえるのITブログ

頑張りすぎない。ほどほどに頑張るブログ。

Amazon S3の静的Webホスティングを使ってみた



S3の静的Webホスティングを使う機会があったので検証してみた。

S3 静的Webホスティングとは
S3にHTMLファイルをアップロードし、パブリックアクセスを許可した状態でブラウザからHTMLファイルにアクセスさせればWebサイトとして動作させることが 可能。

S3 静的WebホスティングとWebサーバを比較した場合のメリット
・Webサーバーをセットアップする必要がない
・ファイルのアップロード、変更でデプロイが可能のため準備が容易

S3 静的WebホスティングとS3直接参照を比較した場合のメリット
トラフィックが増大しても高いスケーラビリティによってコンテンツ配信の問題が生じにくい

S3 静的Webサイトホスティングのデメリット
・動的コンテンツの利用ができないのでLambdaなどと組み合わせる必要がある
・独自のSSL/TLS証明書が利用できないのでCloudFrontなどの別サービスを組み合わせる必要がある。


やること

terraformでS3の静的Webホスティングサイトを作成し、アクセスしてページの表示状況を確認する。

構成

外部ブラウザ ⇒ S3(静的Webホスティング)

実践!

1.HTMLファイル作成
1-1.表示用、エラー用のHTMLファイル作成

# vi index.html
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome to My Static Site</title>
</head>
<body>
    <h1>Welcome to My Static Site</h1>
    <p>This is the main page.</p>
</body>
</html>
# vi error.html
<!-- error.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Error Page</title>
</head>
<body>
    <h1>Oops! Something went wrong.</h1>
    <p>We couldn't find the page you were looking for.</p>
</body>
</html>


2.環境作成
2-1.下記を実行

# vi main.tf
provider "aws" {
  region = "ap-northeast-1"
}

resource "aws_s3_bucket" "static_website" {
  bucket = "staticwebhosting12345689" # ユニークなものに変更
  force_destroy = true

  website {
    index_document = "index.html"
    error_document = "error.html"
  }
}

resource "aws_s3_bucket_policy" "bucket_policy" {
  bucket = aws_s3_bucket.static_website.bucket

  policy = jsonencode({
    Version = "2012-10-17",
    Statement = [
      {
        Effect = "Allow",
        Principal = "*",
        Action = ["s3:GetObject"],
        Resource = [
          "${aws_s3_bucket.static_website.arn}/*"
        ]
      },
    ]
  })
}

resource "aws_s3_bucket_object" "index_html" {
  bucket = aws_s3_bucket.static_website.id
  key    = "index.html"
  source = "index.html"
  content_type = "text/html"
}

resource "aws_s3_bucket_object" "error_html" {
  bucket = aws_s3_bucket.static_website.id
  key    = "error.html"
  source = "error.html"
  content_type = "text/html"
}

2-2.terraform実行

# terraform plan
# terraform apply


3.動作確認
3-1.[S3] - [バケット] - 作成したバケットを選択

3-2.[プロパティ]タブを選択

3-3.[静的ウェブサイトホスティング]からURLをクリックし、ページが表示されることを確認


3-4.静的ウェブサイトホスティングのURLに適当な文字をいれ、エラーページが表示されることを確認
例)http://staticwebhosting12345689.s3-website-ap-northeast-1.amazonaws.com/testtest



感想

勉強しなくてもいい人生を送りたい