packagemainimport("log""net/http""os""strings")varversion="master"funcshowVersion(whttp.ResponseWriter,r*http.Request){log.Println(version)w.Write([]byte(version))}funcsayHello(whttp.ResponseWriter,r*http.Request){message:=r.URL.Pathmessage=strings.TrimPrefix(message,"/")message="Hello, drone got the message: "+messagelog.Println(message)w.Write([]byte(message))}funcmain(){// use PORT environment variable, or default to 8080port:="8080"iffromEnv:=os.Getenv("PORT");fromEnv!=""{port=fromEnv}http.HandleFunc("/version",showVersion)http.HandleFunc("/",sayHello)log.Println("Listen server on "+port+" port")iferr:=http.ListenAndServe(":"+port,nil);err!=nil{log.Fatal(err)}}
從上面程式可以看到,在編譯 Go 語言專案時,可以從外部帶入 version 變數,證明目前的 App 版本。請參考 Makefile 內的
pipeline:build_linux_amd64:image:golang:1.10group:buildenvironment:- GOOS=linux- GOARCH=amd64- CGO_ENABLED=0commands:- cd example19-deploy-with-kubernetes && make build
docker_golang:image:plugins/docker:17.12secrets:[docker_username, docker_password ]repo:appleboy/golang-httpdockerfile:example19-deploy-with-kubernetes/Dockerfiledefault_tags:truewhen:event:[push, tag ]
apiVersion:extensions/v1beta1kind:Deploymentmetadata:name:frontend# these labels can be applied automatically# from the labels in the pod template if not setlabels:app:gotrainingtier:frontendspec:# this replicas value is default# modify it according to your casereplicas:3# selector can be applied automatically# from the labels in the pod template if not set# selector:# app: guestbook# tier: frontendstrategy:type:RollingUpdaterollingUpdate:maxSurge:1maxUnavailable:1minReadySeconds:5template:metadata:labels:app:gotrainingtier:frontendspec:containers:- name:go-helloimage:appleboy/golang-http:VERSIONimagePullPolicy:Alwaysresources:requests:cpu:100mmemory:100Miports:- containerPort:8080env:- name:FOR_GODS_SAKE_PLEASE_REDEPLOYvalue:'THIS_STRING_IS_REPLACED_DURING_BUILD'
大家可以找到 image: appleboy/golang-http:VERSION,這邊需要寫個 sed 指令來取代 VERSION,部署到 staging 則是 latest,如果是 tag 則取代為 DRONE_TAG
prepare:
sed -ie "s/VERSION/$(VERSION)/g" deployment.yml
sed -ie "s/THIS_STRING_IS_REPLACED_DURING_BUILD/$(shell date)/g" deployment.yml
cat deployment.yml
而 Tag 就不用擔心,原因就是 VERSION 就會改變不一樣的值,所以肯定會即時更新,那假設團隊想要上傳相同 tag (這是不好的做法,請盡量不要使用),這時候動態修改 env 的作法就發揮功效了。從上面的教學,現在我們看安新的透過 GitHub Flow 來完成部署 Staging 及 Production 了。