S3完全ガイド
S3 (Simple Storage Service) 完全ガイド
Section titled “S3 (Simple Storage Service) 完全ガイド”S3は、オブジェクトストレージサービスです。実務で使える実装例とベストプラクティスを詳しく解説します。
1. S3とは
Section titled “1. S3とは”S3は、任意の量のデータを保存・取得できるオブジェクトストレージサービスです。
アプリケーション ↓(オブジェクトをアップロード)S3バケット ├─ オブジェクト1 ├─ オブジェクト2 └─ オブジェクト3なぜS3が必要か
Section titled “なぜS3が必要か”問題のある構成(ローカルストレージ):
# 問題: ローカルストレージの使用# 1. ディスク容量の制限# 2. バックアップの手動管理# 3. スケーリングが困難# 4. 可用性が低い(単一障害点)
# 問題点:# 1. 容量の制限# 2. バックアップの複雑さ# 3. スケーリングの困難さ# 4. 可用性の問題解決: S3によるオブジェクトストレージ
# 解決: S3へのアップロードaws s3 cp file.txt s3://my-bucket/file.txt
# メリット:# 1. 無制限の容量(実質的に)# 2. 自動バックアップ(99.999999999%の耐久性)# 3. 自動スケーリング# 4. 高い可用性(99.99%)2. S3の基本概念
Section titled “2. S3の基本概念”バケットは、オブジェクトを格納するコンテナです。リージョン内で一意の名前が必要です。
# バケットの作成aws s3 mb s3://my-bucket --region us-east-1
# バケットの一覧表示aws s3 ls
# バケットの削除aws s3 rb s3://my-bucketオブジェクト
Section titled “オブジェクト”オブジェクトは、ファイルとメタデータの組み合わせです。
# オブジェクトのアップロードaws s3 cp file.txt s3://my-bucket/file.txt
# オブジェクトのダウンロードaws s3 cp s3://my-bucket/file.txt file.txt
# オブジェクトの一覧表示aws s3 ls s3://my-bucket/
# オブジェクトの削除aws s3 rm s3://my-bucket/file.txtキーは、オブジェクトの一意の識別子です。パス形式で指定できます。
s3://my-bucket/ ├─ images/ │ ├─ photo1.jpg │ └─ photo2.jpg ├─ documents/ │ └─ report.pdf └─ data/ └─ dataset.csv3. S3ストレージクラス
Section titled “3. S3ストレージクラス”ストレージクラスの種類
Section titled “ストレージクラスの種類”Standard
Section titled “Standard”用途: 頻繁にアクセスするデータ特徴: 即座にアクセス可能、高い耐久性コスト: 最も高い例: アクティブなWebサイトのコンテンツStandard-IA(Infrequent Access)
Section titled “Standard-IA(Infrequent Access)”用途: アクセス頻度が低いデータ特徴: 即座にアクセス可能、Standardより安価コスト: Standardの約50%例: バックアップ、ログファイルIntelligent-Tiering
Section titled “Intelligent-Tiering”用途: アクセスパターンが不明なデータ特徴: 自動的に最適なストレージクラスに移動コスト: モニタリング料金が追加例: 新しいデータ、アクセスパターンが不明なデータGlacier Instant Retrieval
Section titled “Glacier Instant Retrieval”用途: アーカイブデータ(即座にアクセスが必要)特徴: 数ミリ秒でアクセス可能コスト: Standard-IAより安価例: 医療記録、財務記録Glacier Flexible Retrieval
Section titled “Glacier Flexible Retrieval”用途: アーカイブデータ(数分〜数時間でアクセス可能)特徴: 3つの取得オプション(Expedited、Standard、Bulk)コスト: Standardより大幅に安価例: バックアップ、長期アーカイブGlacier Deep Archive
Section titled “Glacier Deep Archive”用途: 長期アーカイブデータ(12時間でアクセス可能)特徴: 最も安価なストレージクラスコスト: Standardの約1/5例: コンプライアンス要件のあるデータ、長期アーカイブストレージクラスの選択
Section titled “ストレージクラスの選択”// 用途別の選択例const storageClassSelection = { 'アクティブなWebコンテンツ': 'STANDARD', 'バックアップ(30日以上)': 'STANDARD_IA', 'アクセスパターン不明': 'INTELLIGENT_TIERING', 'アーカイブ(即座にアクセス)': 'GLACIER_INSTANT_RETRIEVAL', 'アーカイブ(数時間でOK)': 'GLACIER_FLEXIBLE_RETRIEVAL', '長期アーカイブ(12時間でOK)': 'DEEP_ARCHIVE'};4. ライフサイクルポリシー
Section titled “4. ライフサイクルポリシー”ライフサイクルポリシーとは
Section titled “ライフサイクルポリシーとは”ライフサイクルポリシーは、オブジェクトを自動的に別のストレージクラスに移動したり、削除したりするルールです。
基本的な設定
Section titled “基本的な設定”{ "Rules": [ { "Id": "TransitionToIA", "Status": "Enabled", "Transitions": [ { "Days": 30, "StorageClass": "STANDARD_IA" } ] }, { "Id": "TransitionToGlacier", "Status": "Enabled", "Transitions": [ { "Days": 90, "StorageClass": "GLACIER" } ] }, { "Id": "DeleteOldVersions", "Status": "Enabled", "NoncurrentVersionExpiration": { "NoncurrentDays": 90 } }, { "Id": "DeleteIncompleteMultipartUpload", "Status": "Enabled", "AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 7 } } ]}Terraformでの設定
Section titled “Terraformでの設定”resource "aws_s3_bucket_lifecycle_configuration" "example" { bucket = aws_s3_bucket.example.id
rule { id = "TransitionToIA" status = "Enabled"
transition { days = 30 storage_class = "STANDARD_IA" } }
rule { id = "TransitionToGlacier" status = "Enabled"
transition { days = 90 storage_class = "GLACIER" } }
rule { id = "DeleteOldVersions" status = "Enabled"
noncurrent_version_expiration { noncurrent_days = 90 } }}5. バージョニング
Section titled “5. バージョニング”バージョニングとは
Section titled “バージョニングとは”バージョニングは、オブジェクトの複数のバージョンを保持する機能です。
バージョニングの有効化
Section titled “バージョニングの有効化”# バージョニングの有効化aws s3api put-bucket-versioning \ --bucket my-bucket \ --versioning-configuration Status=Enabled
# バージョンの一覧表示aws s3api list-object-versions \ --bucket my-bucket \ --prefix file.txt
# 特定のバージョンを取得aws s3api get-object \ --bucket my-bucket \ --key file.txt \ --version-id <version-id> \ file.txtMFA Delete
Section titled “MFA Delete”# MFA Deleteの有効化(バージョンの削除にMFAが必要)aws s3api put-bucket-versioning \ --bucket my-bucket \ --versioning-configuration \ Status=Enabled,MFADelete=Enabled \ --mfa "arn:aws:iam::123456789012:mfa/root-account-mfa-device 123456"6. S3のセキュリティ
Section titled “6. S3のセキュリティ”バケットポリシー
Section titled “バケットポリシー”{ "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*", "Condition": { "StringEquals": { "aws:Referer": "https://example.com/*" } } }, { "Sid": "AllowIAMUserAccess", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::123456789012:user/username" }, "Action": [ "s3:GetObject", "s3:PutObject", "s3:DeleteObject" ], "Resource": "arn:aws:s3:::my-bucket/*" } ]}{ "Rules": [ { "ApplyServerSideEncryptionByDefault": { "SSEAlgorithm": "AES256" } }, { "ApplyServerSideEncryptionByDefault": { "SSEAlgorithm": "aws:kms", "KMSMasterKeyID": "arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012" } } ]}CORS設定
Section titled “CORS設定”{ "CORSRules": [ { "AllowedOrigins": ["https://example.com"], "AllowedMethods": ["GET", "PUT", "POST", "DELETE"], "AllowedHeaders": ["*"], "ExposeHeaders": ["ETag"], "MaxAgeSeconds": 3000 } ]}7. 静的Webサイトホスティング
Section titled “7. 静的Webサイトホスティング”基本的な設定
Section titled “基本的な設定”# 静的Webサイトホスティングの有効化aws s3 website s3://my-bucket \ --index-document index.html \ --error-document error.html
# バケットポリシーの設定(公開読み取り)aws s3api put-bucket-policy --bucket my-bucket --policy '{ "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*" } ]}'CloudFrontとの統合
Section titled “CloudFrontとの統合”Resources: CloudFrontDistribution: Type: AWS::CloudFront::Distribution Properties: DistributionConfig: Origins: - DomainName: my-bucket.s3.amazonaws.com Id: S3-my-bucket S3OriginConfig: OriginAccessIdentity: !Sub 'origin-access-identity/cloudfront/${OAI}' DefaultCacheBehavior: TargetOriginId: S3-my-bucket ViewerProtocolPolicy: redirect-to-https AllowedMethods: - GET - HEAD CachedMethods: - GET - HEAD ForwardedValues: QueryString: false MinTTL: 0 DefaultTTL: 86400 MaxTTL: 315360008. 実務でのベストプラクティス
Section titled “8. 実務でのベストプラクティス”パターン1: コスト最適化
Section titled “パターン1: コスト最適化”{ "Rules": [ { "Id": "CostOptimization", "Status": "Enabled", "Transitions": [ { "Days": 0, "StorageClass": "INTELLIGENT_TIERING" } ], "Filter": { "Prefix": "data/" } } ]}パターン2: バックアップ戦略
Section titled “パターン2: バックアップ戦略”{ "Rules": [ { "Id": "BackupStrategy", "Status": "Enabled", "Transitions": [ { "Days": 1, "StorageClass": "STANDARD_IA" }, { "Days": 30, "StorageClass": "GLACIER" }, { "Days": 365, "StorageClass": "DEEP_ARCHIVE" } ] } ]}パターン3: ログファイルの管理
Section titled “パターン3: ログファイルの管理”{ "Rules": [ { "Id": "LogManagement", "Status": "Enabled", "Transitions": [ { "Days": 7, "StorageClass": "STANDARD_IA" }, { "Days": 30, "StorageClass": "GLACIER" } ], "Expiration": { "Days": 90 }, "Filter": { "Prefix": "logs/" } } ]}9. よくある問題と解決策
Section titled “9. よくある問題と解決策”問題1: コストが高い
Section titled “問題1: コストが高い”原因:
- 適切なストレージクラスを使用していない
- ライフサイクルポリシーが設定されていない
- 未使用のオブジェクトが残っている
解決策:
# ストレージクラスの確認aws s3api list-objects-v2 \ --bucket my-bucket \ --query 'Contents[].{Key:Key,StorageClass:StorageClass}'
# ライフサイクルポリシーの確認aws s3api get-bucket-lifecycle-configuration --bucket my-bucket
# 未使用のオブジェクトの検索aws s3api list-objects-v2 \ --bucket my-bucket \ --query 'Contents[?LastModified<`2024-01-01`]'問題2: アクセスが拒否される
Section titled “問題2: アクセスが拒否される”原因:
- バケットポリシーが正しく設定されていない
- IAMポリシーに権限がない
- 暗号化キーへのアクセス権限がない
解決策:
# バケットポリシーの確認aws s3api get-bucket-policy --bucket my-bucket
# IAMポリシーの確認aws iam get-user-policy --user-name username --policy-name S3Access
# 暗号化設定の確認aws s3api get-bucket-encryption --bucket my-bucketこれで、S3の基礎知識と実務での使い方を理解できるようになりました。