一、代码文件
main.go
代码语言:javascript复制package main
// Import the fmt for formatting strings
// Import os so we can read environment variables from the system
import (
"fmt"
"os"
)
func main() {
fmt.Println("Hello, Kubernetes!I'm from Jenkins CI!")
fmt.Println("BRANCH_NAME:", os.Getenv("branch"))
}
二、构建镜像的Dockerfile文件
代码语言:javascript复制FROM golang:1.8.0-alpine
ADD . /go/src/app
WORKDIR /go/src/app
RUN GOOS=linux GOARCH=386 go build -v -o /go/src/app/jenkins-app
CMD ["./jenkins-app"]
三、k8s部署服务k8s.yaml文件
代码语言:javascript复制apiVersion: apps/v1
kind: Deployment
metadata:
name: jenkins-demo
namespace: default
spec:
selector:
matchLabels:
app: jenkins-demo
template:
metadata:
labels:
app: jenkins-demo
spec:
containers:
- image: cnych/jenkins-demo:<BUILD_TAG>
imagePullPolicy: IfNotPresent
name: jenkins-demo
env:
- name: branch
value: <BRANCH_NAME>
四、Jenkinsfile流水线文件
代码语言:javascript复制node('haimaxy-jnlp') {
stage('Prepare') {
echo "1.Prepare Stage"
checkout scm
script {
build_tag = sh(returnStdout: true, script: 'git rev-parse --short HEAD').trim()
if (env.BRANCH_NAME != 'master') {
build_tag = "${env.BRANCH_NAME}-${build_tag}"
}
}
}
stage('Test') {
echo "2.Test Stage"
}
stage('Build') {
echo "3.Build Docker Image Stage"
sh "docker build -t cnych/jenkins-demo:${build_tag} ."
}
stage('Push') {
echo "4.Push Docker Image Stage"
withCredentials([usernamePassword(credentialsId: 'dockerHub', passwordVariable: 'dockerHubPassword', usernameVariable: 'dockerHubUser')]) {
sh "docker login -u ${dockerHubUser} -p ${dockerHubPassword}"
sh "docker push cnych/jenkins-demo:${build_tag}"
}
}
stage('Deploy') {
echo "5. Deploy Stage"
if (env.BRANCH_NAME == 'master') {
input "确认要部署线上环境吗?"
}
sh "sed -i 's/<BUILD_TAG>/${build_tag}/' k8s.yaml"
sh "sed -i 's/<BRANCH_NAME>/${env.BRANCH_NAME}/' k8s.yaml"
sh "kubectl apply -f k8s.yaml --record"
}
}