AWSのマネージドサービスを組み合わせ、
CloudFormationのみでサーバレスWebアプリ基盤を構築する構成例を紹介します。
本記事では「とりあえず動く」ではなく、
- なぜこの構成なのか
- CloudFormationで組む意味
- 実運用での拡張ポイント
を意識して解説します。
🎯 目的
この構成で達成したいことは以下です。
- インフラ構成のコード化(IaC)
- 環境差異の排除(dev / stg / prod)
- 再現性・引き継ぎ耐性の向上
CloudFormationを使うことで、
誰が・いつ構築しても同じインフラを作れる状態を目指します。
🏗 全体構成
CloudFront
↓
S3(Frontend / SPA配信)
API Gateway → Lambda → DynamoDB
認証:Cognito User Pool
🔧 各サービスの役割
-
S3
フロントエンド(SPA)の静的ホスティング -
CloudFront
CDN + HTTPS終端 -
API Gateway
API公開・認証連携 -
Cognito
ユーザー認証(JWT発行) -
Lambda
バックエンド処理 -
DynamoDB
サーバレスなデータストア
フルマネージド構成のため、
EC2・AutoScaling・パッチ管理は一切不要です。
📄 CloudFormationテンプレート(最小構成)
以下は全体像を把握するためのシンプルな例です。
AWSTemplateFormatVersion: '2010-09-09'
Description: Serverless Web App Infrastructure
Resources:
AppBucket:
Type: AWS::S3::Bucket
UserPool:
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: sample-user-pool
AutoVerifiedAttributes:
- email
UserPoolClient:
Type: AWS::Cognito::UserPoolClient
Properties:
UserPoolId: !Ref UserPool
GenerateSecret: false
AppTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
LambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
AppFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: nodejs18.x
Handler: index.handler
Role: !GetAtt LambdaRole.Arn
Code:
ZipFile: |
exports.handler = async () => {
return {
statusCode: 200,
body: "ok"
};
};
Api:
Type: AWS::ApiGateway::RestApi
Properties:
Name: sample-api
CloudFrontDist:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Enabled: true
DefaultCacheBehavior:
TargetOriginId: s3origin
ViewerProtocolPolicy: redirect-to-https
Origins:
- Id: s3origin
DomainName: !GetAtt AppBucket.DomainName
S3OriginConfig: {}
⚠️ 実運用で必ず追加する要素
1. API Gateway と Lambda の統合
以下のリソースが必要です。
- AWS::ApiGateway::Resource
- AWS::ApiGateway::Method
- AWS::Lambda::Permission
これがないと
「APIは存在するが実行できない」状態になります。
2. Cognito Authorizer
- API Gateway に Cognito Authorizer を設定
- JWT検証を API Gateway 側で実施
Lambdaに認証ロジックを書かずに済むのが最大の利点です。
3. IAM最小権限設計
ManagedPolicyだけに頼らず、
DynamoDBアクセスなどはインラインポリシーで明示します。
4. CloudFront + OAC
- S3の直接公開を禁止
- CloudFront経由のみアクセス許可
セキュリティレビューではほぼ必須です。
🚀 デプロイ方法
aws cloudformation deploy \
--template-file template.yaml \
--stack-name sample-stack \
--capabilities CAPABILITY_NAMED_IAM
💡 CloudFormationを使う理由(現場視点)
- AWS標準IaCでガバナンスが強い
- 監査・引き継ぎ・レビューに強い
- 長期運用・大規模システム向き
TerraformやCDKと比べると柔軟性は劣りますが、
企業システムでは今も第一候補になるケースが多いです。
🏁 まとめ
この構成は、
- フロント:S3 + CloudFront
- 認証:Cognito
- API:API Gateway + Lambda
- データ:DynamoDB
という AWSサーバレスの王道パターンです。
CloudFormationを使うことで、
- 再現性が高い
- 属人化しない
- 長期運用に耐える
インフラを構築できます。