jenkins groovy - ghdrako/doc_snipets GitHub Wiki

seed Job

  • https://www.linkedin.com/pulse/jenkins-automation-using-groovy-priyanshi-kaila A seed Job has to be created manually that too only once and all the Jobs are automatically configured by it. This is called the Jenkinsfile Approach. Jenkinsfile is a text file that contains the definition of all the Jobs. Job DSL Plugin is required for creating automatic jobs using a Jenkinsfile.
  • CREATING THE SEED JOB

Seed Job has to be made only once manually. It will pull the GitHub repo and configure other specified Jobs whenever the Developer pushes the code. This can be done by creating a GitHub Hook Trigger.

In the Seed Job set the Build Options to "GitHub hook trigger for GITScm polling" so that whenever the Developer pushes the code the Job is automatically build.

For building the further Jobs by using the Seed Job you need to set the file name in which the DSL Script is present in the "DSL Scripts" option of the Seed Job.

Shared libraries

Pipeline has support for creating shared libraries which can be defined in external source control repositories and loaded into existing pipelines

A shared library is defined with a name, a source code retrieval method such as by SCM, and optionally a default version. The name should be a short identifier as it will be used in scripts.

(root)
+- src # Groovy source files
|
+- vars
|
+- test # unit test files
|
+- resources # resource files
| 
  • src directory is added to the classpath when executing pipelines.
  • vars directory hosts script files that are exposed as a variable in pipelines. The name of the file is the name of the variable in the pipeline.
  • resources directory all the non-Groovy files/helper scripts required for the pipeline can be managed in this folder, from the above structure the sample. JSON template is stored in the resources folder and can be called in the shared library using libraryResource function.

call the library

@Library('my-shared-library') _ 

Sample of writing functions in the Groovy shared library

// src/org/foo/Zot.groovy
#!/usr/bin/groovy
package org.foo

def myFunction(repo) {
  sh "echo this is my function in Shared Library"
}

return this 

Defining shared library global variables

The vars directory hosted scripts that define global variables accessible from the pipeline.

+- vars
| +- myVariables.groovy

Internally, scripts in the vars directory are instantiated on-demand as singletons. This allows multiple methods to be defined in a single .Groovy file for convenience.

withCredentials

HTTP Request Plugin

httpRequest: Perform an HTTP Request and return a response object

withCredentials([string(credentialsId: settings.code_credentials_id, variable: 'GITLAB_API_TOKEN')]) {
   def response = httpRequest(url: "${GITLAB_URL}/api/v4/projects/${project_id}/hooks",
                                contentType: 'APPLICATION_JSON',
                                customHeaders: [name: 'PRIVATE-TOKEN', value: "${GITLAB_API_TOKEN}"](/ghdrako/doc_snipets/wiki/name:-'PRIVATE-TOKEN',-value:-"${GITLAB_API_TOKEN}"),
                                httpMode: 'GET',
                                consoleLogResponseBody: false,
                                quiet: true
                            )
  // println("HTTP Response: " + response.content)

  def webhooks = new JsonSlurper().parseText(response.content)
  // println("Configured webhooks:\n" + JsonOutput.prettyPrint(response.content))
  for (webhook in webhooks) {
      if (webhook.url == jenkinsUrl) {
        NEED_WEBHOOK_INSTALLATION = false
      }
  }
  if (NEED_WEBHOOK_INSTALLATION) {
    print "No webhook found, creating (${projectWithNamespace})..."

                                // Not possible to disable push events (hardcode in sharedlibs to enable push and merge request events)
                                // gitlab.addWebhook([
                                //     gitlabApiToken: settings.code_credentials_id,
                                //     webhookToken: webhookToken,
                                //     jenkinsUrl: jenkinsUrl,
                                //     projectId: projectWithNamespace
                                // ])

                                response = httpRequest(url: "${GITLAB_URL}/api/v4/projects/${project_id}/hooks",
                                    contentType: 'APPLICATION_JSON',
                                    customHeaders: [name: 'PRIVATE-TOKEN', value: "${GITLAB_API_TOKEN}"](/ghdrako/doc_snipets/wiki/name:-'PRIVATE-TOKEN',-value:-"${GITLAB_API_TOKEN}"),
                                    httpMode: 'POST',
                                    requestBody: """
                                        {
                                            "enable_ssl_verification":"true",
                                            "merge_requests_events":"true",
                                            "push_events":"false",
                                            "url": "${jenkinsUrl}"
                                        }
                                    """.stripIndent(),
                                    consoleLogResponseBody: false,
                                    quiet: true
                                )
                                println("HTTP Response: " + response.content)
                            }
                            SUMMARY += "| ${response.status} | Webhooks found: ${webhooks.size()} | Webhook added: ${NEED_WEBHOOK_INSTALLATION}\t| ${projectWithNamespace}"
                        }
'''