Don’t be a tool man. Touching hands teaches you Jenkins!

Time:2021-2-27

Hello everyone, I’m a piece of cake, a piece of cake eager to be Cai Bucai in the Internet industry. Soft or hard, praise is soft, white whoring is just!Ghost ~ remember to give me a third company after watching it!

Don't be a tool man. Touching hands teaches you Jenkins!

This article mainly introducesJenkins

If necessary, please refer to

If it helps, don’t forgetgive the thumbs-up

The official account of WeChat has been opened.A good story of a small dishIf you don’t pay attention, remember to pay attention!

“Well, after submitting the code every day, you have to package it and deploy it to the test environment and development environment. What a hassle! It’s going to be “operation and maintenance.”

“Ah? oh Indeed, every day’s packaging and deployment has become a tool man. “

A simple conversation quickly disappeared in the office, but it caused me to think, “such a troublesome process must have a good solution, after all, programmers areLazy programmingI’m rightJenkinsI’ve heard about this tool for a long time. It seems that I have to learn about it todayStart“It’s over.”

Do as you say. Let’s have a look todayJenKinsAfter watching, you might as well give your whole project and add more to yourselfPaddleTime of the day!

Don't be a tool man. Touching hands teaches you Jenkins!

Note before reading:This article is long, from installation to use, step by step to take you super God!

WeChat official account: [Xiaocai Liangji], take you to appreciate the technology style!

1、 What is Jenkins

Jenkins is aOpen source softwareThe project is based onjavaA method of developmentContinuous integrationTools, used to monitor continuous and repetitive work, aims to provide an open and easy-to-use software platform, making continuous integration of software possible.

In a nutshell, it is oneContinuous integrationMy tools!

1. Continuous integration

Continuous integration(continuous integration)CI. Before integrating the code into the trunk frequently, we must pass the automatic test. As long as one test case fails, we cannot integrate. Through continuous integration, teams can quickly move from one function to another.

Don't be a tool man. Touching hands teaches you Jenkins!

Benefits:

  • Reduce risk, because of continuous integration to build, compile and test, you can find problems early
  • Reduce repetitive work
  • Continuous deployment, providing deployable unit package
  • Continuous delivery of available versions

2. Jenkins continuous integration

Don't be a tool man. Touching hands teaches you Jenkins!

Let’s look at this picture firstJenkinsIt plays an important role in this process

  • First, the developer submits the code to theGitWarehouse
  • thenJenkinsuseGitPlug in to pullGitWarehouse code, and then cooperateJDK、MavenAnd other software to complete code compilation, testing, review, testing and packaging
  • lastJenkinsThejar/warPush toTest / production serverFor users to access

As a developer, we just need to submit the code, and the rest of the work is left to usJenkinsIt’s so beautiful. Why didn’t you get on the car earlier!

2、 Jenkins installation

Sharpening a knife doesn’t miss a woodcutter. No matter how much it is, it’s empty. Let’s take a look firstJenkinsHow to install it!

1. Install JDK

becauseJenkinsyesjavaWrite, so to run it must be configuredjavaRunning environment. There is no need to talk about the installation process of JDK

2. Download and install Jenkins

  • download

We can go to the download page and select the version we want to installDownload addressThe version we use here is:jenkins-2.190.3-1.1.noarch.rpm

  • install

And then download itrpmThe package is uploaded to our server viarpm -ivh jenkins-2.190.3-1.1.noarch.rpmInstall and editetcUnder the directoryjenkinsProfile:vim /etc/sysconfig/jenkinsThe following points need to be changed (or you can choose not to change them)

 JENKINS_USER=”root”

 JENKINS_PORT=”8888″

  • start-up

systemctl start jenkins

  • visit

Access via browserHttp: / / server IP: 8888/, see the following page to show that the startup is successful

Don't be a tool man. Touching hands teaches you Jenkins!

Then we get the password from the specified file on the server and proceed to the next step.

In this step, we can skip the plug-in installation first, becauseJenkinsThe plug-in needs to be downloaded from the default official website, which is very slow

Don't be a tool man. Touching hands teaches you Jenkins!

Then we add an administrator account to manage:

Don't be a tool man. Touching hands teaches you Jenkins!

The following page indicates that the setting is successful:

Don't be a tool man. Touching hands teaches you Jenkins!

WeChat official account:A good story of a small dish, take you to appreciate the technology style!

3、 Jenkins uses

1. Plug in acceleration

Sharp tools make good work

Sweet side dishes will not let you suffer the pain of waiting. First of all, let’s enterJenkins -> Manage Jenkins -> Manage Plugins, clickinstall

Don't be a tool man. Touching hands teaches you Jenkins!

And then we’re installing itJenkinsEnter the/var/lib/jenkins/updatesDirectory, you can see that there is adefault.jsonDocuments,Step one:We need to replace some of the fields. The input command is as follows:

sudo sed -i ‘s#updates.jenkins.io/download/plugins#mirrors.tuna.tsinghua.edu.cn/jenkins/plugins#g’ default.json && sudo sed -i ‘s#www.google.com#www.baidu.com#g’ default.json

Step 2:We entered into the/var/lib/jenkinsContents, editinghudson.model.UpdateCenter.xmAnd put it insidehttps://updates.jenkins.io/update-center.jsonAmend to readhttp://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/update-center.json

Last step:Enter the following command to restartJenkins

systemctl restart jenkins

Through the above steps, we can happily install the plug-in!

2. User management

stayJenkinsIn this case, we need to use plug-insRole-based Authorization Strategy

  • Install firstRole-based Authorization Strategyplug-in unit

Don't be a tool man. Touching hands teaches you Jenkins!

  • Enable global security configuration

Don't be a tool man. Touching hands teaches you Jenkins!

Switch authorization policy to"Role-Based Strategy"

Don't be a tool man. Touching hands teaches you Jenkins!

  • Create user

After changing the authorization policy, we can create a user and enter theManage Users

Don't be a tool man. Touching hands teaches you Jenkins!

Here we create two users, which arecbuc1andcbuc2

Don't be a tool man. Touching hands teaches you Jenkins!

  • Creating roles

Create a good user, we can create a role, in the system management page to enterManage and Assign Roles

Don't be a tool man. Touching hands teaches you Jenkins!

The roles are mainly divided intoGlobal rolesandItem roles

Global roles:Advanced users such as administrators can create global based roles

Item roles:Roles for one or more projects

Don't be a tool man. Touching hands teaches you Jenkins!

Our system now has two users, and then we can bind the corresponding roles to these two users

Don't be a tool man. Touching hands teaches you Jenkins!

3. Voucher management

What is a voucher?voucherIt can be used to store database passwords that need ciphertext protection,GitLabPassword information,DockerLogin password of the private warehouse. After saving this information,JenkinsYou can interact with these third-party applications. Of course, it has to be helpedJenkinsPlug in!

1) Installation

Install firstCredentials Bindingplug-in unit

Don't be a tool man. Touching hands teaches you Jenkins!

After the plug-in is installed, there will be more than one in the first menu bar of the systemvouchermenu

Don't be a tool man. Touching hands teaches you Jenkins!

Click in, we can see the voucher that can be added5Species:

Don't be a tool man. Touching hands teaches you Jenkins!

  1. Username with password: user name and password
  2. SSH Username with private key:useSSHUser and key
  3. Secret file:Text files that need to be kept confidential, when usedJenkinsThe file will be copied to a temporary directory, and then the file path will be set to a variableSecret fileIt will be deleted
  4. Secret text:Need to save an encrypted string of text, such as the nail robot orGitHubOfapi token
  5. Certificate:By uploading the certificate file

We usually use the following types:Username with passwordandSSH Username with private key

2) Git voucher management

If we want to useJenkinsfromGitLabPull the project code, we have to use the certificate to verify.

  • installGitplug-in unit

We need to be hereJenkinsInstallation inGit plug inTo pull the project code

Don't be a tool man. Touching hands teaches you Jenkins!

Then we need to install it on the serverGit tools

Installation command

 yum install git -y

Verify command

 git –version

1. Mode 1: user password type

We can use itUser passwordAfter logging in, pull the project code, which we need to use at this timeThe user name with password type of the credential

Don't be a tool man. Touching hands teaches you Jenkins!

Don't be a tool man. Touching hands teaches you Jenkins!

If it is created successfully, we can test whether it is available. Let’s create one firstFreestyle project

Don't be a tool man. Touching hands teaches you Jenkins!

And then in theGitLabCopy our project inURL

Don't be a tool man. Touching hands teaches you Jenkins!

stayCredentialsSelect the voucher we just created in the. After saving the configuration, we clickBuild NowTo build a project:

Don't be a tool man. Touching hands teaches you Jenkins!

At this time, you can see the output on the console

Don't be a tool man. Touching hands teaches you Jenkins!

Then enter the/var/lib/jenkins/workspaceYou can see the items we pulled in the directory:

Don't be a tool man. Touching hands teaches you Jenkins!

It shows that we have successfully used itUser passwordVoucher mode pull toGit project

2. Mode 2: SSH key type

In addition to using the account password to verifyGitWe can also use itSSH keyThe procedure is as follows:

Don't be a tool man. Touching hands teaches you Jenkins!

As we can see from the figure, the first step is to generatePublic private keyWe’re hereJenkins serverEnter the following command to generate:

ssh-keygen -t rsaAfter inputting the command, press enter all the way to enter the/root/.ssh/Generate public and private keys in the directory:

Don't be a tool man. Touching hands teaches you Jenkins!

  • id_rsa: private key file
  • id_rsa.pub: public key file

Then we put the generated public key in theGitLabIn the middle,Log in to root account, click avatar, settings, SSH keys, copyid_rsa.pubContent in, click“Add key”

Don't be a tool man. Touching hands teaches you Jenkins!

And then we go backJenkinsTo add a voucher to the system page, selectSSH Username with private keyTo copy the contents of the private file just generated

Don't be a tool man. Touching hands teaches you Jenkins!

After adding, a voucher will be generated

Don't be a tool man. Touching hands teaches you Jenkins!

If it is created successfully, we can test whether it is available. Let’s create one firstFreestyle project

Don't be a tool man. Touching hands teaches you Jenkins!

And then in theGitLabCopy our project inURL

Don't be a tool man. Touching hands teaches you Jenkins!

stayCredentialsSelect the voucher we just created in the. After saving the configuration, we clickBuild NowTo build a project:

Don't be a tool man. Touching hands teaches you Jenkins!

At this time, you can see the output on the console

Don't be a tool man. Touching hands teaches you Jenkins!

Then enter the/var/lib/jenkins/workspaceYou can see the items we pulled in the directory:

Don't be a tool man. Touching hands teaches you Jenkins!

It shows that we have successfully used itSSH Username with private keyVoucher mode pull toGit project

4. Project management

1) Maven installation

Most of the projects we are developing areMavenProject, usingMavenProject, we need to carry outDependency managementSo we should install it on the serverMavenTo download project dependencies.

  • Install maven

We can start fromMavenDownload the compressed package from the official website, and then upload it to the server for decompression

tar -xzf apache-maven-3.6.0-bin.tar.gz

  • Configure environment variables

vim /etc/profile

export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk
 export MAVEN_HOME=/home/maven/apache-maven-3.6.2
 export PATH=$PATH:$JAVA_HOME/bin:$MAVEN_HOME/bin

To make the profile effective after editing:

source /etc/profile

verification:

mvn -v

Then set it upMavenOfsettings.xml

#Create local warehouse directory

Change the local warehouse to:/root/repo/

Add Alibaba cloud private service address:alimaven aliyun maven http://maven.aliyun.com/nexus/content/groups/public/ central

  • Jenkins configuration

stayJenkinsWe also need configurationJDKandMavenThe relationship between the two

get intoJenkins -> Global Tool Configuration -> JDK

Don't be a tool man. Touching hands teaches you Jenkins!

get intoJenkins -> Global Tool Configuration -> Maven

Don't be a tool man. Touching hands teaches you Jenkins!

Add global variable

get intoManage Jenkins->Configure System->Global Properties, add three global variables

JAVA_HOME、M2_HOME、PATH+EXTRA

Don't be a tool man. Touching hands teaches you Jenkins!

Then we go into the project and clickconfigure

Don't be a tool man. Touching hands teaches you Jenkins!

Then addshellExecute script:

Don't be a tool man. Touching hands teaches you Jenkins!

After saving, rebuild and view the console, you can seemvnSuccessful construction:

Don't be a tool man. Touching hands teaches you Jenkins!

2) War package deployment

If our project is in the form of war package, we need to use thetomcatContainer to run, then we first need to install onetomcat

Tomcat installation

We’ll download it in advanceTomcatThe installation package is uploaded to the server through thetar -xzf apache-tomcat-8.5.47.tar.gzUnzip and runbinUnder the directorystart.shstart-upTomcatIf you see the following results, the startup is successful:

Don't be a tool man. Touching hands teaches you Jenkins!

Next, we need to configure Tomcat user role permissions. By default, Tomcat does not configure user role permissions

First of all, we need to modify ittomcat/conf/tomcat-users.xmlFile:

Don't be a tool man. Touching hands teaches you Jenkins!

(copy) as follows:

<role rolename="tomcat"/>
 <role rolename="role1"/>
 <role rolename="manager-script"/>
 <role rolename="manager-gui"/>
 <role rolename="manager-status"/>
 <role rolename="admin-gui"/>
 <role rolename="admin-script"/>
 <user username="tomcat" password="tomcat" roles="manager-gui,manager-script,tomcat,admin-gui,admin-script"/>

Then modify it/tomcat/webapps/manager/META-INF/context.xmlThe following contents are annotated:

Don't be a tool man. Touching hands teaches you Jenkins!

Then entertomcatPage, click to enter:

Don't be a tool man. Touching hands teaches you Jenkins!

Account and passwordtomcat

Don't be a tool man. Touching hands teaches you Jenkins!

The success page is as follows:

Don't be a tool man. Touching hands teaches you Jenkins!

So we’re donetomcatThen you can deploy it

Tomcat deployment
  • stayjenkinsInstallation inDeploy to containerplug-in unit
  • add toTomcatvoucher

Don't be a tool man. Touching hands teaches you Jenkins!

  • Build configuration

At the end of the projectconfigureMedium configuration

Don't be a tool man. Touching hands teaches you Jenkins!

Then click build to view the console output:

Don't be a tool man. Touching hands teaches you Jenkins!

Display that the deployment has been successful, and then visit the project page to seewarPackage project deployed successfully:

Don't be a tool man. Touching hands teaches you Jenkins!

3) Jar package deployment

That’s itwarPackage project is how to deploy, but we now use the project more or lessSpringBootAt this time, it isjarType, butSpringBootIt’s built intomcatContainer, so we don’t have to rely on the outsidetomcatThe use of the container.

Don't be a tool man. Touching hands teaches you Jenkins!

  • First of all, we are hereJenkinsDownload fromMavenPlug in. When creating a new project, there will be a plug-inMavenProject options

Don't be a tool man. Touching hands teaches you Jenkins!

And then at the end of the projectconfigureThe configuration is as follows:

Don't be a tool man. Touching hands teaches you Jenkins!

Repository URL: library addressCredentials: voucherBranch Specifier (blank for ‘any’): Branch

Don't be a tool man. Touching hands teaches you Jenkins!

Run only if build succeeds: follow up steps when the build is successfulAdd post-build step: add post build stepsSend files or execute commands over SSH: send file or execute command through SSH

  • installPublish Over SSHplug-in unit

Because the server we are going to deploy is the same as theJenkinsNot on the same server, so we need this plug-in for remote deployment

After installing the plug-in, we need to configure the remote server firstJenkinsInput on the serverSSH copy ID remote server IPCopy the public key to the remote server, and thenJenkinsAdd server information to the system configuration as follows:

Don't be a tool man. Touching hands teaches you Jenkins!

After completing the above steps, we can go back to the beginning of the projectconfigureAdd the server information we just configured to the

Don't be a tool man. Touching hands teaches you Jenkins!

Name: server configured in SSH serversSource files: source fileRemove prefix: remove prefixRemote directory: the directory uploaded to the serverExec command: script to execute

Complete the above steps, we can click happilyBuild NowIt’s over!

Don't be a tool man. Touching hands teaches you Jenkins!

4) Assembly line project

JenkinsThere are many types of automatic construction projects in, including the following three types:

  • Freestyle project
  • Maven project
  • Pipeline project

In fact, each type of construction can complete the same construction process and result, but there are some differences in operation mode and flexibility. Among them, the pipeline type has higher flexibility, and the other two types have been tried in the above examples. Let’s introduce how to build a pipeline project.

1. Concept

PipelineIt’s a system that runs inJenkinsThe workflow framework based on, which connects the original independent operation with the tasks of single or multiple nodes, realizes the complex process choreography and visualization that single task is difficult to complete

2. Advantages
  • codePipelineImplemented in code form, usually checked into source code control, enabling the team to edit, review, and iterate its delivery process.
  • persistence:Whether it is a planned or unplanned server restart,PipelineIt’s all recoverable
  • Can stop: PipelineInteractive input can be received to determine whether to proceedPipeline
  • multi-function: PipelineSupporting complex continuous delivery requirements in the real world, it supportsfork/join, loop execution and parallel execution
  • Scalable: PipelineThe plug-in supports itsDSLAnd multiple options for integration with other plug-ins
3. Create

establishPipelineWe need to install before the projectPipelineplug-in unit:

Don't be a tool man. Touching hands teaches you Jenkins!

Then there will be more when creating projectsPipelineType:

Don't be a tool man. Touching hands teaches you Jenkins!

After selecting the project type, we can select theconfigureIt is configured as follows:

  • First of all, the configuration is the same as beforegitThe address is the same as the above. I don’t want to make too much fuss here
  • Then configurePipelinescript

PipelineThe project is passed uniformlyPipelineScript to manage, which also better improve the flexibility

Hello WorldTemplate:

 pipeline {

  agent any

  stages {

  stage(‘Hello’) {

  steps {

  echo ‘Hello World’

  }

  }

  }

 }

stages:Represents all the execution phases of the entire pipeline, usuallystagesThere is only one, which contains multiple stages

stage:Represents the logic to be executed in a phase,stepsIt’s insideshellscript,gitPull code,sshRemote publishing, etc

Declarative pipelineTemplate:

pipeline {

You don’t have to worry about not being able to write at allPipelineScript, we can click[Pipeline Syntax]Jump toPipeline code generation page

Don't be a tool man. Touching hands teaches you Jenkins!

Don't be a tool man. Touching hands teaches you Jenkins!

After writing the script, click build to see the whole build process

Don't be a tool man. Touching hands teaches you Jenkins!

If we need to deploy to different environments, such as production environment and development environment, we can also deploy in theconfigureTo configure in:

  • You need to install it firstExtended Choice Parameterplug-in unit
  • Then add theExtended Choice Parameterparameter

Don't be a tool man. Touching hands teaches you Jenkins!

After completing the above configuration, click save. At this time, we can select the server to be deployed during construction

Don't be a tool man. Touching hands teaches you Jenkins!

Then we can start fromPipelineIn the script, read our selected parameters and paste the construction script of the project as follows:

Don't be a tool man. Touching hands teaches you Jenkins!

node {

Another situation is if you deployJenkinsIf your server goes down, it will be lost at this timePipelineScript file, rewriting is a very troublesome thing, so we can put the script file in the root directory of our project, and thenconfigureMedium configurationPipelineLocation of script file:

Don't be a tool man. Touching hands teaches you Jenkins!

Don't be a tool man. Touching hands teaches you Jenkins!

Then we click build, and we can see that the result is also successful

Don't be a tool man. Touching hands teaches you Jenkins!

5) Building triggers

Above, we have talked about several ways to build projects, all of which are built by manually clicking build. We can also build projects by triggers

Don't be a tool man. Touching hands teaches you Jenkins!

Commonly used are:

1. Build After Other Projects Are Built

Don't be a tool man. Touching hands teaches you Jenkins!

Other projects are triggered after construction. In the options, fill in the items we are concerned about. There are also three choices for you to choose from:

Trigger only if build is stable:Execute only when the project is stable build

Trigger even if the build is unstable:Even if the construction of the project is unstable, it can be executed

Trigger even if the build fails:Execute even if the project fails to build

2. Build Periodically

Don't be a tool man. Touching hands teaches you Jenkins!

Build on time. Grammatical types such ascronThe timing string from left to right is:Time sharing day month week

3. Poll SCM

Polling SCM. Specify the time to scan the code of the local code warehouse for changes. If the code changes, the project construction will be triggered.

Don't be a tool man. Touching hands teaches you Jenkins!

4. Trigger builds remotely

Don't be a tool man. Touching hands teaches you Jenkins!

Remote trigger build. By using the key we defined and then accessing the build address:http://192.168.100.131:8888/job/test01/build?token=123123

5. Automatic trigger construction

What we saw just now wasJenkinsIn the built-in build trigger of,Polling SCMIt can be realizedGitlabCode update and project automatic construction, but the performance of this scheme is poor. Is there a better plan? yes , we have. It’s usingGitlabOfwebhookImplementation codepushTo the warehouse, immediately trigger the automatic construction of the project.

Don't be a tool man. Touching hands teaches you Jenkins!

To complete the auto trigger build, we need toJenkinsTo install the plug-in:GitLab HookandGitLab

Don't be a tool man. Touching hands teaches you Jenkins!

And then we’re inBuild TriggerYou can see one more option:

Don't be a tool man. Touching hands teaches you Jenkins!

Copy this stringWebHookAddress, followGitLabPage settings:

Path steps:Admin Area -> Settings -> Network

Don't be a tool man. Touching hands teaches you Jenkins!

Then we set it in the corresponding project

Don't be a tool man. Touching hands teaches you Jenkins!

Finally, back toJenkinsMake the following configuration in the page:Manage Jenkins->Configure System

Don't be a tool man. Touching hands teaches you Jenkins!

Finish the above configuration, we can happily code for automatic trigger build!

END

This article is long, full of dry goods, from installation to use, step by step to take you intoOperation and maintenanceThe pit, learn this quickly to your project use it! It’s a long way to go. I’ll search with you!

Don't be a tool man. Touching hands teaches you Jenkins!

Today’s you work harder, tomorrow’s you will be able to say less words to ask for help!

I am Xiaocai, a man who studies with you.

The official account of WeChat has been opened.A good story of a small dishIf you don’t pay attention, remember to pay attention!