main_bg

Jenkins Interview Questions

Explore the world of Jenkins with 'Jenkins Interview Questions.' This blog is your essential guide for preparing for Jenkins-related interviews, offering a comprehensive collection of questions and detailed answers. Whether you're a DevOps engineer, a software developer, or a Jenkins enthusiast, our resource provides insights into Jenkins fundamentals, continuous integration, automation, and best practices. Prepare with confidence and discover the power of Jenkins in streamlining software development and deployment processes.

1. What is Jenkins?

Jenkins is an open-source automation server that facilitates continuous integration and continuous delivery (CI/CD). It helps automate the building, testing, and deployment of code changes.

2. Explain the difference between Jenkins and Hudson.

Jenkins and Hudson are both CI/CD tools, but Jenkins is a fork of Hudson. Jenkins has a larger and more active community and more frequent releases compared to Hudson.

3. What are the common use cases Jenkins is used for?

Jenkins being open-source automation can be used for any kind of software-based automation. Some of the common use-cases include but not limited to -

  • Software build jobs
  • Sanity/Smoke/CI/Regression test jobs
  • Web/Data Scraping related jobs
  • Code coverage measurement jobs
  • General-purpose automation
  • Reverse Engineering jobs
  • Key Decoding jobs & many other jobs where software automation will be applicable.

4. What is a Jenkins job?

A Job/Project is the fundamental unit of a logical work (like a software build, an automation task, test execution, etc) using the Jenkins automation server and other required plugins, configurations & infrastructures.

Jobs can be of different types like - a freestyle project, a multi-configuration project, a pipeline project, a multi-branch project, etc.

5. What are the types of Jenkins pipelines?

Jenkins Pipelines can be either - a Declarative pipeline or a Scripted Pipeline. Declarative pipeline makes use of numerous, generic, predefined build steps/stages (i.e. code snippets) to build our job according to our build/automation needs whereas, with Scripted pipelines, the steps/stages can be custom-defined & used using a groovy syntax which provides better control & fine-tuned execution levels.

6. How do you store credentials in Jenkins securely?

Credentials can be stored securely in Jenkins using the Credentials plugin, which stores different types of credentials like - Username with a password, SSH username with the private key, AWS Credentials, Jenkins Build Token, Secret File/Text, X509 & other certificates, Vault related credentials securely with proper encryption & decryption as and when required.

7. How can we stop a scheduled job from being executed temporarily?

Disable the job from the job details page to temporarily stop all scheduled executions & other factors/events from triggering the job and enable it back to resume the job schedules/triggers. If a job is not required permanently, we can delete the job from the jobs list view page.

8. What are the ways to trigger a Jenkins Job/Pipeline?

There are many ways we can trigger a job in Jenkins. Some of the common ways are as below -

  • Trigger an API (POST) request to the target job URL with the required data.
  • Trigger it manually from the Jenkins web application.
  • Trigger it using Jenkins CLI from the master/slave nodes.
  • Time-based Scheduled Triggers like a cron job.
  • Event-based Triggers like SCM Actions (Git Commit, Pull Requests), WebHooks, etc.
  • Upstream/Downstream triggers by other Jenkins jobs.

9. What is Jenkins Build Cause?

Build Cause is a text attribute that represents what made a job's build to be triggered, say it could be a Jenkins User (from UI), Timer for Scheduled jobs, Upstream jobs for a job which was triggered by upstream job, etc. This is mainly used to identify the nature of the builds - be it nightly, manual, automated, etc.

10. How Jenkins knows when to execute a Scheduled job/pipeline and how it is triggered?

Jenkins master will have the cron entries set up for the jobs as per the scheduled Job's configurations. As and when the time for a particular job comes, it commands agents (based on the configuration of the job) to execute the job with required configurations.

11. What are the credential types supported by Jenkins?

In Jenkins, credentials are a set of information used for authentication with internal/external services to accomplish an action. Jenkins credentials are provisioned & managed by a built-in plugin called - Credentials Binding - plugin. Jenkins can handle different credentials as follows -

  • Secret text - A token such as an API token, JSON token, etc.
  • Username and password - Basic Authentication can be stored as a credential as well.
  • Secret file - A secret file used to authenticate some secure data services & security handshakes.
  • SSH Username with a private key - An SSH public/private key pair for Machine to Machine authentication.
  • Certificate - a PKCS#12 certificate file and an optional password.
  • Docker Host Certificate Authentication credentials.

And as we can guess, this can be extended to several other extensible credential types like - AWS credential, Azure secrets, etc. using commonly available plugins.

12. What are the Scopes of Jenkins Credentials?

Jenkins credentials can be of one of the two scopes - Global & System

Global - the credential will be usable across all the jobs configured in the Jenkins instance (i.e. for all jobs). This is more suited for user Jobs (i.e. for the freestyle, pipeline, or other jobs) to authenticate itself with target services/infrastructures to accomplish the purpose of the job)

System - This is a special scope that will allow the Jenkins itself (i.e. the core Jenkins functionalities & some installed plugins) to authenticate itself to external services/infrastructures to perform some defined tasks. E.g. sending emails, etc.

13. What is a Jenkins Shared Library and how it is useful?

As an organization starts using more and more pipeline jobs, there is a chance for more and more code being duplicated in every pipeline job, since a part of the build/automation processes will be the same for most of the jobs. In such a situation, every other new upcoming job should also duplicate the same piece of code. To avoid duplications, the Jenkins project brought in the concept of Shared Libraries, to code - DRY - Don't Repeat Yourself.

Shared libraries are a set of code that can be common for more than one pipeline job and can be maintained separately. Such libraries improve the maintenance, modularity & readability of the pipeline code. And it also speeds up the automation for new jobs.

14. How Jenkins jobs can be Triggered/Stopped/Controlled programmatically?

Jenkins Remote Access API can be used to do things like -

  • Retrieving information about jobs, views, nodes, builds, etc. from Jenkins for programmatic consumption.
  • Trigger a build (both parameterized & non-parameterized), stop/abort a build, enable/disable a Job, group/remove jobs into/from views, etc.
  • Create/copy/modify/delete jobs.

and many other programming language-specific functionalities. It has wrappers for main programming languages like - Python, Ruby & Java. It can be triggered via CURL as below -

Jobs without parameters

Simply an HTTP POST on JENKINS_URL/job/JOBNAME/build.

Jobs with parameters

Simple example - sending "String Parameters":

curl JENKINS_URL/job/JOB_NAME/buildWithParameters  --user USER:TOKEN --data id=123 --data verbosity=high

15. How to get the Jenkins version programmatically in Jobs/Pipelines or nodes other than master?

To check the version of Jenkins, load the top-level page or any top-level Remote Access API path like the '.../api/*' page and then check for the 'X-Jenkins' response header.

This contains the version number of Jenkins, like "1.404". This is also a good way to check if an URL is a Jenkins URL.

16. What happens when a Jenkins agent is offline and what is the best practice in that situation?

When a job is tied to a specific agent on a specific node, the job can only be run on that agent and no other agents can fulfill the job request. If the target node is offline or all the agents on that particular node are busy building other jobs, then the triggered job has to wait until the node comes online or an agent from that node becomes available to execute the triggered build request.

As a result, a triggered job may sometimes wait indefinitely without knowing that the target node is offline. So, it is always the best practice to tie the jobs to a group of nodes & agents, referred to with a 'Label'. Once a job is tied to a Label, instead of a specific node/agent, any of the nodes/agents falling under the label can fulfill a build request, when a job is triggered. This way we can reduce the overall turn-around time of the builds.

Even then if a job is waiting for more time for the nodes/agents, then it is time to consider adding more nodes/agents.

17. What is the Jenkins User Content service?

Jenkins has a mechanism known as "User Content", where administrators can place files inside the $JENKINS_HOME/userContent folder and these files are served from yourhost/jenkins/userContent.

This can be thought of as a mini HTTP server to serve images, stylesheets, and other static resources that you can use from various description fields inside Jenkins.

18. How is continuous integration achieved using Jenkins?

Continuous integration is a process where a developer’s code changes are constantly integrated into the main code and the same will be tested automatically and the results of the tests will decide whether the change is ready for deployment. In this process -

  • Developer Makes a change - commit/pull_request - in feature/dev branch
  • Source Control Management system generates appropriate events
  • SCM Specific Jenkins Plugins like Git/SVN will detect those events from the configured repositories and these events will be used to Trigger - build/dependent/test - jobs on Jenkins
  • After the Test/Dependent jobs are completed, the change/patch will be labeled according to the status of the test job
  • Based on the Status (i.e. readiness of a change to be merged with the main branch), the Continuous Delivery or Continuous Deployment strategy/tool will take it forward.

19. What is Artifact Archival & how to do it in Pipelines?

Artifacts are the exportable/storable/archivable results of a specific job build. This can be configured using a plugin called - Copy artifact Plugin. Based on the configured pattern, the files/directories matching the configured patterns will be archived for a Jenkins build, which can be used for future references. In the pipeline, it can be configured as follows -

archiveArtifacts artifacts: 'output/**/*'

20. How to configure inclusions & exclusions in Artifacts Archival?

Artifact archival takes in a pattern for matching target files. Similarly, it also takes in a pattern (ANT build system pattern for matching files) for exclusion as well which will be ignored while selecting the files for archival.

For e.g.
archiveArtifacts artifacts: 'output/*.txt', excludes: 'output/specific_file.txt'

The above command will archive all the text files from the output folder except specific_file.txt

21. How can we share information between different build steps or stages in a Jenkins Job?

Every build step or stage will be running in its process and hence sharing information between two different build steps is not so direct. We can use either a File, a Database Entry, an Environment Variable, etc. to share info from one build step to another or a post-build action.

22. How code coverage is measured/tracked using Jenkins in a CI environment?

Using language-specific code coverage plugins like JaCoCo, CodeCov, etc or generic tools/plugins like Sonarqube which will add the code coverage data to builds with some minor tweaks in the code and the same can be displayed as a graph in Jenkins.

23. Default Environment Variables by Jenkins & How to introduce custom environment variables?

Jenkins provides several environment variables by default like - BRANCH_NAME, BUILD_NUMBER, BUILD_TAG, WORKSPACE, etc.

24. How can a job configuration be reset to an earlier version/state?

From the Job details page, we can use Job Config History to - See diff, Review & Revert the Job configs from the history of changes we have made to a particular job. This will be super useful when a job is misconfigured by someone by mistake, it can be reviewed and reverted easily to any of its earlier states.

25. How to do Global Tools Configuration in Jenkins?

Global Tools are tools that need to be installed outside the Jenkins environment and need to be controlled from within the Jenkins environment. Hence it needs its corresponding Jenkins plugin as well. Steps to using a Global Tool generally include -

  • Install the tool Plugin into the Jenkins instance, to include the global tool into a list of global tools used by Jenkins.
  • Install the tool in the Jenkins instance or provide away (maybe a command to download and) install the tool during runtime.
  • Go to Manage Jenkins -> Global Tools Configuration and Scroll through the tool list and configure the global tool-specific configurations.
  • Make use of the installed global Tool in your job/pipeline.

26. How to create & use a Shared Library in Jenkins?

Basic requirements for a Jenkins shared library to be used in a Pipeline Code are -

  • A Repository with pipeline shared library code in SCM.
  • An appropriate SCM Plugin configuration for the Jenkins instance.
  • Global Shared Library should be configured in Jenkins Global configuration.
  • Include the Shared Library in the Pipeline Code and use the methods defined in the Jenkins Shared Library.

E.g.

#!/urs/bin/env groovy
@Library('fs_jenkins_shared_library@v2.0.7')_

27. How to download the Console log for a particular Jenkins build programmatically?

Using the Jenkins CLI - console - command

java -jar jenkins-cli.jar console JOB [BUILD] [-f] [-n N]

Produces the console output of a specific build to stdout, as if you are doing 'cat build.log'

  • JOB: Name of the job
  • BUILD: Build number or permalink to point to the build. Defaults to the last build
  • -f: If the build is in progress, append console output as it comes, like tail -f
  • -n N: Display the last N lines.

E.g.

ssh -l <ssh_username> -p <port_no> <Jenkins_URL> console <JOB_NAME>

28. What is In-process Script Approval and how it works?

Jenkins, and several plugins, allow users to execute Groovy scripts in Jenkins. To protect Jenkins from the execution of malicious scripts, these plugins execute user-provided scripts in a Groovy Sandbox that limits what internal APIs are accessible.

This protection is provided by the Script Security plugin. As soon as an unsafe method is used in any of the scripts, the "In-process Script Approval" action should appear in "Manage Jenkins" to allow Administrators to make a decision about which unsafe methods, if any, should be allowed in the Jenkins environment.

This in-process script approval inherently improves the security of the overall Jenkins ecosystem.

29. Can we monitor Jenkins using common Observability tools?

Common monitoring platforms like DataDog, Prometheus, JavaMelody & few others - have their corresponding Jenkins plugin, which when configured, sends Metrics to the corresponding Monitoring platform, which can then be Observed with the latest tools & technologies. The same can be configured with Alarms & Notifications for immediate attention when something goes wrong.

30. Code Snippet: Jenkins Pipeline

            
pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
                // Build steps here
            }
        }
        stage('Test') {
            steps {
                // Test steps here
            }
        }
        stage('Deploy') {
            steps {
                // Deployment steps here
            }
        }
    }
}
            
        

31. Online Resources:

Published On: 2024-01-17