how to fetch agent pod template from different repository in jenkins pipeline

985 Views Asked by At

I want to keep jenkins pipeline agents (kubernetes pod) templates in Repo A. The jenkinsfile is in Repo B. To run stage 'ci' on Repo B, I need agents folder checked out from Repo A.

pipeline {
  agent none
  stages {
    stage('ci') {
      agent {
        kubernetes {
          yamlFile "agents/ci.yaml"
        }
      }
      steps {
      }
    }
    stage('staging deploy') {
      agent {
        kubernetes {
          yamlFile "agents/stage-deploy.yaml"
        }
      }
      steps {
      }
    }
  }
}

When I run jenkins pipeline job, it checks out Repo B (branch name = develop). But I am not able to checkout Repo A (branch name = master) to get the agents templates. Any help here would be great. I have been struggling around this a lot.

1

There are 1 best solutions below

0
On

You need to pull the repo with pod templates first, next reference the contents of the desired yaml file. The first stage needs to be executed on master node.

Here is the example of the pipeline:

def currentLabel = "${UUID.randomUUID().toString()}"
def podTemplate 

pipeline {
  agent any

  stages {
    stage('Checkout pod templates') {
      agent {
        label 'master'
      }
      steps {
        sh "mkdir podTemplates"

        dir("podTemplates") {
          git branch: "master",
          url: "[email protected]/your-pod-templates.git",
          credentialsId: "$REPO_CREDS"
        }
        script {
            podTemplate = new File("${WORKSPACE}/podTemplates/pod-template.yml").text
        }
      }
    }


    stage('Second stage') {
        agent {
          kubernetes {
            label currentLabel
            defaultContainer 'jnlp'
            yaml podTemplate
          }
        }  

        steps {
            script {
                ...
                do something here
                ...
            }
        }
    }

  }
}

I think you can create as many podTemplate variables as you need.