podTemplate(cloud: 'kubernetes', yaml: """
apiVersion: v1
kind: Pod
spec:
containers:
- name: jnlp
image: 'ops-reg.xxxx.com/ops/rancher/jenkins-jnlp-slave:3.10-1-alpine'
args: ['\$(JENKINS_SECRET)', '\$(JENKINS_NAME)']
- name: docker-test
image: ops-reg.xxxx.com/ops/docker:dind
command: ['cat']
tty: true
env:
- name: HARBORUSERNAME
valueFrom:
configMapKeyRef:
name: harbor-username-pwd
key: username
- name: HARBORPWD
valueFrom:
configMapKeyRef:
name: harbor-username-pwd
key: password
volumeMounts:
- name: dockersock
mountPath: /var/run/docker.sock
volumes:
- name: dockersock
hostPath:
path: /var/run/docker.sock
imagePullSecrets:
- name: registry-secret
"""
) {
def GITLAB_REGISTRY = 'ops-reg.xxxx.com'
node(POD_LABEL) {
stage('Build Docker image') {
container('docker-test') {
withCredentials([usernamePassword(credentialsId: 'harbor', passwordVariable: 'harborPwd', usernameVariable: 'harborUsername')]) {
sh "docker login -u ${harborUsername} -p ${harborPwd} ${GITLAB_REGISTRY}"
}
def docker_repo = 'cenarius'
git changelog: false, credentialsId: 'c0255365-13dd-4b18-aa16-49c8b9de9a50', poll: false, url: 'https://oa-git.xxxx.com/JDS/Cenarius.git' //clone代码到docker-test容器中
// def GIT_COMMIT_INFO = checkout scm //获取本次commit信息,其中包括commit hash值.
// echo "$GITLAB_REGISTRY/3rd/${docker_repo}:${GIT_COMMIT_INFO.GIT_COMMIT}"
def app = docker.build("$GITLAB_REGISTRY/3rd/${docker_repo}")
def TAG = sh(returnStdout: true, script: 'sh get_version.sh')
app.push("${TAG}")
def imageID = app.id
sh "docker rmi ${imageID}"
}
}
}
}
在podTemplate中使用yaml语法定义name
为jnlp
的pod(注意,这里的name必须为jnlp,Jenkins将通过yaml中定义的pod name来决定那个容器做什么用,而kubernetes-plugin默认slave的使用的容器名称为jnlp),jenkins将默认使用该pod作为slave的基础镜像。因为jnlp镜像比较大,所以从私库拉取镜像是更好的方法。同样在yaml中定义私库地址,并用imagePullSecrets
指出登录私库所用secret。
env:
- name: HARBORUSERNAME
valueFrom:
configMapKeyRef:
name: harbor-username-pwd
key: username
以上yaml表示通过读取configmap,获取相关配置信息(在该处,读取名为harbor-username-pwd的configmap的username属性,并将该属性的值设置为名为HARBORUSERNAME的容器环境变量)。
withCredentials([usernamePassword(credentialsId: 'harbor', passwordVariable: 'harborPwd', usernameVariable: 'harborUsername')]) {
sh "docker login -u ${harborUsername} -p ${harborPwd} ${GITLAB_REGISTRY}"
}
以上配置使用在jenkins中添加的凭据,这样做的好处在于,将隐藏所有敏感信息,例如harbor的登录用户名及密码。
参考:
https://github.com/jenkinsci/kubernetes-plugin
The default jnlp agent image used can be customized by adding it to the template
部分。