Bird
Raised Fist0
Jenkinsdevops~10 mins

@Library annotation in Jenkins - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - @Library annotation
Start Jenkinsfile
↓
@Library annotation reads library name
↓
Jenkins loads shared library code
↓
Library functions/classes become available
↓
Jenkinsfile calls library code
↓
Pipeline executes with library support
↓
End
The @Library annotation tells Jenkins to load shared library code before running the pipeline script.
Execution Sample
Jenkins
@Library('my-shared-lib') _
pipeline {
  agent any
  stages {
    stage('Example') {
      steps { myFunction() }
    }
  }
}
This Jenkinsfile uses @Library to load 'my-shared-lib' and calls a function from it in the pipeline.
Process Table
StepActionEvaluationResult
1Read Jenkinsfile startDetect @Library('my-shared-lib')Prepare to load 'my-shared-lib'
2Load shared libraryFetch 'my-shared-lib' from configured sourceLibrary code loaded and available
3Parse pipeline blockRecognize stages and stepsPipeline structure ready
4Execute stage 'Example'Call myFunction() from librarymyFunction() runs successfully
5Complete pipelineNo errorsPipeline finishes successfully
💡 Pipeline ends after all stages run with library functions available
Status Tracker
VariableStartAfter Step 2After Step 4Final
libraryLoadedfalsetruetruetrue
myFunctionAvailablefalsetruetruetrue
pipelineStatusnot startednot startedrunningcompleted
Key Moments - 2 Insights
Why do we need the underscore (_) after the @Library annotation?
The underscore tells Jenkins to load the library immediately and make its functions available in the script, as shown in execution_table step 2 and 4.
What happens if the library name is incorrect or missing?
Jenkins will fail to load the library, causing errors when calling library functions, stopping the pipeline before step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step is the shared library code loaded?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Check the 'Action' and 'Result' columns in execution_table row 2
According to variable_tracker, when does 'myFunctionAvailable' become true?
AAfter Step 2
BStart
CAfter Step 4
DFinal
💡 Hint
Look at the 'myFunctionAvailable' row and its values after each step
If the @Library annotation is missing the underscore (_), what likely happens?
APipeline fails to start
BLibrary loads but functions are not available
CPipeline runs normally
DLibrary loads twice
💡 Hint
Refer to key_moments explanation about the underscore usage
Concept Snapshot
@Library annotation loads shared Jenkins libraries.
Syntax: @Library('lib-name') _
Loads code before pipeline runs.
Makes library functions/classes available.
Use underscore (_) to apply immediately.
Without it, library code is not imported.
Full Transcript
The @Library annotation in Jenkinsfiles tells Jenkins to load shared library code before running the pipeline. The underscore (_) after the annotation is important because it instructs Jenkins to import the library functions immediately, making them available in the pipeline script. The execution flow starts by reading the Jenkinsfile, detecting the @Library annotation, loading the shared library, then running the pipeline stages that can call library functions. Variables like 'libraryLoaded' and 'myFunctionAvailable' change from false to true once the library is loaded. If the library name is wrong or the underscore is missing, the pipeline will fail or the functions won't be available. This visual trace helps beginners see how the annotation affects pipeline execution step-by-step.

Practice

(1/5)
1. What is the main purpose of the @Library annotation in Jenkins pipelines?
easy
A. To specify the pipeline agent type
B. To load shared code libraries for reuse in pipelines
C. To define environment variables for the pipeline
D. To trigger downstream jobs automatically

Solution

  1. Step 1: Understand the role of @Library

    The @Library annotation is used to load shared libraries in Jenkins pipelines.
  2. Step 2: Identify its main purpose

    Loading shared libraries allows reuse of code and better organization of pipeline scripts.
  3. Final Answer:

    To load shared code libraries for reuse in pipelines -> Option B
  4. Quick Check:

    @Library loads shared libraries = C [OK]
Hint: Remember: @Library loads reusable code libraries [OK]
Common Mistakes:
  • Confusing @Library with environment variable setup
  • Thinking it triggers jobs instead of loading code
  • Using it to specify pipeline agents
2. Which of the following is the correct syntax to load a shared library named 'utils' in a Jenkinsfile?
easy
A. @Library('utils') _
B. @Library utils _
C. library('utils') _
D. @LoadLibrary('utils') _

Solution

  1. Step 1: Recall the correct syntax for @Library

    The correct syntax uses parentheses and quotes around the library name, followed by an underscore.
  2. Step 2: Match the syntax to options

    @Library('utils') _ matches @Library('utils') _, which is correct.
  3. Final Answer:

    @Library('utils') _ -> Option A
  4. Quick Check:

    Correct syntax uses parentheses and underscore = A [OK]
Hint: Use parentheses and underscore after @Library [OK]
Common Mistakes:
  • Omitting parentheses or quotes
  • Using wrong annotation like @LoadLibrary
  • Placing underscore before the annotation
3. Given this Jenkinsfile snippet:
@Library('mathLib') _
pipeline {
  agent any
  stages {
    stage('Calculate') {
      steps {
        script {
          echo mathLib.add(2, 3).toString()
        }
      }
    }
  }
}

What will be the output if the shared library 'mathLib' has a method add(a, b) that returns the sum of two numbers?
medium
A. 5
B. mathLib.add(2, 3)
C. Error: method not found
D. 23

Solution

  1. Step 1: Understand the method call in the script block

    The code calls mathLib.add(2, 3) which returns the sum of 2 and 3.
  2. Step 2: Convert the result to string and echo

    The result 5 is converted to string and printed by echo.
  3. Final Answer:

    5 -> Option A
  4. Quick Check:

    Sum of 2 and 3 = 5 [OK]
Hint: Method returns sum; echo prints '5' as string [OK]
Common Mistakes:
  • Expecting the method name printed instead of result
  • Confusing concatenation with addition
  • Assuming method is missing causing error
4. You wrote this at the top of your Jenkinsfile:
@Library('commonLib')
pipeline {
  agent any
  stages {
    stage('Test') {
      steps {
        script {
          commonLib.doSomething()
        }
      }
    }
  }
}

But Jenkins throws an error saying Missing required underscore after @Library annotation. How do you fix it?
medium
A. Change @Library to @LoadLibrary
B. Remove the parentheses from @Library
C. Place the underscore before the annotation like _ @Library('commonLib')
D. Add an underscore _ immediately after the annotation like @Library('commonLib') _

Solution

  1. Step 1: Identify the syntax error from the message

    The error says the underscore is missing after @Library, which is required syntax.
  2. Step 2: Correct the syntax by adding underscore

    Add an underscore immediately after the annotation: @Library('commonLib') _.
  3. Final Answer:

    Add an underscore _ immediately after the annotation like @Library('commonLib') _ -> Option D
  4. Quick Check:

    Underscore after @Library fixes syntax [OK]
Hint: Always put underscore right after @Library(...) [OK]
Common Mistakes:
  • Omitting the underscore
  • Placing underscore before annotation
  • Changing annotation name incorrectly
5. You want to load two shared libraries named 'utils' and 'helpers' in your Jenkinsfile. Which is the correct way to do this using the @Library annotation?
hard
A. @Library('utils_helpers') _
B. @Library('utils') _ @Library('helpers') _
C. @Library(['utils', 'helpers']) _
D. @Library('utils,helpers') _

Solution

  1. Step 1: Recall how to load multiple libraries

    Multiple libraries can be loaded by passing a list of names inside @Library annotation.
  2. Step 2: Identify correct syntax for multiple libraries

    The correct syntax is @Library(['utils', 'helpers']) _ which loads both libraries at once.
  3. Final Answer:

    @Library(['utils', 'helpers']) _ -> Option C
  4. Quick Check:

    Use list inside @Library for multiple libs [OK]
Hint: Use list syntax inside @Library to load many libs [OK]
Common Mistakes:
  • Trying to use multiple @Library annotations
  • Passing comma-separated string instead of list
  • Combining names into one string without list
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard