LoginSignup
0
0

S3で静的ウェブサイトをホスティングしてみた

Posted at

はじめに

S3のバケットにhtmlファイルをアップロードしブラウザからの表示をAWSマネジメントコンソールとTerraformの両方で試してみた。

1.S3の作成

1.下記表を参照し、S3を作成します。

項目
バケット名 任意のバケット名
AWS リージョン ap-northeast-1
パブリックアクセスをすべて ブロック ✓を外す
現在の設定により、このバケットとバケット内のオブジェクトが公開される可能性があることを承認します。

2.バケット > バケット名 > アクセス許可 > バケットポリシーを編集します。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "{$バケットARN}/*"
        }
    ]
}

3.index.htmlファイルを作成します。

<!doctype html>
<html lang="ja">
  <body>
    Hello world!
  </body>
</html>

4.バケット > バケット名 > オブジェクトからindex.htmlをアップロードします。
5.バケット > バケット名 > プロパティ > 静的ウェブサイトホスティングを下記表を参照し、編集します。

項目
静的ウェブサイトホスティング 有効にする
ホスティングタイプ  静的ウェブサイトをホストする 
 インデックスドキュメント   index.html 

6.変更の保存を選択します。
7.バケットウェブサイトエンドポイントのリンクを選択しHello world!が表示されることを確認します。
スクリーンショット 2023-08-08 0.04.56.png

2.Terraformで作成する場合

#S3
resource "aws_s3_bucket" "example" {
  #グローバルで一意のバケット名に変更
  bucket = "test-bucket"
}

#静的ウェブサイトホスティングの有効化
resource "aws_s3_bucket_website_configuration" "example" {
  bucket = aws_s3_bucket.example.id

  index_document {
    suffix = "index.html"
  }
}

#パブリックアクセスの有効化
resource "aws_s3_bucket_public_access_block" "example" {
  bucket = aws_s3_bucket.example.id

  block_public_acls       = false
  block_public_policy     = false
  ignore_public_acls      = false
  restrict_public_buckets = false
}

#バケットポリシー
data "aws_iam_policy_document" "example" {
  statement {
    sid       = "PublicReadGetObject"
    effect    = "Allow"
    actions   = ["s3:GetObject"]
    resources = ["${aws_s3_bucket.example.arn}/*"]

    principals {
      type        = "AWS"
      identifiers = ["*"]
    }
  }
}

#S3とバケットポリシーの紐付け
resource "aws_s3_bucket_policy" "example" {
  bucket = aws_s3_bucket.example.id
  policy = data.aws_iam_policy_document.example.json

  #パブリックアクセスの有効化を先に実行しないとエラーになる
  #https://zenn.dev/hige/articles/01b69444ccaa3d
  depends_on = [
    aws_s3_bucket_public_access_block.example
  ]
}

apply後にindex.htmlをアップロード、Hello world!が表示されることを確認します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0