gitlab ci配合rancher2实现自动重新部署

之前都是通过gitlab ci去构建项目,生成镜像上传到docker仓库,然后手动去重新部署rancher上的项目。最近研究了下通过调用rancher的api来自动重新部署。
rancher2和1.6又很大区别,没有官方的api来实现,所以我谷歌了很久,基本现在有2种实现实现方法:
1.通过diemscott/rancher-cli-k8s:v2.0.2镜像,使用kubectl来实现更新

RANCHER_SERVER_URL=https://rancher.example.com
RANCHER_API_TOKEN="token-sd5kk:d27nrsstx6z5blxgkmspqv94tzkptnrpj7rkcrt7vtxt28tvw4djxp"

deploy:
  stage: deploy
  image: diemscott/rancher-cli-k8s:v2.0.2
  script:
    - rancher login "$RANCHER_SERVER_URL" -t "$RANCHER_API_TOKEN"
    - rancher kubectl --namespace=default patch deployment nginx --type=strategic -p '{"spec":{"template":{"spec":{"containers":[{"name":"nginx","image": "nginx","env":[{"name":"FORCE_RESTART_AT","value":"$CI_PIPELINE_ID"}]}]}}}}'

但由于我们的rancher没有证书,导致这种方式跑不通,所以采用了第二种方式
2.采用和rancher客户端一样的接口,来实现自动部署,脚本如下

#!/bin/bash

programName=$1
workspace=$2
namespace=$3

function update()
{
    url='https://192.168.6.238:10443/v3/project/'${workspace}'/workloads/deployment:'${namespace}':'${programName}''
    #curl 请求
    pod_upgrade_body=$(curl -s "$url" -X GET -u "token" -H 'Accept-Encoding: gzip, deflate, br' -H 'Connection: keep-alive' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' -H 'content-type: application/json' -H 'accept: application/json'  --insecure 2>&1 | sed  "s/\"cattle\.io\/timestamp\"\:\"[0-9T:Z-]*\"/\"cattle\.io\/timestamp\":\"$(date -u +"%Y-%m-%dT%H:%M:%SZ")\"/g")

    echo "$pod_upgrade_body"
    curl 'https://192.168.6.238:10443/v3/project/'${workspace}'/workloads/deployment:'${namespace}':'${programName}'' -X PUT -u"token"  -H 'Accept-Encoding: gzip, deflate, br' -H 'Connection: keep-alive' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' -H 'content-type: application/json' -H 'accept: application/json' --data-binary "$pod_upgrade_body" --compressed --insecure
}



update

3.使用我上传到dockerhub上的镜像:
具体说明可以去dockerhub上自行查看

deploy:
  stage: deploy
  image: lwydyby/rancher-gitlab-deploy:latest
  script:
    - bash  /data/update.sh ${PROJECT_NAME} ${RANCHER_WORKSPACE} ${RANCHER_NAMESPACE} ${RANCHER_IP} ${RANCHER_TOKEN}

你可能感兴趣的:(平时遇到的问题)