🌊

44.S3をCloudFrontで配信したい時

2025/02/22に公開

S3

# 環境変数
PROFILE=
BUCKET_NAME=

# 作る
aws s3 mb s3://${BUCKET_NAME} \
--profile ${PROFILE}

# 確認する
aws s3 ls \
--profile ${PROFILE}

# 上げる
aws s3 sync . s3://${BUCKET_NAME} \
--profile ${PROFILE}

# 消す
aws s3 rb s3://${BUCKET_NAME} --force \
--profile ${PROFILE}

CloudFront

# 環境変数
AWS_ACCOUNT_ID=

# ①distributionの作成
aws cloudfront create-distribution \
--origin-domain-name ${BUCKET_NAME}.s3.amazonaws.com \
--default-root-object index.html \
--profile ${PROFILE}

# 環境変数
DISTRIBUTION_ID=

# ②バケットポリシー設定
aws s3api put-bucket-policy \
--bucket ${BUCKET_NAME} \
--policy "{
  \"Version\":\"2012-10-17\",
  \"Statement\": [
    {
      \"Effect\": \"Allow\",
      \"Principal\": {
        \"Service\": \"cloudfront.amazonaws.com\"
      },
      \"Action\": \"s3:GetObject\",
      \"Resource\": \"arn:aws:s3:::${BUCKET_NAME}/*\",
      \"Condition\": {
        \"StringEquals\": {
          \"AWS:SourceArn\": \"arn:aws:cloudfront::${AWS_ACCOUNT_ID}:distribution/${DISTRIBUTION_ID}\"
        }
      }
    }
  ]
}" \
--profile ${PROFILE}

# ③OACの作成
aws cloudfront create-origin-access-control \
--origin-access-control-config '{
    "Name": "MyOAC",
    "Description": "My Origin Access Control",
    "SigningProtocol": "sigv4",
    "SigningBehavior": "always",
    "OriginAccessControlOriginType": "s3"
}' \
--profile ${PROFILE}

# 環境変数
OAC_ID=

# ④distributionにOAC追加
## dist-configファイルの吐き出し
aws cloudfront get-distribution-config \
--id ${DISTRIBUTION_ID} \
--output yaml \
--profile ${PROFILE} \
> dist-config.yaml

## 編集
- OriginAccessControlId: ${OAC_ID} を設定
- ETagをIfMatchに変更

# ⑤distributionにOAC適応
aws cloudfront update-distribution \
--id ${DISTRIBUTION_ID} \
--cli-input-yaml file://dist-config.yaml \
--profile ${PROFILE}

---
# 削除
## distribution
### 無効化
マネコンでボタンポチが早い

### 削除
そのままマネコンでボタンポチが早い

## オリジンコントローう
そのままマネコンでボタンポチが早い

https://docs.aws.amazon.com/ja_jp/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html

メモ

  • CloudFront 使わずに静的ウェブサイトホスティング
# ブロックパブリックアクセス
aws s3api put-public-access-block \
--bucket ${BUCKET_NAME} \
--public-access-block-configuration "BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false" \
--profile ${PROFILE}

# バケットポリシー
aws s3api put-bucket-policy \
--bucket ${BUCKET_NAME} \
--policy '{"Version":"2012-10-17","Statement":[{"Sid":"PublicReadGetObject","Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::${BUCKET_NAME}/*"}]}' \
--profile ${PROFILE}

# 静的ウェブサイトホスティング
aws s3api put-bucket-website \
--bucket ${BUCKET_NAME} \
--website-configuration '{"IndexDocument": {"Suffix": "index.html"}}' \
--profile ${PROFILE}

# サイトURL(確認できず)
aws s3api get-bucket-website --bucket ${BUCKET_NAME} \
--profile ${PROFILE}

Discussion