gojenkinsjenkins-pipelinejenkins-groovy

Cannot get parameter value using gojenkins


I am creating an go api using gojenkins library. when I pass parameter in jenkins.BuildJob(ctx,jobName,parameter). I cannot access the parameter. the parameter type is map[string]string

I am providing code snippet.

Jenkin Job create function:

func (l kuberaes) jenkinsJobBuild(i JenkinsBuildReq) ResponseJenkinsResource {
    ctx := context.Background()
    jenkins := gojenkins.CreateJenkins(nil, "http://aescontroller-jenkins.default:8080/", "admin", "pass")
    fmt.Println("Jenkins ", jenkins)
    var deploymentType string
    if i.Deployment == "FRONTEND" {
        deploymentType = "update_frontend"
    } else if i.Deployment == "BACKEND" {
        deploymentType = "update_backend"
    }

    pipelineScript := `<?xml version="1.0"?>
<flow-definition plugin="workflow-job@2.40">
  <actions>
    <org.jenkinsci.plugins.pipeline.modeldefinition.actions.DeclarativeJobAction plugin="pipeline-model-definition@1.11.1"/>
  </actions>
  <description></description>
  <keepDependencies>false</keepDependencies>
  <properties/>
  <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2.92">
    <script>

    pipeline {
      parameters {
        string name: "GIT_REPO_P" 
                // I also used string(name:"GIT_REPO")
      }
      agent {
        kubernetes {
          label 'docker'
          idleMinutes '60'
          yaml '''
          apiVersion: v1
          kind: Pod
          spec:
            containers:
            - name: docker
              image: docker:19.03.6
              command:
              - cat
              tty: true
              env:
                - name: DOCKER_HOST
                  value: "tcp://dind.default:2375"
                - name: JENKINS_AGENT_WORKDIR
                  value: "/var/jenkins_home"
          '''
          }
        }

        environment {
          // Git
          GIT_REPO = "` + i.GitRepo + `"
          GIT_BRANCH = "` + i.GitBranch + `"
          GIT_ACCESS_TOKEN = "` + i.GitAccessToken + `"

          //Docker
          USER_NAME = "` + i.DockerUserName + `"
          APP_NAME = "` + i.DockerAppName + `"
          IMAGE_TAG = "$BUILD_NUMBER"
          PASSWORD = "` + i.DockerPassword + `"

          //deployed Info
          DEPLOYED_NAME = "` + i.Name + `"
          DEPLOYED_NAMESPACE = "` + i.Namespace + `"
          DEPLOYMENT_TYPE = "` + deploymentType + `"
        }
        
        triggers {
          GenericTrigger(
            token: '${DEPLOYED_NAME}-${DEPLOYED_NAMESPACE}',
          )
        }

        stages {
          stage('Print Parameters') {
            steps {
                script {
                    // Print parameters
                    echo "Hello World"
                    echo "Target Environment: ${GIT_REPO}"
                }
            }
          }
          stage("GIT CLONE") {
            steps {
              container('docker') {
                git branch: "${GIT_BRANCH}", url: "${GIT_REPO}"
              }
            }
          }
          stage("BUILD DOCKER IMAGE") {
            steps {
              container('docker') {
                sh "docker build -t ${USER_NAME}/${APP_NAME}:${IMAGE_TAG} -t ${USER_NAME}/${APP_NAME}:latest . -f ./dockerfile"
              }
            }
          }
          stage("PUSH DOCKER IMAGE TO DOCKERHUB") {
            steps {
              container('docker') {
                sh """
                  echo ${PASSWORD} | docker login --username ${USER_NAME} --password-stdin
                  docker push ${USER_NAME}/${APP_NAME}:${IMAGE_TAG}
                  docker logout
                """
              }
            }
          }
          stage("DEPLOY") {
            steps {
              sh """curl -X POST -H 'Content-Type: application/json' -d '{
                "Name": "ng",
                "Namespace": "test",
                "FrontendImg": "${USER_NAME}/${APP_NAME}:${IMAGE_TAG}"
              }' http://core-goport.core-ns.svc.cluster.local:8080/anwarcloud/${DEPLOYMENT_TYPE}"""
            }
          }
        }
    }   
    </script>
    <sandbox>true</sandbox>
  </definition>
  <triggers/>
  <disabled>false</disabled>
</flow-definition>`

    jobName := i.Name + "-pipeline"
    // Create the Pipeline job
    job, err := jenkins.CreateJob(ctx, pipelineScript, jobName)
    if err != nil {
        return ResponseJenkinsResource{
            Message: "Failed to create job: " + err.Error(),
            Status:  http.StatusInternalServerError,
        }
    }

    //Get Core Ip Address
    serviceName := "ingress-nginx-controller"
    service, _ := l.clientset.CoreV1().Services("core-ns").Get(context.TODO(), serviceName, metav1.GetOptions{})
    ExternalIP := service.Status.LoadBalancer.Ingress[0].IP
    WebHook := ExternalIP + "/generic-webhook-trigger/invoke?token=" + i.Name + "-" + i.Namespace

    var returnBody []TemplateJenkinsReturnBody
    body := TemplateJenkinsReturnBody{
        JobName: jobName,
        Webhook: WebHook,
    }
    returnBody = append(returnBody, body)
    return ResponseJenkinsResource{
        Message: "Successfully create " + job.GetName(),
        Body:    returnBody,
        Status:  http.StatusOK,
    }
}

During Build job I passed parameter:

func (l kuberaes) jenkinsJobRun(i JenkinsReq) ResponseJenkinsResource {
    ctx := context.Background()
    jenkins := gojenkins.CreateJenkins(nil, "http://aescontroller-jenkins.default:8080/", "admin", "pass")
    // jenkins.DeleteJob(ctx,)


    p := map[string]string{
    "GIT_REPO_P": "https://github.com/aes-sourav/sample-private-1.git",
     }

    p := gojenkins.ParameterDefinition{

    }
    queueid, err := jenkins.BuildJob(ctx, i.JobName, p) // here I passed the params

    if err != nil {
        return ResponseJenkinsResource{
            Message: "Failed to build the job: " + err.Error(),
            Status:  http.StatusInternalServerError,
        }
    }
    build, err := jenkins.GetBuildFromQueueID(ctx, queueid)
    if err != nil {
        panic(err)
    }

    return ResponseJenkinsResource{
        Message: "Successfully run " + build.Job.GetName(),
        Body:    nil,
        Status:  http.StatusOK,
    }
}

Thanks in advance

I have tried : params.GIT_REPO_P it also does not works


Solution

  • I figure out the problem. On the first attempt(job run), Jenkins just configured the configuration. when I run the second attempt (job run) everything works fine.