Yuta NakataのBlog

Python / AWS / ITについて役立つ情報を発信します

【コピペでOK】CloudFormationを用いて、S3 × CloudFrontで静的ページを公開する

はじめに

この記事では、CloudFormationを用いてS3とCloudFrontにリソースをデプロイし、静的ページを公開する手順を紹介します。

また、初学者やAWS詳しくない方向けにStepByStepで、コピペで行けるように紹介します。

前提

  • aws cliのインストールができていること

aws cliのインストールが済んでいることを前提とします。 インストールができていない場合は、下記からインストールをしてください。

https://docs.aws.amazon.com/ja_jp/cli/latest/userguide/getting-started-install.html

  • ~/.aws/configの設定が完了していること

~/.aws/configにファイルがあること。なければ、

[default]
region = ap-northeast-1

を転記しておきましょう。

デプロイ手順

1. 公開用CloudFrontをデプロイする

下記の内容を、template.yamlとして保存します。

AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31

Resources:
  CloudFrontDistribution:
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        Enabled: true
        HttpVersion: http2
        PriceClass: PriceClass_All
        DefaultRootObject: index.html
        Origins:
          - Id: hosting-s3
            DomainName: hosting-bucket-ane1.s3.ap-northeast-1.amazonaws.com
            S3OriginConfig:
              OriginAccessIdentity: ""
            OriginAccessControlId: !GetAtt OAC.Id
        DefaultCacheBehavior:
          TargetOriginId: hosting-s3
          AllowedMethods:
            - GET
            - HEAD
            - OPTIONS
          CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad
          OriginRequestPolicyId: 88a5eaf4-2fd4-4709-b370-b4c650ea3fcf
          ViewerProtocolPolicy: redirect-to-https
          
  OAC:
    Type: AWS::CloudFront::OriginAccessControl
    Properties:
      OriginAccessControlConfig:
        Name: hosintg-OAC
        OriginAccessControlOriginType: s3
        SigningBehavior: always
        SigningProtocol: sigv4

Outputs:
  CloudFrontDistributionId:
    Value: !Ref CloudFrontDistribution
    Export:
      Name: hosting-CloudFrontDistributionId

次のコマンドでデプロイします。

sam deploy --template-file template.yaml --capabilities CAPABILITY_NAMED_IAM --stack-name hosting-cloudfront --region ap-northeast-1 --profile default

2. 静的リソース用S3をデプロイする

下記の内容を、template.yamlとして保存します。

AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31

Resources:
  Bucket:
    Type: AWS::S3::Bucket
    Properties:
      LifecycleConfiguration:
        Rules:
          - Id: hosting-bucket-delete-multipart
            Status: Enabled
            AbortIncompleteMultipartUpload:
              DaysAfterInitiation: 1
      CorsConfiguration:
        CorsRules:
          - AllowedOrigins:
              - "*"
            AllowedHeaders:
              - "*"
            AllowedMethods:
              - GET
              - HEAD

  BucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref Bucket
      PolicyDocument:
        Statement:
          - Effect: Allow
            Action: s3:GetObject
            Resource: !Sub
              - ${Bucket}/*
              - Bucket: !GetAtt Bucket.Arn
            Principal:
              Service: cloudfront.amazonaws.com
            Condition:
              StringEquals:
                aws:SourceArn: !Join
                  - ""
                  - - !Sub "arn:aws:cloudfront::${AWS::AccountId}:distribution/"
                    - {'Fn::ImportValue': hosting-CloudFrontDistributionId}

次のコマンドでデプロイします。

sam deploy --template-file template.yaml --capabilities CAPABILITY_NAMED_IAM --stack-name hosting-bucket --region ap-northeast-1 --profile default

3. index.htmlをS3に転送する

下記の内容を、index.htmlとして保存します。

<html>
    <body>
        <h1>Hello World</h1>
    </body>
</html>

このindex.htmlをS3に転送します。

aws s3 cp index.html s3://my-hosting-bucket-ane1/

4. cloudfrontのURLにアクセスします

無事にindex.htmlが表示されました🙌