avatar

Niki Tech

ๅ—่จ—้–‹็™บใฎใปใ‹ใซใ‚‚ใ€็‹ฌ่‡ชใซ้–‹็™บใ—ใฆใ„ใ‚‹ใ‚ขใƒ—ใƒชใ‚‚ใ‚ใ‚Šใพใ™๐Ÿš€

๐Ÿ› Auto build Static website with React, S3, Cloudfont and Github

2024-06-04

This blog is deployed automatic by github commmit

Flow

  1. Push to GitHubใ€Github workflows will be auto run
  2. Github workflows is defined by.github/workflows/build-and-deploy.yaml
    1. React will make Build
    2. All files from Build will be uploaded to S3
    3. Clear cache Cloudfront
  3. New posts/updates will be reflect to static website

Setup

Create Github workflows file

Add .git/workflows/build-and-deploy.yaml

name: Build and Deploy on: push: branches: - main permissions: id-token: write contents: read jobs: build-and-deploy: name: Build and Deploy runs-on: ubuntu-latest env: S3_BUCKET_NAME: ${S3_BUCKET_NAME} CLOUDFRONT_DISTRIBUTION_ID: ${CLOUDFRONT_DISTRIBUTION_ID} NEXTJS_DIST: out AWS_REGION: us-east-1 steps: - name: Checkout code uses: actions/checkout@v2 - name: Configure AWS credentials from AWS account uses: aws-actions/configure-aws-credentials@v2 with: role-to-assume: arn:aws:iam::637423222151:role/github-to-aws aws-region: us-east-1 - name: Set up Node.js uses: actions/setup-node@v2 with: node-version: '14' - name: Install dependencies run: npm install - name: Build Static Site run: npm run build - name: Copy files to S3 run: aws s3 sync --delete out s3://${S3_BUCKET_NAME} - name: Copy files to production run: aws cloudfront create-invalidation --distribution-id ${CLOUDFRONT_DISTRIBUTION_ID} --paths '/*' - name: Deploy run: |

Setup in AWS with S3, Cloudfront and IAM

  1. Create S3-bucket: ${S3_BUCKET_NAME}
    1. Block-traffic disable
    2. Make static web hosting
    3. Make bucket-policy (S3-Object with resource to ${S3_BUCKET_NAME})
  2. Create Cloudfront Distribution
    1. make http -> https
    2. default root: index.html
  3. Create IAM
    1. Create Identity provider for OpenID https://token.actions.githubusercontent.com
    2. Create Policy s3-web-access-policy
    { "Version": "2012-10-17", "Statement": [ { "Sid": "ListObjectsInBucket", "Effect": "Allow", "Action": [ "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::${S3_BUCKET_NAME}" ] }, { "Sid": "InvalidateCF", "Effect": "Allow", "Action": [ "cloudfront:CreateInvalidation" ], "Resource": "*" }, { "Sid": "AllObjectsActions", "Effect": "Allow", "Action": "s3:*Object", "Resource": [ "arn:aws:s3:::${S3_BUCKET_NAME}/*" ] } ] }
    1. Create Role github-to-aws
    { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Federated": "arn:aws:iam::637423222151:oidc-provider/token.actions.githubusercontent.com" }, "Action": "sts:AssumeRoleWithWebIdentity", "Condition": { "StringEquals": { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" }, "StringLike": { "token.actions.githubusercontent.com:sub": "repo:bestapuri/nikitech.jp:*" } } } ] }