Jenkins Pipeline Shared Library Resources Read File

How to Create a Jenkins Shared Library (Tutorial + Case Repo)

You're getting upward to speed with Jenkins, and you're mastering the fine art of the pipeline. Only now that you've got a few projects up and running, how exercise y'all avoid repeating the same code in many different pipelines?

As you've probably realised by at present, copying and pasting the same code into different Jenkins pipelines can become an absolute headache.

There'south a point at which some voice in your head starts telling yous: "D.R.Y." (Don't Repeat Yourself).

Merely I often demand to write code that I will need to utilise in several dissimilar pipelines in Jenkins.

How can yous avoid this?

You can store your "reusable bits" (technical term!) in a Shared Library in Jenkins.

Bookshelf

You only demand to write your lawmaking once, and so y'all can share the same code with all of your pipelines. BAM. 💥

This tutorial will tell you the nuts of setting up a Jenkins pipeline shared library, how to load the library, and how to use it in your pipelines.

Let'due south go.

Can yous reuse code in Jenkins?

If you're already writing custom code in your pipelines to do things like this:

  • read a configuration file

  • perform a code review of the application (e.g. using a tool similar SonarQube)

  • do some checks on the target environment

  • perform a deployment

…then you're probably improve off calculation this code into a shared library, then that other projects can use it.

Over fourth dimension, you'll build up a collection of these reusable functions in your Library.

People will admire your library, and will come up to visit to encounter the marvellous works within.

Library illustration

The library is airtight.

A shared library is a collection of independent Not bad scripts which yous pull into your Jenkinsfile at runtime.

The best part is, the Library can be stored, like everything else, in a Git repository. This ways you can version, tag, and practise all the absurd stuff y'all're used to with Git.

Hither'south how you create a Jenkins library, pace-past-step:

  1. Beginning you create your Groovy scripts (see further beneath for details), and add them into your Git repository.

  2. Then, you add your Shared Library into Jenkins from the Manage Jenkins screen.

  3. Finally, you lot pull the Shared Library into your pipeline using this annotation (usually at the superlative of your Jenkinsfile):

                                          @Library                    (                    'your-library-name'                    )                                  

What goes inside a Shared Library?

Within your Library you'll probably have two types of common code:

Steps.

Steps.

  • Steps: These are chosen Global Variables in Jenkins terminology, but these are the custom steps that you lot want to be available to all your Jenkins pipelines.

    For case: you might write a standard pace to deploy an application, or perform a code review. To do this, add your lawmaking into vars/YourStepName.bang-up and then implement a def phone call function, like this:

                                          #                    !                    /usr/                    bin                    /                    env                    groovy                    // vars/YourStepName.neat                    def                    call                    ()                    {                    // Practise something here...                    }                                  
  • Other common code: This might include helper classes, or common code that you lot might desire to include inside pipeline steps themselves (very meta!). Yous could as well use it as a place to store static constants which you want to use throughout your pipelines.

    Code like this needs to get in the src/your/package/name directory, and then yous can use normal Groovy syntax.

    For example: Here'south a common file, xyz/tomd/GlobalVars.nifty (notation the package xyz.tomd at the meridian):

                                          #                    !                    /usr/                    bin                    /                    env                    groovy                    packet                    xyz.tomd                    class                    GlobalVars                    {                    static                    String                    foo                    =                    "bar"                    }                                  

    You tin can and then import this class into your Jenkinsfile and reference the static variable like GlobalVars.foo.

And so now the but affair left to do in this guide is show yous how to do it, for existent.

In this section, we'll see how to prepare up a shared library in Jenkins, with a quick example.

  1. Create the shared library

    First you need to create a Git repository which will contain your library of functions (steps). (You can too use Subversion.)

    In your repository, create a directory called vars. This volition hold your custom steps. Each of them will be a unlike .slap-up file underneath your vars directory, e.g.:

                      vars/     deployApplication.groovy     parseFile.groovy     sayHello.smashing     readSystemCredentials.groovy     doCodeReview.groovy                                  

    I'm using Git to store my repository. I've created a sample repo on GitHub, which includes ane function, the sayHello example from the official Jenkins documentation.

    Come across the example repository on GitHub

  2. Add your custom steps

    Each of your custom steps is a different .peachy file within your vars/ directory. In Jenkins terminology, these are called Global Variables, which is why they are located inside vars/.

    Create a file for your custom stride, and make full in the code. For example, a unproblematic greeting function would wait like this:

                                          #                    !                    /usr/                    bin                    /                    env                    groovy                    def                    telephone call                    (                    Cord                    proper noun                    =                    'human'                    )                    {                    repeat                    "Hello, ${name}."                    }                                  

    Detect how the Groovy script must implement the call method.

    After writing that, you should write your custom code within the braces { }. You can as well add parameters to your method - the case above has i parameter chosen name, which has a default value of man (cos nosotros're being actually personal here.)

  3. Prepare upwards the library in Jenkins

    Now you've created your library with custom steps, you need to tell Jenkins almost it.

    You can define a shared library within a Jenkinsfile, or yous can configure the library using the Jenkins web console. Personally, I call up it'southward meliorate to add from the spider web console, because y'all then you tin share the library beyond all of your build jobs.

    To add together your shared library (I'yard using my demo repository on GitHub as an example):

    In Jenkins, become to Manage Jenkins → Configure Organisation. Under Global Pipeline Libraries, add a library with the following settings:

    • Proper noun: pipeline-library-demo

    • Default version: Specify a Git reference (co-operative or commit SHA), e.1000. master

    • Retrieval method: Mod SCM

    • Select the Git type

    • Projection repository: https://github.com/tutorialworks/pipeline-library-demo.git

  4. Use the library in a pipeline

    To apply the shared library in a pipeline, you lot add @Library('your-library-name') to the height of your pipeline definition, or Jenkinsfile. Then phone call your step by name, e.g. sayHello:

                                          @Library                    (                    'pipeline-library-demo'                    )                    _                    stage                    (                    'Demo'                    )                    {                    echo                    'Hello world'                    sayHello                    'Dave'                    }                                  

    Note: The underscore (_) is not a typo! You demand this underscore if the line immediately after the @Library notation is not an import statement.

    If you're using declarative pipeline, the syntax looks slightly different:

                                          libraries                    {                    lib                    (                    'pipeline-library-demo'                    )                    }                    pipeline                    {                    // Your pipeline would get here....                    }                                  
  5. Run the pipeline above, and the output should look something similar this:

Sample job output from Jenkins

Sample job output from Jenkins

Sample job output from Jenkins past Tutorial Works is licensed under CC BY-SA 4.0

And you're washed.

At present you lot can start adding all of your custom steps to the library.

What if you don't accept Jenkins admin access?

You might find that you don't take ambassador admission to Jenkins, and then you can't see the Manage Jenkins surface area.

(I think this is pretty bad, because you should be able to manage your ain Jenkins instance)

If this is a blocker for you lot, then you lot can import a library explicitly in a pipeline, instead.

Here'southward an case declarative pipeline which uses a shared library, which is stored in a protected (private) Git repository.

The pipeline imports the library past using the library command, and giving a retriever, which is basically the details of your Git repo.

Golden retriever dog

An bodily retriever

The retriever will authenticate to the repository using the credentials identified by your-credentials-id:

                              library                identifier:                'mylibraryname@master'                ,                // 'mylibraryname' is just an identifier, it can be anything y'all like                // 'master' refers to a valid git ref (branch)                retriever:                modernSCM                ([                $class                :                'GitSCMSource'                ,                credentialsId:                'your-credentials-id'                ,                // remove this if information technology's public!                remote:                'https://git.yourcompany.com/yourrepo/individual-library.git'                ])                pipeline                {                agent                any                stages                {                stage                (                'Demo'                )                {                steps                {                echo                'Howdy earth'                yourCustomStep                'your_arg'                }                }                }                }                          

Summary (TL;DR)

That's information technology for my intro to Shared Libraries in Jenkins! Equally you can see they're a useful style to share common code that you lot might use across different Jenkinsfiles.

Here are the important things to call back:

  • You lot demand to use Dandy to write your custom functions or steps

  • To write pipeline steps that you can call from your pipelines (east.one thousand. deployApplication, readConfigFile, etc.):

    • Create a file in the vars/ directory in your repository, with the proper name of your custom pace

    • The file should implement the def telephone call() method; you lot can as well define parameters to your step

  • To write other mutual Slap-up code, add it into src/

  • Add your Shared Library in Jenkins using the Configure Organisation screen

Cheers for reading! I hope you've institute this instance Jenkins pipeline library useful.

How are you using Jenkins pipelines? Any feedback on this article? You're very welcome to postal service your thoughts in the comments section beneath.

This commodity was originally posted on my blog.

Copyright © 2022 Tom Donohue. All rights reserved, except where stated.

Tutorial Works is a participant in the Amazon.com Services LLC Associates Program. Every bit an Amazon Associate nosotros earn from qualifying purchases. Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.

coxliturname.blogspot.com

Source: https://www.tutorialworks.com/jenkins-shared-library/

0 Response to "Jenkins Pipeline Shared Library Resources Read File"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel