๐ Auto build Static website with React, S3, Cloudfont and Github
2024-06-04
This blog is deployed automatic by github commmit
Flow
- Push to
GitHub
ใGithub workflows
will be auto run Github workflows
is defined by.github/workflows/build-and-deploy.yaml
React
will makeBuild
- All files from
Build
will be uploaded toS3
- Clear cache
Cloudfront
- 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
- Create
S3-bucket
: ${S3_BUCKET_NAME}- Block-traffic disable
- Make static web hosting
- Make bucket-policy (S3-Object with resource to ${S3_BUCKET_NAME})
- Create
Cloudfront Distribution
- make http -> https
- default root: index.html
- Create
IAM
- Create Identity provider for OpenID https://token.actions.githubusercontent.com
- 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}/*" ] } ] }
- 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:*" } } } ] }