本节我们将使用AWS Code系列的服务创建Dogs Service的CICD Pipeline,使用CodeCommit托管服务的代码,使用CodeBuid来构建镜像,使用CodePipeline来编排并部署到ECS上
先创建一个CodeCommit仓库:
aws codecommit create-repository --repository-name Dogs --repository-description "My Dogs repository" --region us-west-2
将仓库clone到本地:
cd ~/environment
git clone codecommit://Dogs
业务的代码直接从之前的目录拷贝:
cd Dogs
cp ~/environment/ecsworkshop/dogs/* ./
将业务代码push到CodeCommit:
git add .
git commit -m "initial commit"
git push
在CodeCommit的页面能看到新上传的代码:
CodeBuild使用buildspec.yml
来进行项目的构建,在当前目录创建该文件,将以下内容放进去,更新
version: 0.2
phases:
pre_build:
commands:
- echo Logging in to Amazon ECR...
- export AWS_REGION="<YOUR REGION>"
- export AWS_ACCOUNT_ID="<YOUR ACCOUNT ID>"
- export IMAGE_REPO_NAME="Dogs"
- aws --version
- aws ecr get-login-password --region ${AWS_REGION} | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com
- export REPOSITORY_URI=$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$IMAGE_REPO_NAME
- export COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
- export IMAGE_TAG=${COMMIT_HASH:=latest}
build:
commands:
- echo Build started on `date`
- echo Building the Docker image...
- docker build -t $REPOSITORY_URI:latest .
- docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG
post_build:
commands:
- echo Build completed on `date`
- echo Pushing the Docker images...
- docker push $REPOSITORY_URI:latest
- docker push $REPOSITORY_URI:$IMAGE_TAG
- echo Writing image definitions file...
- printf '[{"name":"dogs","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json
artifacts:
files: imagedefinitions.json
在CodePipeline的页面,创建一个新的Pipeline:
命名为dogs-cicd
:
添加source,使用上一节的CodeCommit地址:
添加Build Stage,使用CodeBuild,并点击Create project
先创建一个CodeBuild的项目:
项目命名为dogs-build
, 操作系统选择linux相关,注意钩上Priviledged
:
最后点击Continue to CodePipeline
,这样会自动创建好CodeBuild项目:
创建好CodeBuild项目后,进入下一步:
Deploy的阶段,provider选择ECS,并选择对应的集群及服务:
全部配置好后,点击创建。CodePipeline就创建完成了。
上一步我们自动创建了一个CodeBuild的Role,这个Role本身没有访问ECR的权限,需要先手动添加下,因为后面CodeBuild需要将构建好的项目镜像上传到ECR中。
这里直接添加ECR FullAccess:
回到本地项目,更新index.html
的<h1>
,加入Version 2
字样:
将新版本的代码上传到CodeCommit:
git add .
git commit -m "add buildspec and dogs-version2"
git push
上传完成后,在CodePipeline中会自动触发流水线:
在Build过程中,CodeBuild执行了buildspec.yml
中的命令进行镜像的构建:
构建完成后,进入第三阶段Deploy
,此时在ECS中创建一个新的Deployment
:
创建完成后,将原来的Deployment下线掉:
访问ELB页面,新版本的页面已经生效: