How to integrate allure reports for automated tests in jenkins x

Loading scripts

The Pipeline DSL allows you to load other scripts, enabling sharing of build logic. Optionally the script can return a reference to itself, allowing you to store the script in a variable for later use.

  1. Configure the job and change the script to the following. The created script is executed immediately after loading.

  2. Configure the job and change the script to the following. The created script defines a method. The statement gives a reference to the Groovy Script Object to the caller, which can invoke it at any time.

Loading a script from another Git repository

This requires the Pipeline Remote File Loader plugin. The example assumes you have a repository somewhere that contains a file, which you want to download to your Jenkins workspace.

  1. Go to Manage Jenkins > Manage Plugins and install (without restart)

  2. Configure a Pipeline job and set the Pipeline script to the following:

script

script block helps us run Groovy code inside the Jenkins declarative pipeline.

pipeline {
agent any
parameters {
string(name: ‘NAME’, description: ‘Please tell me your name’)
choice(name: ‘GENDER’, choices: , description: ‘Choose Gender’)
}
stages {
stage(‘Printing name’) {
steps {
script {
def name = «${params.NAME}»
def gender = «${params.GENDER}»
if(gender == «Male») {
echo «Mr. $name»
} else {
echo «Mrs. $name»
}
}
}
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

pipeline{

agentany

parameters{

string(name’NAME’,description’Please tell me your name’)

choice(name’GENDER’,choices’Male’,’Female’,description’Choose Gender’)

}

stages{

stage(‘Printing name’){

steps{

script{

def name=»${params.NAME}»

def gender=»${params.GENDER}»

if(gender==»Male»){

echo»Mr. $name»

}else{

echo»Mrs. $name»

}

}

}

}

}

}

script block is wrapped inside the steps block. In the above example, we are printing the name passed as parameter suffixed with Mr. or Mrs. based on the Gender chosen.

We used build with parameters to pass params at the time of running the job.

Первый запуск пайплайна

На самом деле мы не полностью настроили конфиг пайплайна, т.к. часть параметров конфига хранятся в Jenkinsfile — скрипте в удаленном репозитории,который мы указали в п.6. Поэтому чтобы донастроить пайплайн необходимо выполнить пробный запуск. Для этого:

  1. В Веб-интерфейсе дженкинса на главной странице переходим в наш пайплайн erp_features
  2. В открывшемся окне нажимаем Build (Собрать сейчас) в левой командной панели и наблюдаем процесс сборки. Сборка должна будет упасть — это нормально.
  3. Обновляем браузер через f5 и видим, что теперь у нас вместо кнопки Build появится другая кнопка Build with parameters (Собрать с параметрами) — это как раз то, что нам нужно.

Static Code Analysis

Pep8/Flake8:

We use the ‘Pep8’ parser and the pattern is the path to the log file created by either pep8 or flake8. ‘unstableTotalAll’ = 0 makes sure the build is marked unstable if there is a single violation. If you want the build to fail on violations, use «failedTotalAll: ‘0’». It is not recommended to use any other threshold than ‘0’ for those settings.

TSLint:

timeout(time: 5, unit: 'MINUTES') {
  sh 'npm run lint:ci'
  step(],
    unstableTotalAll: '0',
    usePreviousBuildAsReference: true
  ])
}

There is no documentation whatsoever available of how to use this plugin with Jenkins pipelines. See this github commit. for details.

Serializing Local Variables

If you tried inlining the function as follows:

node('remote') {
  git url: 'https://github.com/jglick/simple-maven-project-with-tests.git'
  def matcher = readFile('pom.xml') =~ '<version>(.+)</version>'
  if (matcher) {
    echo "Building version ${matcher}"
  }
  def mvnHome = tool 'M3'
  sh "${mvnHome}/bin/mvn -B -Dmaven.test.failure.ignore verify"
  step([$class: 'ArtifactArchiver', artifacts: '**/target/*.jar', fingerprint: true])
  step([$class: 'JUnitResultArchiver', testResults: '**/target/surefire-reports/TEST-*.xml'])
}

you would have noticed a problem:

  • This occurs because the local variable is of a type () not considered serializable by Java.
    Since pipelines must survive Jenkins restarts, the state of the running program is periodically saved to disk so it can be resumed later
    (saves occur after every step or in the middle of steps such as ).

  • The “state” includes the whole control flow including: local variables, positions in loops, and so on. As such: any variable values used in your program should be numbers, strings, or other serializable types, not “live” objects such as network connections.

  • If you must use a nonserializable value temporarily: discard it before doing anything else.
    When you keep the matcher only as a local variable inside a function, it is automatically discarded as soon as the function returned.

You can also explicitly discard a reference when you are done with it:

node('remote') {
  git url: 'https://github.com/jglick/simple-maven-project-with-tests.git'
  def matcher = readFile('pom.xml') =~ '<version>(.+)</version>'
  if (matcher) {
    echo "Building version ${matcher}"
  }
  matcher = null
  def mvnHome = tool 'M3'
  sh "${mvnHome}/bin/mvn -B -Dmaven.test.failure.ignore verify"
  step([$class: 'ArtifactArchiver', artifacts: '**/target/*.jar', fingerprint: true])
  step([$class: 'JUnitResultArchiver', testResults: '**/target/surefire-reports/TEST-*.xml'])
}

However the safest approach is to isolate use of nonserializable state inside a method marked with the annotation .
Such a method will be treated as “native” by the Pipeline engine, and its local variables never saved.
However it may not make any calls to Pipeline steps, so the call must be pulled out:

node('remote') {
  git url: 'https://github.com/jglick/simple-maven-project-with-tests.git'
  def v = version(readFile('pom.xml'))
  if (v) {
    echo "Building version ${v}"
  }
  def mvnHome = tool 'M3'
  sh "${mvnHome}/bin/mvn -B -Dmaven.test.failure.ignore verify"
  step([$class: 'ArtifactArchiver', artifacts: '**/target/*.jar', fingerprint: true])
  step([$class: 'JUnitResultArchiver', testResults: '**/target/surefire-reports/TEST-*.xml'])
}
@NonCPS
def version(text) {
  def matcher = text =~ '<version>(.+)</version>'
  matcher ? matcher[]  null
}

Here the logic inside the function is run by the normal Groovy runtime, so any local variables are permitted.

The Pipeline: Groovy plugin page has deeper background on .

Меняемся к лучшему 1 — Настройка slave ноды дженкинса

После установки дженкинса мы получаем одну master ноду, запущенную как системный процесс. Но в приличном jenkins обществе принято использовать master ноду только в качестве менеджера slave агентов, а не ка запускалку пайплайнов. Поэтому чтобы не создавать на нее лишнюю нагрузку и не вешать ее в случае какого-либо неоптимального кода, заводятся slave ноды.

Для нас необходимость второй ноды обсусловлена еще и сугубо утилитарными нуждами — для правильной работы нашего пайплайна требуется нода, запущенная не как служба, а как консольное приложение. Дело в том, что ADD запускается в среде 1С со всем полагающимся графическим интерфейсом. Если мы будем запускать ADD под master нодой, то мы просто не увидим процесс выполнения ADD тестов на нашей машине (хотя это не помешает успешному выполнению тестов) Для простоты развернем slave на той же машине, на которой запущен и master. Итак, наши шаги будут следующими:

  1. Разрешаем запуск слейв агентов в качестве консольных приложений. Для этого в веб-интерфейсе дженкинса переходим в меню Manage Jenkins (Настроить Jenkins) => Configure Global Security (Глобальные настройки безопасности) => Agents и в поле TCP port for JNLP agents меняем переключатель на Fixed (Статичный) и указываем порт, например 10001.
  2. Добавляем ноду. Для этого переходим в меню Manage Jenkins (Настроить Jenkins) => Manage Nodes (Управление средами сборки) и в левой командной панели нажимаем New Node (Новый узел), вводим имя, активируем переключатель Permanent Agent и жмем ок.
  3. Вводим параметр ноды:
  • Name — имя хоста (компьютера)
  • Remote root directory (Корень удаленной ФС) — произвольный путь к каталогу, в котором дженкинс будет выполнять пайплайны, например D:\jenkins
  • Labels (Метки) — произвольное имя, по которому будем ссылаться на ноду в пайплайне. Рекомендую ставить такое же, как имя ноды.
  • Launch method (Способ запуска) — выбираем Launch agent via Java Web Start
  1. Жмем save

Теперь нужно поднять ноду:

В главном меню дженкинса в левой части должна появится иконка нашей новой ноды.

Кликаем на нее и смотрим на последнюю строчку. Это и есть командная строка запуска slave ноды.

  • Копируем командную строку и записываем ее в bat-ник, заодно скачиваем agent.jar по гиперссылке. Все это помещаем в каталог, который мы выделили ранее для slave дженкинса.
  • Добавляем строчку -Dfile.encoding=UTF-8  в строку запуска для правильной кодировки и запускаем bat-ник. Если все сделано правильно, то через пару секунд запустится консольная слейв нода.

  1. Самое время проверить работоспособность слейв ноды на нашем пайплайне. Для этого переходим к вводу входных параметров пайплайна, меняем параметр jenkinsAgent на label, который мы указали во время настройки ноды и запускаем пайплайн. В логах запущенной сборки можно увидеть, что пайплайн запустился на слейве

Build and Install

Like the Jenkins project itself, this project is a maven based project. To build this project, after you install maven and java 1.8 or later, and cd to this projects root directory (where the file is located), run . If built successfully, and file will reside in the subdirectory.

Aside from building the plugin locally, there are a few other ways to obtain built version of the plugin:

  1. The Centos and RHEL versions of the OpenShift Jenkins Docker Image, starting officially with V3.2 of OpenShift, will have the plugin installed. See the Jenkins Docker Image repository for details.

  2. A RHEL RPM is also available as of V3.2 of OpenShift.

Unless you are using a OpenShift Jenkins Docker Image with the plugin preinstalled, follow the Jenkins instructions for installing a plugin either by supplying the file, or by pulling it down from the Jenkins Update Center.

Issue

Problem description

// stage
}
$ E:\Jenkins\Slave1\tools\ru.yandex.qatools.allure.jenkins.tools.AllureCommandlineInstallation\C_Commons_Rep_allure_bin_\bin\allure.bat generate «E:\Jenkins\Slave1\workspace\KA_NightBuild\allure-results\Начальное заполнение информационной базы» «E:\Jenkins\Slave1\workspace\KA_NightBuild\allure-results\Обновление информационной базы при переходе на новую версию» «E:\Jenkins\Slave1\workspace\KA_NightBuild\allure-results\Проверка открытия печатных форм Администратор» «E:\Jenkins\Slave1\workspace\KA_NightBuild\allure-results\Проверка открытия печатных форм Бухгалтер Гладилина» «E:\Jenkins\Slave1\workspace\KA_NightBuild\allure-results\Проверка открытия печатных форм Производство Трудолюбов» «E:\Jenkins\Slave1\workspace\KA_NightBuild\allure-results\Проверка открытия форм созданием Администратор Федоров» «E:\Jenkins\Slave1\workspace\KA_NightBuild\allure-results\Проверка открытия форм созданием Бухгалтер Гладилина» «E:\Jenkins\Slave1\workspace\KA_NightBuild\allure-results\Проверка открытия форм созданием Кладовщик Волков» «E:\Jenkins\Slave1\workspace\KA_NightBuild\allure-results\Проверка открытия форм созданием Менеджер по закупкам Королев» «E:\Jenkins\Slave1\workspace\KA_NightBuild\allure-results\Проверка открытия форм созданием Менеджер по продажам Васечкин» «E:\Jenkins\Slave1\workspace\KA_NightBuild\allure-results\Проверка открытия форм созданием Петрищев Руководитель отдела продаж» «E:\Jenkins\Slave1\workspace\KA_NightBuild\allure-results\Проверка открытия форм созданием Толчеева Маркетолог» «E:\Jenkins\Slave1\workspace\KA_NightBuild\allure-results\Проверка открытия форм созданием Трудолюбов Производство» «E:\Jenkins\Slave1\workspace\KA_NightBuild\allure-results\Проверка сервисов ИТС Администратор Федоров» -c -o E:\Jenkins\Slave1\workspace\KA_NightBuild\allure-report
���誮� ������� �室��� ��ப�.
�訡�� � ᨭ⠪�� �������.
// withEnv
}
// node
End of Pipeline
ru.yandex.qatools.allure.jenkins.exception.AllurePluginException: Can not generate Allure Report, exit code: 255
at ru.yandex.qatools.allure.jenkins.AllureReportPublisher.generateReport(AllureReportPublisher.java:296)
at ru.yandex.qatools.allure.jenkins.AllureReportPublisher.perform(AllureReportPublisher.java:218)
at org.jenkinsci.plugins.workflow.steps.CoreStep$Execution.run(CoreStep.java:80)
at org.jenkinsci.plugins.workflow.steps.CoreStep$Execution.run(CoreStep.java:67)
at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution.lambda$start$0(SynchronousNonBlockingStepExecution.java:47)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Finished: FAILURE

Использование агента docker

Переходим к настройке нашего задания или создаем новое и приводим Groovy-код к такому виду:

pipeline {
    agent { docker { image ‘python:latest’ } }
    stages {
        stage(‘Подготовка’) {
            steps {
                sh «python —version»
            }
        }
        stage(‘Сборка’) {
            steps {
                echo ‘Выполняем команды для сборки’
            }
        }
        stage(‘Тестирование’) {
            steps {
                echo ‘Тестируем нашу сборку’
            }
        }
        stage(‘Развертывание’) {
            steps {
                echo ‘Переносим код в рабочую среду или создаем артефакт’
            }
        }
    }
}

* обратите внимание, мы изменили агента на docker с указанием образа, в котором будет выполняться обработка — в данном примере, с помощью python (последней версии). Также мы добавили этап Подготовка, в котором просто выведем на экран версию python

Первый запуск будет выполняться долго, так как необходимо будет загрузить образ. В конечном итоге, мы должны получить, примерно, следующую картину:

Для подробного просмотра хода процесса (или решения проблем в случае их возникновения), кликаем по стрелке справа от названия задания и переходим к сборке:

Переходим к консоли:

Если задание выполнено успешно, среди логов мы должны увидеть версию используемого в контейнере Docker python:

Wrapping Up!

Jenkins has a lot of potential in it. With the integration of various plugins and configuration of different platforms like LambdaTest integration with Jenkins; It provides different environments to create a build and facilitates various applications of continuous integration and continuous deployment.

However, setting up the environment variables is a crucial step in every use case provided by Jenkins. These variables maintain a lot of information required for a successful setup. These are accessed and injected in freestyle projects and pipelines to fulfil essential requirements of the build process and the test process. With Jenkins, we aim to create a robust product or software with excellent test resistance and performance. Thus, ensure that the required Jenkins environment variables are set and can be accessed wherever and whenever necessary.

Also, don’t forget to leave your comments, and if you have any query or question, shoot up to the LambdaTest community and get it resolved.

Till then, Happy Testing!

Praveen Mishra

Praveen is a Computer Science Engineer by degree, and a Digital Marketer by heart who works at LambdaTest. A social media maven, who is eager to learn & share about everything new & trendy in the tech domain.

Marking build as Unstable

There are scenarios where we don’t want to mark build as failure but want to mark build as unstable.

Example- When test case coverage doesn’t cross the threshold we expect, we can mark the build as UNSTABLE.

pipeline {
agent any
tools {
maven ‘MAVEN_PATH’
jdk ‘jdk8’
}
stages {
stage(«Tools initialization») {
steps {
sh «mvn —version»
sh «java -version»
}
}
stage(«Checkout Code») {
steps {
git branch: ‘master’,
url: «https://github.com/iamvickyav/spring-boot-data-H2-embedded.git»
}
}
stage(«Building Application») {
steps {
sh «mvn clean package»
}
}
stage(«Code coverage») {
steps {
jacoco(
execPattern: ‘**/target/**.exec’,
classPattern: ‘**/target/classes’,
sourcePattern: ‘**/src’,
inclusionPattern: ‘com/iamvickyav/**’,
changeBuildStatus: true,
minimumInstructionCoverage: ’30’,
maximumInstructionCoverage: ’80’)
}
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

pipeline{

agentany

tools{

maven’MAVEN_PATH’

jdk’jdk8′

}

stages{

stage(«Tools initialization»){

steps{

sh»mvn —version»

sh»java -version»

}

}

stage(«Checkout Code»){

steps{

git branch’master’,

url»https://github.com/iamvickyav/spring-boot-data-H2-embedded.git»

}

}

stage(«Building Application»){

steps{

sh»mvn clean package»

}

}

stage(«Code coverage»){

steps{

jacoco(

execPattern’**/target/**.exec’,

classPattern’**/target/classes’,

sourcePattern’**/src’,

inclusionPattern’com/iamvickyav/**’,

changeBuildStatustrue,

minimumInstructionCoverage’30’,

maximumInstructionCoverage’80’)

}

}

}

}

Sample can be found here at .

jacoco() is a special method which helps us configure Jacoco reports including the minimum & maximum coverage threshold. In the above example, min coverage (minimumInstructionCoverage) check is set as 30 & max coverage (maximumInstructionCoverage) check is set as 80.

So if the code coverage is-

Less than 30 – Build will be marked as Failure.Between 30 & 80 – Build will be marked as Unstable.Above 80 – Build will be marked as Success.

Triggers / Scheduling

Trigger build regularly with cron:

pipeline {
    agent any
    triggers {
        cron('H */4 * * 1-5')
    }
    stages {
        stage('Example') {
            steps {
                echo 'Hello World'
            }
        }
    }
}

Triggers Pipeline Syntax docs: .

Paremeterized Trigger / Cron:

pipeline {
    agent any
    parameters {
      string(name: 'PLANET', defaultValue: 'Earth', description: 'Which planet are we on?')
      string(name: 'GREETING', defaultValue: 'Hello', description: 'How shall we greet?')
    }
    triggers {
        cron('* * * * *')
        parameterizedCron('''
# leave spaces where you want them around the parameters. They'll be trimmed.
# we let the build run with the default name
*/2 * * * * %GREETING=Hola;PLANET=Pluto
*/3 * * * * %PLANET=Mars
        ''')
    }
    stages {
        stage('Example') {
            steps {
                echo "${GREETING} ${PLANET}"
                script { currentBuild.description = "${GREETING} ${PLANET}" }
            }
        }
    }
}

Reading Jenkins Environment Variables

In this section, we will see how you can read your Jenkins environment variables list. Let’s take it one step at a time-

  1. To access the Jenkins environment variables in a pipeline, you can use the env object, eg. env.BUILD_NUMBER will give the current build number of a pipeline. The reference to Jenkins pipeline environment variables is made by surrounding it by ${} in the following way: ${env.BUILD_NUMBER}
  2. You can also use the short version, which is BUILD_NUMBER. But this variant is quite confusing for some users. The script to read the build number via environment variables is :

pipeline{
agent any

stages{
stage(«Env Build Number»){
steps{
echo «The build number is ${env.BUILD_NUMBER}»
echo «You can also use \${BUILD_NUMBER} -> ${BUILD_NUMBER}»
}
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12

pipeline{

agentany

stages{

stage(«Env Build Number»){

steps{

echo»The build number is ${env.BUILD_NUMBER}»

echo»You can also use \${BUILD_NUMBER} -> ${BUILD_NUMBER}»

}

}

}

}

The console output of the build processed via the above script is :

Issue: Jenkins UI does not populate Allure Test report even though Test Result is populated

Problem description

Describe your problem in a meaningful way:

  • what were you doing:
    We are having a Jenkins pipeline script defined for running TesNG Tests in remote system and Generate Allure report then publish it in Jenkins UI as part of Job triggered, from the TestNG Test Result

  • what was expected: In Jenkins UI:
    Part of Job triggered, the Allure report to be published,
    In Jenkins Job workspace both Test result and report folder should get populated.

  • what occurred finally
    Part of Job triggered, the Allure report is not getting published,
    In Jenkins Job workspace only Test result gets populated and no report folder is getting populated.

Logs & Traces

}
// dir
}
// stage
stage
{ (RUN_AUTOMATION)
dir
Running in /var/jenkins_home/workspace/RSMP/REMS_CI/CI_Workspace
{
echo
TRIGGERING TEST AUTOMATION
sh

  • cd Ansible_PlayBooks/Deploy-REMS-Automation
  • ansible-playbook Run_Automation.yml

PLAY ******************************************

TASK *********************************************************
ok:

TASK *******************************************************************
changed:

PLAY *************************************************

TASK *******************************************************************
changed:

PLAY **************************************************

TASK *****************************************************************
: The value True (type bool) in a string field was converted to
u’True’ (type string). If this does not look like what you expect, quote the
entire value to ensure it does not change.
changed:

TASK *******************************************************************
changed:

PLAY RECAP *********************************************************************
10.89.159.83 : ok=5 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

sh

  • cp -f /Test-Results.zip Ansible_PlayBooks/Deploy-REMS-Automation/
    sh
  • cd Ansible_PlayBooks/Deploy-REMS-Automation
  • unzip -o Test-Results.zip
    Archive: Test-Results.zip
    creating: Test-Results/Allure-Results/
    inflating: Test-Results/Allure-Results/26ad1616-5694-4135-812f-83b406f9d0e0-container.json
    inflating: Test-Results/Allure-Results/385b9b37-7929-4a50-b6f6-8b6592af6a30-result.json
    inflating: Test-Results/Allure-Results/005847ca-765e-40ff-ae9f-c7ec7cb75196-container.json
    inflating: Test-Results/Allure-Results/4d0bf4f5-5d8a-4adb-b14a-d2d058efd4d0-container.json
    inflating: Test-Results/Allure-Results/d399faa8-c787-485d-bcfe-33d54fe087aa-result.json
    inflating: Test-Results/Allure-Results/5e7aa288-8211-446e-9172-fd1fbf2ebbf9-container.json
    inflating: Test-Results/Allure-Results/222fad59-53a9-40e8-bcd5-f7368f746032-container.json
    inflating: Test-Results/Allure-Results/c48769ba-341d-407d-863b-1be16849dcd7-container.json
    inflating: Test-Results/Allure-Results/f2370b71-b5b8-4e97-960b-c0618348f147-container.json
    inflating: Test-Results/Allure-Results/26d96196-b56a-4857-9f46-0d38649520de-container.json
    sh
  • ls -la Ansible_PlayBooks/Deploy-REMS-Automation/Test-Results
    total 4
    drwxr-xr-x. 3 root root 36 Nov 19 06:32 .
    drwxr-xr-x. 4 root root 274 Nov 19 06:32 ..
    drwxrwxr-x. 2 root root 4096 Nov 19 01:32 Allure-Results
    }
    // dir
    }
    // stage
    stage
    { (PUBLISH_RESULTS)
    echo
    PUBLISHING TEST RESULTS ON JENKINS
    dir
    Running in /var/jenkins_home/workspace/RSMP/REMS_CI/CI_Workspace
    {
    echo
    Publishing Allure Report
    publishHTML
    Archiving HTML reports…
    Archiving at BUILD level /var/jenkins_home/workspace/RSMP/REMS_CI/CI_Workspace/Ansible_PlayBooks/Deploy-REMS-Automation/Test-Results/Allure-Report to /var/jenkins_home/jobs/RSMP/jobs/REMS_CI/builds/133/htmlreports/TestResultsAllureReport
    ERROR: Specified HTML directory ‘/var/jenkins_home/workspace/RSMP/REMS_CI/CI_Workspace/Ansible_PlayBooks/Deploy-REMS-Automation/Test-Results/Allure-Report’ does not exist.
    }
    // dir
    dir
    Running in /var/jenkins_home/workspace/RSMP/REMS_CI/CI_WorkspaceJenkins pipeline script.txtJenkins pipeline script.txt

_

Установка плагина

При установке Jenkins система по умолчанию предлагает установить плагин pipeline. Вероятно, в нашей системе он есть. Но если плагин не установлен, переходим на стартовой странице веб-интерфейса Jenkins в раздел Настроить Jenkins:

Кликаем по Управление плагинами:

Переходим на вкладку Доступные и ищем нужный нам плагин по слову «pipeline». Мы получим большое количество результатов — нам нужен плагин с названием «Pipeline»:

Внизу экрана нажимаем Install without restart:

Мы увидим полный список компонентов, которые нужно будет установить для плагина — дожидаемся окончания процесса (мы должны увидеть «Успешно» или «Success»):

* в процессе установки плагина могут появиться сообщения об ошибках. Проблемы могут быть связаны с расхождением версий зависимых компонентов или необходимостью перезагрузки. Так или иначе, просматриваем такие сообщения и самостоятельно пытаемся в них разобраться.

После завершения установки, можно вернуться на главную страницу, кликнув по одноименной ссылке:

Наша система готова для создания конвейера.

post

post block contains additional actions to be performed on completion of the pipeline execution. It can contain one or many of the following conditional blocks – always, changed, aborted, failure, success, unstable etc.

post block conditions

always – run this post block irrespective of the pipeline execution statuschanged – run this post block only if the pipeline’s execution status is different from the previous build run. E.g., the build failed at an earlier run & ran successfully this time.aborted – if the build is aborted in the middle of the run. Usually due to manual stopping of the build runfailure – if the build status is failuresuccess – if the build ran successfullyunstable – build is successful but not healthy. E.g. On a particular build run, test cases ran successfully, but test coverage % is less than expected, then the build can be marked as unstable

Example-

pipeline {
agent any
stages {
stage(‘build step’) {
steps {
echo «Build stage is running»
}
}
}
post {
always {
echo «You can always see me»
}
success {
echo «I am running because the job ran successfully»
}
unstable {
echo «Gear up ! The build is unstable. Try fix it»
}
failure {
echo «OMG ! The build failed»
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

pipeline{

agentany

stages{

stage(‘build step’){

steps{

echo»Build stage is running»

}

}

}

post{

always{

echo»You can always see me»

}

success{

echo»I am running because the job ran successfully»

}

unstable{

echo»Gear up ! The build is unstable. Try fix it»

}

failure{

echo»OMG ! The build failed»

}

}

}

Sample can be found here at .

Создание и настойка задания

На главной странице Jenkins кликаем по Создать Item:

Даем название нашей задаче и ниже выбираем Pipeline:

Нажимаем кнопку OK:

Прокручиваем страницу вниз до подраздела «Pipeline» — сюда мы пишем скрипт на Groovy:

Также у нас есть возможность использовать репозиторий Git в качестве источника файла Jenkinsfile, выбрав в подразделе «Definition» Pipeline script from SCM и Git:

… но мы в данной инструкции будем рассматривать написание кода напрямую в Jenkins.

Для начала, напишем приветствие:

pipeline {
    agent any
    stages {
        stage(‘Hello’) {
            steps {
                echo ‘Hello World’
            }
        }
    }
}

Существует 2 способа написания pipeline — скриптовый и декларативный. В нашем примере используется последний. Благодаря строгому синтаксису, он проще читается — в декларативном пайплайне обязательно должны быть:

  1. Директива pipeline. В нее мы оборачиваем наш код.
  2. Определение агента. В нашем примере пока не задан конкретный (agent any), но ниже мы рассмотрим запуск конвейера в docker.
  3. Необходима директива stages, в которой, в свою очередь, определены стадии (stage).
  4. Обязательно указываем steps, в котором и будет наш код.

А также:

  • Экранирование некоторых символов можно сделать с помощью обратного слеша — \
  • Блок текста, например для его написания в несколько строк, можно обернуть в три одинарные кавычки — »’
  • Оставить комментарий на одну строку можно двумя прямыми слешами — //
  • Блок комментария делаем так — /* комментарий */

И нажимаем Сохранить:

* наш скрипт на Groovy будет сохранен в так называемый Jenkinsfile — это файл, в котором мы описываем этапы выполнения нашего задания с использованием pipeline.

Нас перекинет на страницу задания — слева кликаем по Собрать сейчас:

Конвейер немного поработает и выдаст результат, состоящий из одного шага:

Созданное задание работает — попробуем его усложнить.

Рейтинг
( Пока оценок нет )
Понравилась статья? Поделиться с друзьями:
Мой редактор ОС
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: