配置Jenkins连接kubernetes的Pod Template模板

Posted Serverless和DevOps技术分享

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了配置Jenkins连接kubernetes的Pod Template模板相关的知识,希望对你有一定的参考价值。

配置Jenkins连接kubernetes模板

如果跑java 的流水线工程,显示Jenkins从业务节点pending状态,如果是调度出现cpu或者内存大小资源问题,可以到Jenkins "配置">"configure cloud" > "kubernetes" > "Template" > "java模板" 中修改resource的大小,使其可以分配

进入Jenkins配置->修改Configure Cloud模板

image

image

配置一个kubernetes节点

image

image

增加Pod Template配置

在最下面增加pod template配置,当前主要增加了默认的Jenkins-slave节点、Jenkins-slave-Java节点、Jenkins-slave-golang1.15节点、Jenkins-slave-python3.7节点、Jenkins-slave-nodejs12节点的模板。

image

image

image

分解显示--> base Template

image

image

image

image

分解显示--> Java Template

image

image

image

image

分解显示--> golang1.15 Template

image

image

image

分解显示--> nodejs12 Template

image

image

image

分解显示--> Python 3.7 Template

image

image

image

以上就是Jenkins web 页面连接kubernetes的配置,主要是连接Jenkins之后使其自动拉起Jenkins-slave组件。

附上发布Java的Jenkinsfile文件

image

Jenkinsfile文件如下


void clone_stepsFunc() {
		script {
  def defaultTimeout = \'10\'
  def inputTimeout = \'10\'
  def validReg = \'^[1-9]\\\\d*$\'
  if (!inputTimeout.matches(validReg)) {
      inputTimeout = defaultTimeout
  }
  timeout(time: inputTimeout.toInteger(), unit: "MINUTES"){
    def repositoryURL = "http://192.168.40.195:31101/root/testjava"
    def credentialsID = ""
    def relativeDirectory = "."

    env.RELATIVE_DIRECTORY = relativeDirectory
    def branch = "master"

      if ("".equals(branch)) {
        branch = "master"
      }

    def useBindCodeRepository = false
    useBindCodeRepository = true

  def isPr=false;
  def sourceBranch
  try {
    def alaudaDevopsInstance = alaudaDevops.newInstance()
    alaudaDevopsInstance.withCluster() {
      alaudaDevopsInstance.withProject(alaudaContext.getNamespace()){
        def isTriggerByCodeRepoPushEvent
        try {
          isTriggerByCodeRepoPushEvent = alaudaEvent.isCodeRepoPushEvent()
        } catch (groovy.lang.MissingPropertyException e) {
          echo "Error when try to read event details from global variable, you probably are using a lower version Jenkins, reason: ${e.message}"
          isTriggerByCodeRepoPushEvent = false
        }

        // if pipeline is triggered by coderepository.push event,
        // we will clone the repository that has been pushed.
        if (isTriggerByCodeRepoPushEvent) {
          def eventContext = alaudaEvent.getCodeRepoPushContext()
          def codeRepository = alaudaDevopsInstance.selector("coderepository", eventContext.repoName).object()

            credentialsID = codeRepository.metadata.annotations.secretNamespace + \'-\' + codeRepository.metadata.annotations.secretName
            repositoryURL = codeRepository.spec.repository.cloneURL

            if(eventContext!=null){
              if (eventContext.getEventType()=="PRBranch"){
                branch = eventContext.targetBranch
                sourceBranch = eventContext.sourceBranch
                isPr=true
              }else {
                branch = eventContext.branch
              }
            }
          } else if (useBindCodeRepository) {
            def codeRepository = alaudaDevopsInstance.selector("coderepository", "demo1-operators-demo1-gitlab-sample-root-testjava").object()
            credentialsID = codeRepository.metadata.annotations.secretNamespace + \'-\' + codeRepository.metadata.annotations.secretName
          }
        }
      }
    } catch (err) {
      error err.getMessage()
    }

    if (credentialsID == "") {
      credentialsID = "demo1-p1-demo1-gitlab-root"
    }

    def scmVars=null
    if (isPr){
      sh script: \'git config --global user.email "default"\'
      sh script: \'git config --global user.name "Default"\'
      scmVars = checkout([
                  $class: \'GitSCM\',
                  branches: [[name: sourceBranch]],
                  extensions: [[
                    $class: \'PreBuildMerge\',
                    options: [
                        fastForwardMode: \'FF\',
                        mergeRemote: \'origin\',
                        mergeStrategy: \'DEFAULT\',
                        mergeTarget: branch]
                  ],[
                    $class: \'SubmoduleOption\',
                    recursiveSubmodules: true,
                    parentCredentials: true,
                    reference: \'\',
                  ],[
                    $class: \'RelativeTargetDirectory\',
                    relativeTargetDir: relativeDirectory
                  ],[
                    $class: \'RecordLastChangeLog\'
                  ],[
                    $class: \'CheckoutOption\', timeout: inputTimeout.toInteger()
                  ]],
                  userRemoteConfigs: [[
                    credentialsId: credentialsID,
                    url: repositoryURL
                  ]]
                ])
    } else {
      scmVars = checkout([
        $class: \'GitSCM\',
        branches: [[name: branch]],
        extensions: [[
          $class: \'SubmoduleOption\',
          recursiveSubmodules: true,
          parentCredentials: true,
          reference: \'\',
        ],[
          $class: \'RelativeTargetDirectory\',
          relativeTargetDir: relativeDirectory
        ],[
          $class: \'RecordLastChangeLog\'
        ],[
          $class: \'CheckoutOption\', timeout: inputTimeout.toInteger()
        ]],
        userRemoteConfigs: [[
          credentialsId: credentialsID,
          url: repositoryURL
        ]]
      ])
    }

    dir(RELATIVE_DIRECTORY){
          env.FROM_SCM = true
          env.SCM_AUTHOR = sh (script: \'git log -1 --pretty=format:"%an"\',returnStdout: true).trim()
          env.SCM_COMMIT_INFO = sh (script: \'git log -1 --pretty=%B\',returnStdout: true).trim()
          env.SCM_COMMIT = scmVars.GIT_COMMIT
          env.GIT_COMMIT = scmVars.GIT_COMMIT
          env.IS_PR = isPr

          if (isPr){
            env.GIT_BRANCH = sourceBranch
            //compatible with multi-branch pipeline
            env.BRANCH_NAME = sourceBranch

            env.TARGET_BRANCH = branch
          } else {
            env.GIT_BRANCH = scmVars.GIT_BRANCH.replaceFirst("origin/","")
            //compatible with multi-branch pipeline
            env.BRANCH_NAME = scmVars.GIT_BRANCH.replaceFirst("origin/","")

            env.TARGET_BRANCH = ""
            }

          //compatible with old version pipeline
          env.GIT_BRANCH_AS_TAG = env.GIT_BRANCH.replaceAll("/","-")

    }

    alaudaPipeline.appendInfo(STAGE_NAME, [commit_id: scmVars.GIT_COMMIT, branch: scmVars.GIT_BRANCH, repo_url: repositoryURL as String], \'_Clone\')

    
    env.CREDENTIAL_ID = credentialsID
    env.CODE_REPO = repositoryURL
    env.TIMESTAMP = new Date().format("yyyyMMddHHmmss")
  }
}

	}
void maven_stepsFunc() {
		script {
try{
  container(\'java\'){
    sh """
      mvn clean package
    """
  }
}catch(Exception e){
    throw e
}finally{
}

}

	}
void build_docker_stepsFunc() {
		script {
    def alaudaDevopsInstance = alaudaDevops.newInstance()
    def retryCount = 3
    def repositoryAddr = \'192.168.40.195:31104/demo1-p1/testjava\'.replace("http://","").replace("https://","")
    def IMAGE_REPO = repositoryAddr
    def IMAGE_REGISTRY_SERVER = repositoryAddr.replaceAll("/.*","")

    def credentialId = \'\'
    credentialId = "demo1-p1-dockercfg--demo1-p1--demo1-p1-harbor"
    dir(RELATIVE_DIRECTORY) {
        container(\'tools\'){
            retry(retryCount) {
                def buildImages = []
                withDockerRegistry([credentialsId: credentialId, url: \'https://\'+IMAGE_REGISTRY_SERVER]) {
                    def tagswithcomma = "latest,${TIMESTAMP},${GIT_COMMIT}"
                    def tags = tagswithcomma.split(",")
                    def incubatorimage = "${IMAGE_REPO}:${tags[0]}"
                    def image = docker.build(incubatorimage, "-f Dockerfile  .")
                    tags.each { tag ->
                      image.tag(tag)
                      image.push(tag)

                      buildImages.add("${IMAGE_REPO}:${tag}" as String)
                    }
                }
                alaudaPipeline.appendInfo(STAGE_NAME, [build_image: buildImages], \'_Docker\')
            }
        }
    }
}

	}
pipeline{

	

	agent {label "java"}
	environment{
			ALAUDA_PROJECT = "demo1-p1"
	}
    options{
        buildDiscarder(logRotator(numToKeepStr: \'200\'))
	}

	stages{
		stage("clone"){

	
	steps{
		clone_stepsFunc()
	}
}
stage("maven"){

	
	steps{
		maven_stepsFunc()
	}
}
stage("build-docker"){

	
	steps{
		build_docker_stepsFunc()
	}
}

	}
}

以上是关于配置Jenkins连接kubernetes的Pod Template模板的主要内容,如果未能解决你的问题,请参考以下文章

jenkins-使用 Pod 构建任务时挂载 NFS 持久卷到工作目录

jenkins-使用继承实现基于 kubernetes Pod 的多容器的多构建环境的 Jenkins Slave

配置 Jenkins 连接 Kubernetes 集群

GitLab + Jenkins + Docker + Kubernetes。

从 kubernetes 插件 / jenkins 中的 gcr 拉取 docker 图像的问题

(集群外)jenkins连接K8S集群