在进行开发的时候,CI/CD的好处就不必多说了。下面就介绍一下如何使用AWS Code Build自动部署React应用到AWS S3。

AWS Code Build教程
创建相应的AWS资源
创建S3 bucket
创建bucket
创建一个名字为“lcoding-react-s3-demo”的bucket,同时注意
- 取消”Block all public access”复选框。
- Versioning:Enable
- Server-side encryption: Enable
单击“Create Bucket”后创建S3 bucket。
激活bucket作为静态网站主机
然后进入这个bucket,并:
- 在Properties中,Enable “Static website hosting”,并将index document和Error document都设置为index.html(如果创建了404.html,则设为该文件)。
设定访问权限
选择Permissions => Bucket Policy并增加如下的Policy:
json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::lcoding-react-s3-demo/*"
}
]
}
创建React应用
创建React APP
使用如下命令创建一个React应用程序:
bash
npx create-react-app codebuild-demo
定义Code Build将要使用的部署流程
接下来添加文件buildspec.yml:
yaml
version: 0.2
phases:
install:
runtime-versions:
nodejs: 14
commands:
- echo "Installing dependencies..."
- npm install
build:
commands:
- echo "Building React APP..."
- npm run-script build
post_build:
commands:
- echo "Syncing files to S3 bucket..."
- aws s3 sync build/ s3://lcoding-react-s3-demo
设置Code Build
创建Build project
进入AWS Code Build并创建一个Build Project
- Project name: React to S3 CD demo
- Source provider: Github (并通过OAuth授权)
- 选择对应的Repo
- 选择master branch
- 勾选这项:Additional configuration => Primary source webhook events => Rebuild every time a code change is pushed to this repository
- Event type选择”PUSH”
- Operating system选择Ubuntu
- Runtime: Standard
- Image: aws/codebuild/standard:5.0
- Image version: Always use the latest image for this runtime version
- Environment type: Linux
- Logs => Cloudwatch => Group name: codebuild
- Stream name: react-s3-demo
- 其余的都选择默认值
单击“Create build project”
允许Code Build访问S3 bucket
打开Build details => Environment => Service role,添加如下对S3的访问权限:
json
{
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObjectAcl",
"s3:GetObject",
"s3:DeleteObjectVersion",
"s3:GetObjectVersionAcl",
"s3:ListBucket",
"s3:PutObjectAcl",
"s3:GetObjectVersion"
],
"Resource": [
"arn:aws:s3:::lcoding-react-s3-demo/*",
"arn:aws:s3:::lcoding-react-s3-demo"
]
}
最终的权限设置如下:

AWS Code Build教程
这时,任何新提交到GH Repo的代码都会触发Code Build自动构建并发布React APP到S3 bucket上。