本次cicd的流水线是解决python的flask自动部署到lambda,实现通过apigateway访问flask接口。
Gitlab CI/CD流水线搭建
git runner部署
参考文档:https://www.cnblogs.com/eastpig/p/12721130.html
本次git runner使用的是docker部署的,直接上命令
1.启动docker容器:
docker run -d --name tzq_gitlab_runner --restart always -v /srv/gitlab-runner/config:/etc/gitlab-runner -v /var/run/docker.sock:/var/run/docker.sock --net=host gitlab/gitlab-runner:latest
2.进入容器注册runner
docker exec -it tzq_gitlab_runner /bin/bash
gitlab-runner register
3.在gitlab上获取tocken
![](https://img.haomeiwen.com/i13692711/18e0bea7e5c46bbd.png)
![](https://img.haomeiwen.com/i13692711/9c1fcd6cd3ff1804.png)
4.给runner取个名字和tag和runner的执行者和一个默认镜像
![](https://img.haomeiwen.com/i13692711/9368bd66c6dc978f.png)
![](https://img.haomeiwen.com/i13692711/7580db908e5ee272.png)
![](https://img.haomeiwen.com/i13692711/012be1a8770d6843.png)
![](https://img.haomeiwen.com/i13692711/1f0320e717e9638b.png)
5.修改配置文件(可不操作)
打开/srv/gitlab-runner/config/config.toml文件,找到你对应的runner实例配置
找到并修改为:volumes = ["/cache","/var/run/docker.sock:/var/run/docker.sock"]
pull_policy = "if-not-present"
然后重启runner,
docker restart gitlab-runner
6.gitlab上修改runner配置
这一步主要是忽视runner tag的影响,不然会导致pipline流水线一直处于pengding状态
![](https://img.haomeiwen.com/i13692711/c372219aa3e0bef4.png)
![](https://img.haomeiwen.com/i13692711/b482f8bf76a9660d.png)
Lambda环境搭建
创建具有flask的lambda代码,创建过程略,附上需要注意的地方,第三方模块包使用的层来提供的
附上flask主函数代码(这里只是一个demo):注意引入了一个awsgi的包
import awsgi
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return {'msg': 'inde'}
@app.route('/hello', methods=['GET'])
def hello_get():
return {'msg': 'get method'}
@app.route('/hello', methods=['POST'])
def hello_post():
return {'msg': 'post method'}
def lambda_handler(event, context):
return awsgi.response(app, event, context)
![](https://img.haomeiwen.com/i13692711/f1f64f1ee25ca5b3.png)
ApiGateway部署
通过apigateway将lambda接口暴露出去
1.创建REST的apigateway
![](https://img.haomeiwen.com/i13692711/710f5c094bd756bf.png)
2.自定义api名称,创建api
![](https://img.haomeiwen.com/i13692711/974145e47370860a.png)
3.创建资源
![](https://img.haomeiwen.com/i13692711/d03f885438a77647.png)
4.配置为代理资源proxy模式,这种模式的好处,可以模糊匹配你flask里面的所有路由,就不需要再繁琐的一个一个在api里面加了
![](https://img.haomeiwen.com/i13692711/324d30e8d5db6108.png)
5.绑定后端的lambda函数
![](https://img.haomeiwen.com/i13692711/b76a20ca28110a1e.png)
6.部署api并给阶段命名
![](https://img.haomeiwen.com/i13692711/79ddf1f48100a615.png)
![](https://img.haomeiwen.com/i13692711/860e0f89ffbc633d.png)
![](https://img.haomeiwen.com/i13692711/05f38cd712c875af.png)
通过上面的URL后面加上你自己方法,就可以愉快的玩耍了
gitlab pipline
这次流水线编写的比较简单,只是简单实现了把代码部署到lambda上,后续会加上单元测试相关的类容
image: public.ecr.aws/sam/build-python3.8
stages:
- deploy
deploy_job:
stage: deploy
script:
- zip -r ./lambda.zip ./*
- aws lambda update-function-code --function-name query_db --zip-file fileb://lambda.zip
网友评论