© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
P. P. DingareCI/CD Pipeline Using Jenkins Unleashedhttps://doi.org/10.1007/978-1-4842-7508-5_19

19. Miscellaneous Topics Part 1

Pranoday Dingare1  
(1)
Pune, Maharashtra, India
 

This and the following chapter cover a few important topics such as Jenkins CLI, Jenkins Rest APIs. You are already aware of how to control Jenkins manually using its UI. But sometimes you may need to control Jenkins programmatically through scripting languages or shell programs. In that case, you need to know how to use the programming interface provided by Jenkins and its command-line interface. This chapter focuses on how to interact with Jenkins using its CLI.

You are going to learn about some different common use cases where you are required to interact with Jenkins programmatically instead of manually.

Understanding the Jenkins CLI

Jenkins provides two kinds of interfaces—the Graphical User Interface(GUI), which we have already covered in this book, and the Command-line Interface (CLI), which you are going to learn about in this chapter.

Jenkins provides a different set of shell commands that you can run from shell programs, like the command prompt on Windows or the console shell on Linux-based systems. You can write batch programs or shell scripts to automate access to the Jenkins server. Let’s see in detail the different CLI commands Jenkins provides, how can we interact with the Jenkins server using these commands, and most importantly, how to provide authentication information to the Jenkins server to authenticate the Jenkins server access using CLI.

Jenkins provides us with many CLI commands, a list of which is available on the Jenkins CLI page.

Click the Manage Jenkins link available on the left side of the Jenkins dashboard. This will open the Manage Jenkins page.

Scroll down the page to find the Jenkins CLI link under the Tools and Actions section. Click the Jenkins CLI link, which will take you to the Jenkins CLI. This page shows a list of different commands and the purpose of each command.

How to Interact with Jenkins Using its CLI

This section explains how to perform basic operations through the CLI, like creating a job, running a build of a specific job, retrieving a list of all jobs, retrieving console output of a build, disabling a particular job, deleting a particular job, and more.

Before you start using the Jenkins CLI, you need to download jenkins-cli.jar. This JAR file provides the CLI client so you can access the CLI interface.

Click the jenkins-cli.jar link from the Jenkins CLI page to download the Jenkins-cli.jar file. After you click the link, the jenkins-cli.jar file will be downloaded.

Note

I started my Jenkins server from my machine’s IPv4 address (192.168.43.10) and the default port 8080. Therefore, my Jenkins URL is http://192.168.43.10:8080, which I use to access my Jenkins server through CLI. Your Jenkins URL will contain either the localhost or your IP address along with the port. I keep the jenkins-cli.jar file in the D:JenkinsBookExamples folder, so the CLI commands have the jenkins-cli.jar path, written as D:JenkinsBookExamplesjenkins-cli.jar. You need to use your path on your machine.

How to Create a Job Using the Jenkins CLI

To create a new job in Jenkins, you need to specify the job name and the configuration XML based on the new job. A view is a way to organize jobs and content into tabbed categories on the Jenkins dashboard. By default, Jenkins jobs are created in the All view; this is the tab that you see when you go to the Jenkins dashboard

To create a new job in Jenkins, run the following command:
java –jar {pathofJenkins-cli.jar} -s ${JENKINS_URL} –webSocket create-job  ${JobName} <  ${Configuration.xml}
Note

While demonstrating different CLI commands in this chapter, placeholders use ${}, which should be replaced with actual values.

To create a new job through CLI, you need to specify its specifications using an .XML file, which would be taken as a template for the new job.

I want to create new job called CLIJob1 using the configuration of an existing job named Demo. The configuration file is {JENKINS_HOME}jobsDemoConfig.xml. You get this configuration file of a demo job by default after Jenkins is installed. I copied this file to the D:JenkinsBookExamples folder and renamed it Demo.xml so my command is as follows:
java –jar  D:JenkinsBookExamplesjenkins-cli.jar –s http://192.168.43.10:8080/ –webSocket create-job CLIJob1 < D:JenkinsBookExamplesDemo.xml
Open the command prompt and run this command:
java –jar  D:JenkinsBookExamplesjenkins-cli.jar –s http://192.168.43.10:8080/ –webSocket create-job CLIJob1 < D:JenkinsBookExamplesDemo.xml
It will give the following error:
ERROR: anonymous is missing the Overall/Read permission

You get an error here because Jenkins considered this command coming from an anonymous user, as you have not provided authentication yet. Anonymous users are not authorized to create jobs according to the security configurations of the Jenkins server. Now let's see how to provide the authentication information of a user who is authorized to create a job in this CLI.

Authenticating Users Using Basic Authentication (Username-Password/API Token)

When you perform any task using the Jenkins CLI, you need to provide authentication information to perform that task using the –auth argument. You can authenticate users using basic authentication as well as SSH authentication. Let’s see first how to send Basic Authentication data using the –auth command-line argument. In basic authentication, you have to send a username-password or a username-API token. Sending an API token is the preferred and more secure option.

Log in using the authorized user’s credentials in the Login window. Once you are logged in, you can go to the page to create an API token.

I logged in using my Jenkins administrator credentials.

Click the User Name shown in the top-right corner of the dashboard page.

Click the Configure link to go to the next page, where you can configure API token for the user.

Click the Add New Token button inside the API Token section to generate a new token.

Enter a name in the field and click the Generate button.

Copy the generated token using the Copy This Token button and paste it in a file to preserve it for future use. Click the Save button.

Let’s authenticate the user using this token and create the job again using CLI with the following command:
Java –jar ${Jenkins-cli.jar file path} –s {JENKINS_URL} –auth ${UserName}:${API_TOKEN} –webSocket create-job ${JOB_NAME} < ${Configuration.xml}
I am using the following command after replacing all the placeholders with values:
java –jar D:JenkinsBookExamplesjenkins-cli.jar –s http://192.168.43.10:8080/ -auth Pranodayd:119737275fd132a08d5a3b457ed56649a2 –webSocket create-job CLIJob1 < D:JenkinsBookExamplesDemo.xml

Run the command at the command prompt. Then go to your Jenkins Dashboard page and refresh it. You can see that new job with the name CLIJob1 was created.

Let’s go inside CLIJob1 to see the build step having the Execute Batch command step with the echo Hi, which you also have in the Demo job.

Note

If the template XML file has any syntax issues, the create-job CLI command returns this error: cannot access the file because it is being used by another process. This is quite misleading and not related to the cause of the problem.

If a job with the same name already exists, the create-job command gives the Job Already Exists error.

Authenticating Users Through SSH While Using CLI Commands

You have already seen how to authenticate users using the username-APIToken. Now you'll see how to authenticate Jenkins users using the SSH authentication technique. You are familiar with SSH authentication, which was discussed in previous chapters of this book. The SSH authentication you need is a private key-public key pair.

First generate a new key pair using the following command:
ssh-keygen -m PEM -t rsa
Note that the –m PEM argument is used in the ssh-keygen -m PEM –t. rsa command. –m PEM will generate a private key in RSA format, whereas simple the SSH-Keygen command, without the –m PEM argument, generates a private key in the OpenSSH format. The Jenkins CLI client supports private keys in the RSA format, so don't forget to mention the –m argument in the command. Once the key pair is generated, you need to specify the public key on the Jenkins User Configuration page. Follow these steps to do this:
  1. 1.

    Click the username shown on top-right side of the Dashboard page and click the Configure link.

     
This will open a page on which you can configure details for the user, like the API token, the public key, etc.
  1. 2.

    Scroll down the page to find the SSH Public Keys section. Paste the public key you generated into the SSH Public Keys field.

     
  2. 3.

    Click the Save button.

     

Configuring an SSH Server in Jenkins

To access Jenkins using SSH authentication, you need to configure the SSH Server in Jenkins. First choose the Manage Jenkins➤Configure Global Security menu, which will take you to the Configure Global Security page.

Scroll down the page to find the SSH Server section near the end.

You need to set a port for the SSH connection. You have two options—Fixed and Random. If you select the Random radio control, the Jenkins server will select a random port to accept SSH connections. If we have a Firewall set up on the machine and need to allow incoming connections made on a specific port, then setting up an inbound rule for the random port will be difficult. If you select the Fixed radio button, you can use the port number of your choice. Jenkins will accept SSH connections on a given port. As the port is fixed, it would be easy to set up an inbound rule in a firewall. I selected the Fixed radio button and set it to 9090. Click the Save button.

Configuring an Inbound Rule in a Firewall

If a firewall is set up on the machine, you need to create an inbound rule so that incoming connections made at particular port/incoming connections from a particular program will be allowed. In this example, we are going to create an inbound rule for the SSH server port 9090.
  1. 1.

    Go to the Windows Defender Firewall with Advanced Security menu option from the Windows start menu.

     
  2. 2.

    Click the Inbound Rules option on left side.

     
  3. 3.

    Click the New Rule link on the right side, which will open the Rule Type window.

     
  4. 4.

    Select the Port radio button.

     
  5. 5.

    Click the Next button.

     
  6. 6.

    Select the Specific Local Ports radio button and enter 9090.

     
  7. 7.

    Click the Next button, which will open the Action window.

     
  8. 8.

    Click the Next button to see the Profile window.

     
  9. 9.

    Click the Next button to see the Name window.

     
  10. 10.

    Enter a name for the rule and click the Finish button.

     

How to Build Jobs with the Jenkins CLI Using SSH Authentication

This section explains how to build a Jenkins job using the Jenkins CLI command build.

The build command has the following optional command-line options:
  • -c: If you pass this option to the build command it checks if there are any changes on the SCM configured in the job and triggers the build only if there are changes.

  • -f: If you pass this option to the build command, it returns the exit code based on the outcome of the build. If the build is successful, it returns an exit code of 0.

  • -p: Using this option, you can pass parameters to a build in the Key=Value format.

  • -s: If you pass this option, then the build command will wait until the build completes/gets interrupted. If you do not set this option, the build command will trigger the build but will not wait until its completion.

  • -v: This option will print the console output of the build.

  • -w: This option will wait until the start of the command.

While running the build command, you need to authenticate the Jenkins user who will use the SSH authentication technique. To use Jenkins CLI with SSH authentication, you have the following two options:
  • Using an SSH client like OpenSSH/Putty

  • Using Jenkins-cli.jar

Using the OpenSSH Client to Run Jenkins CLI Commands

Let’s use the OpenSSH client to trigger a build using Jenkins CLI build command.

Open the command prompt and run the following command to run the build of the ReleaseCalculatorAPI job:
ssh ${JenkinsUserName}@${JenkinsServerIPAddress} -p ${JenkinsSSHPort} -i ${PrivateKeyFilePath} build ${JOB_NAME}
I replaced these placeholders with actual values and created the following command:
ssh [email protected] -p 9090 -i D:SSHKeyJenkinsCLI build ReleaseCalculatorAPI
Note

9090 is a port we configured under the SSH Server section in the Jenkins settings.

Pranodayd is a Jenkins user we are authenticating. D:SSHKeyJenkinsCLI is a file with the private key.

Run the following command from the command prompt:
ssh [email protected] -p 9090 -i D:SSHKeyJenkinsCLI build ReleaseCalculatorAPI

Go to the Jenkins dashboard page. You will see that the build for the ReleaseCalculatorAPI job was triggered.

Let’s run the build command again, but this time using the build command's options.
ssh [email protected] -p 9090 -i D:SSHKeyJenkinsCLI build ReleaseCalculatorAPI –s  -v –c

Go to the Jenkins Dashboard page and note that this time the build is not triggered, as we sent the –c option, which checks for changes in the SCM. Since there are no changes in the Git repository, the build is not triggered.

I changed version to 10.0 in pom.xml of the CalculatorAPI project and pushed this change to the Gitlab repository. Then I executed the same Jenkins CLI build command.

You can observe on the Jenkins dashboard that this time, the build was triggered and the console log of the build command was listed because you used the –v option.

Using the jenkins-cli.jar Client to Run Jenkins CLI Commands with SSH

You are already familiar with Jenkins-cli.jar, which you used to run Jenkins CLI commands using the HTTP connection mode. The previous section covered the SSH connection mode and you saw how the SSH client called OpenSSH to run the Jenkins CLI commands. This section explains how to use Jenkins-cli.jar to run Jenkins CLI commands using SSH authentication (SSH Connection mode).

If you are starting the Jenkins server on an IP address (i.e. non-default), then you need to start the Jenkins server with an argument named org.jenkinsci.main.modules.sshd.SSHD.hostName, which will include the IP address of the Jenkins machine as its value.

If you are using the Jenkins.war file to start the Jenkins server, you need to use the following command:
Java -Dorg.jenkinsci.main.modules.sshd.SSHD.hostName=<IPAddress> -jar <PATH of Jenkins jar> --httpListenAddress=<IPAddress>
I am using the following command:
Java -Dorg.jenkinsci.main.modules.sshd.SSHD.hostName=192.168.43.10 -jar D:jenkinsjenkins.war--httpListenAddress=192.168.43.10
Note

There should not be whitespace between - and D and -D and org.jenkinsci.main.modules.sshd.SSHD.hostName.

If you are starting Jenkins as a service, you need to go to the Jenkins.xml file and add this argument inside the <arguments> tag, as shown in Figure 19-1.

A screenshot of a notepad page in which, dash Dorg dot jenkins c i dot main dot modules dot S S H D dot hostname equals 192.168.43.10, is highlighted and boxed.

Figure 19-1

The Dorg.jenkinsci.main.modules.sshd.SSHD.hostName in Jenkins.xml

Restart the Jenkins service. Once the Jenkins server starts, either by using Jenkins.war or a Jenkins service, you can use Jenkins-client.jar to run the Jenkins CLI commands. You need to use the following command:
java -jar ${PATH of Jenkins-cli.jar} -s ${JENKINSURL} -i ${PrivateKeyPATH} -ssh -user ${UserName} ${Jenkins CLI command} ${CLI options}
I am using the following command to build the job named Demo:
java -jar  D:JenkinsBookExamplesjenkins-cli.jar -s http://192.168.43.10:8080 -ssh -user Pranodayd -i D:SSHKeyJenkinsCLI -p 9090 build Demo

Note that when you are using SSH connection mode, you need to specify -ssh in the command. If you are using -ssh then you must send the user ID with the -user option. By default, jenkins-cli.jar connects to the host and port that the Jenkins server is running on to get the SSH connection. But if you have set up a different port for SSH in the Jenkins server configuration (refer to previous sections of this chapter to learn how to set the SSHD port), as we set it to 9090, you need to specify the -p option in the command.

How to Export All Jobs

If you want to shift your Jenkins server from one machine to another, you need to export Jenkins jobs from the old machine before you discontinue it. Listing 19-1 is batch code that exports all Jenkins jobs in .XML files.
set JenkinsCLIJarLocation=D:JenkinsBookExamplesjenkins-cli.jar
set JenkinsURL=http://192.168.43.10:8080
FOR /F "tokens=*" %%g IN ('java -jar  %JenkinsCLIJarLocation% -s %JenkinsURL% -auth Pranodayd:Pranodayd@10 list-jobs') do (java -jar  %JenkinsCLIJarLocation% -s %JenkinsURL% -auth Pranodayd:Pranodayd@10 get-job %%g > %%g.xml)
Listing 19-1

Batch Code to Export all Jenkins Jobs

The batch code defines the variable JenkinsCLIJarLocation with the location of Jenkins-cli.jar. It defines the variable JenkinsURL as having the Jenkins URL. The following command returns all jobs using the Jenkins CLI command list-jobs:
java -jar  %JenkinsCLIJarLocation% -s %JenkinsURL% -auth Pranodayd:Pranodayd@10 list-jobs
The following command runs in a loop and iterates over job names returned by list-jobs. It exports the configuration of each job using the get-job Jenkins CLI command. It exports the configuration returned for each job in the .XML file using the > (the redirection symbol).
java -jar  %JenkinsCLIJarLocation% -s %JenkinsURL% -auth Pranodayd:Pranodayd@10 get-job %%g > %%g.xml

How to Import All Jobs

Once the jobs are exported in the form of .XML files from the old machines, you can copy the folder with all jobs exported to a new Jenkins server machine and run the batch shown in Listing 19-2.
set JenkinsCLIJarLocation=D:JenkinsBookExamplesjenkins-cli.jar
set JenkinsURL=http://192.168.43.10:8080
set JobsExportLocation=D:PD
FOR /F "delims=*" %%a IN ('dir /s /b %JobsExportLocation%*.xml') do java -jar  %JenkinsCLIJarLocation% -s %JenkinsURL% -auth Pranodayd:Pranodayd@10 create-job %%~na< %%a
Listing 19-2

Batch Code to Import All Jenkins Jobs

The batch code defines the variable JenkinsCLIJarLocation as having the location of Jenkins-cli.jar. It defines the variable JenkinsURL as having the Jenkins URL of the new machine

It defines the variable JobsExportLocation as having the path of the folder in which you exported the job XML files.

The following line returns an absolute location of each .XML file from the folder and will store it in a variable:
FOR /F "delims=*" %%a IN ('dir /s /b %JobsExportLocation%*.xml')

The following line runs the Jenkins CLI command create-job${JOB_NAME} < ${CONFIGURATIONFILE} in a loop.

JOB_NAME is extracted from the full path stored in variable a using ~na and CONFIGURATIONFILE is sent using variable a.
do java -jar  %JenkinsCLIJarLocation% -s %JenkinsURL% -auth Pranodayd:Pranodayd@10 create-job %%~na< %%a

Summary

This chapter explained how to interact with Jenkins server using its CLI (command-line interface) and how to use the Jenkins-cli.jar to interact with the Jenkins server by connecting using HTTP URL and SSH authentication. You also learned, with the help of code snippets, how to perform regular tasks like exporting Jenkins jobs using the Jenkins CLI.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.231.128