LoginSignup
0
0

AWS copilotでNextJSの静的ホスティングを自動化する

Last updated at Posted at 2024-05-11

初めに

SSGで良いサービスならAWS copilotでStatic SiteにすればECSとかに比べればかなりお得だし、github actionsとか作らなくて良いからめっちゃ楽じゃんって思ったけど、いまいち情報が少なかったのでまとめました

AWS Copilotについて

NextJSの設定

next.config.mjs以下のようにoutput: 'export'を追加してbuild時にHTMLが出力されるようにします

/** @type {import('next').NextConfig} */
const nextConfig = {
    output: 'export',
};

export default nextConfig;

npm run build等、ビルドコマンドを実行してoutディレクトリにHTMLが出力されているのを確認しておきます

AWS copilotの設定と手動デプロイ

copilot initStatic Siteを選択します
スクリーンショット 2024-05-11 18.00.23.png

  • Which directories or files would you like to upload for サービス名と聞かれるのでHTMLが吐き出されているoutディレクトリでスペースを押します(returnだと何も選ばれず次に行ってしまうので注意)
  • Would you like to deploy an environment?と聞かれるのでyを選び、environmentを作成もしくは選択してデプロイします
  • デプロイが成功するとRecommended follow-up action:にURLが記載されているのでアクセスして、ページが観れていれば成功
  • これ以降はcopilot deployで手動デプロイできます

copilotディレクトリにmanifest.ymlが作成されますが、一応こんな感じ

# The manifest for the "frontend" service.
# Read the full specification for the "Static Site" type at:
# https://aws.github.io/copilot-cli/docs/manifest/static-site/

# Your service name will be used in naming your resources like S3 buckets, etc.
name: サービス名
type: Static Site
files:
  - source: frontend/out # 自分の環境に合ったディレクトリにしてください
    recursive: true

# You can override any of the values defined above by environment.
# environments:
#   test:
#     files:
#       - source: './blob'
#         recursive: true
#         destination: 'assets'
#         exclude: '*'
#         reinclude:
#           - '*.txt'
#           - '*.png'

自動化する

とりあえずデプロイできるようになったので、これをCodePipelineで自動化していきます

  • copilot pipeline initを実行します
  • What type of continuous delivery pipeline is this?と聞かれるのでWorkloadsを選択します
  • Which environment would you like to add to your pipeline?で上記で作成もしくは選択したenvironmentをここでも選択します
  • copilot/pipelines/pipeline名/buildspec.ymlに以下のようにinstallcommandsに追記します。これによってnpm run buildが実行されて、outにHTMLが出力されるようにします
# Buildspec runs in the build stage of your pipeline.
version: 0.2
phases:
  install:
    runtime-versions:
      nodejs: 18
    commands:
      - echo "cd into $CODEBUILD_SRC_DIR"
      - cd $CODEBUILD_SRC_DIR
      # Download the copilot linux binary.
      - wget -q https://ecs-cli-v2-release.s3.amazonaws.com/copilot-linux-v1.33.3 -O copilot-linux
      - chmod +x ./copilot-linux
  build:
    commands:
      # コマンドは環境に合わせてください
      - cd frontend
      - npm ci
      - npm run build
      - cd ..
# 以下省略
  • copilot pipeline deployを実行します
  • ACTION REQUIRED!と表示されるのでURLをクリックしてgithubと連携します
    スクリーンショット 2024-05-11 18.32.55.png

これで設定完了です
copilot/pipelines/pipeline名/manifest.ymlsource.properties.branchに記載されているブランチにpushするとCodePipelineが実行されてデプロイが行われます

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