How make dynamic change stage name in Jenkinsfile Declarative pipeline? - jenkins

I have Jenkinsfile (Scripted Pipeline)
def template1 = "spread_sshkeys"
node {
// Clean before build
stage('Checkout') {
deleteDir()
checkout scm
sh "git submodule foreach --recursive git pull origin master";
}
stage("import template ${template1}") {
script{
sh "ls -las; cd jenkins-ci-examples; ls -las";
jenkins_ci_examples.sub_module = load "jenkins-ci-examples/${template1}"
}
}
stage("run template ${template1}") {
sh "echo ${jenkins_ci_examples.sub_module}";
}
}
after want to Converting to Declarative
def template1 = "spread_sshkeys"
pipeline {
agent any
stages {
stage ("Checkout") {
steps {
deleteDir()
checkout scm
sh "git submodule foreach --recursive git pull origin master"
}
}
stage("import template ${template1}") {
steps {
script {
sh "ls -las; cd jenkins-ci-examples; ls -las";
jenkins_ci_examples.sub_module = load "jenkins-ci-examples/${template1}"
}
}
}
stage("run template ${template1}") {
steps {
sh "echo ${jenkins_ci_examples.sub_module}";
}
}
}
}
After start Jenkins Job stop and return Error
WorkflowScript: 22: Expected string literal # line 22, column 19.
stage("import template ${template1}") {
^
WorkflowScript: 30: Expected string literal # line 30, column 19.
stage("run template ${template1}") {
^
Try to use
stage('run template ${template1}')
and else
stage('run template '+template1)
returned error too.
How solve this problem?

You can create dynamic stages using sequential stages as below:
def template1 ="spread_sshkeys"
pipeline {
agent any
stages {
stage('Dynamic Stages') {
steps {
script {
stage("import template ${template1}"){
println("${env.STAGE_NAME}")
}
stage("run template ${template1}"){
println("${env.STAGE_NAME}")
}
}
}
}
}
}

Related

How to add a jmeter build step to jenkins pipeline when using jmeter maven plugin

I have two stages on jenkins pipeline, and it is expecting to add steps in execute jmeter stage
Could someone help to resolve this....
I got below error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 339: Expected one of "steps", "stages", or "parallel" for stage "Execute Jmeter" # line 339, column 9.
stage('Execute Jmeter') {
Below is the code snippet of jenkins pipeline:
pipeline {
agent {
label 'qatest'
}
tools {
maven 'Maven'
jdk 'JDK8'
}
environment {
VIRTUOSO_URL = 'qa.myapp.com'
}
stages {
stage('BUILD') {
steps {
sh 'mvn clean verify'
}
}
stage('Execute Jmeter') {
post{
always{
dir("scenarioLoadTests/target/jmeter/results/"){
sh 'pwd'
sh 'mv *myapp_UserLoginAndLogout.csv UserLoginAndLogout.csv '
sh 'mv *myapp_myappPortfolioScenario.csv myappPortfolioScenario.csv '
sh 'mv *myapp_myappDesign.csv myappDesign.csv '
perfReport '*.csv'
}
}
}
}
}
}
Shouldn't you use script blocks like:
pipeline {
agent {
label 'qatest'
}
tools {
maven 'Maven'
jdk 'JDK8'
}
environment {
VIRTUOSO_URL = 'qa.myapp.com'
}
stages {
stage('BUILD') {
steps {
script { // <----------------- here
sh 'mvn clean verify'
}
}
}
stage('Execute Jmeter') {
post {
always {
dir('scenarioLoadTests/target/jmeter/results/') {
script { <-------------------------------------- and here
sh 'pwd'
sh 'mv *myapp_UserLoginAndLogout.csv UserLoginAndLogout.csv '
sh 'mv *myapp_myappPortfolioScenario.csv myappPortfolioScenario.csv '
sh 'mv *myapp_myappDesign.csv myappDesign.csv '
perfReport '*.csv'
}
}
}
}
}
}
}
More information:
Pipeline Maven Integration
Running a JMeter Test via Jenkins Pipeline - A Tutorial

Error WorkflowScript: 8: Expected one of "steps", "stages", or "parallel" for stage "check out scm" when need to run a pipeline

I write this pipeline for run that after push on the develop branch or master branch and doing some workers related to that branch.
I want to check the repository and run pipeline after push on the any branches
pipeline {
triggers {
pollSCM('*/1 * * * * ')
}
agent any
stages {
stage('Check out scm') {
when {
branch 'master'
}
checkout scm
}
stage('Install npm') {
steps {
sh 'npm install'
}
}
stage('Build Project Develop') {
when {
branch 'develop'
}
steps {
sh 'ng build --prod '
}
}
stage('Build Project Realase')
{
when {
branch 'master'
}
steps {
sh 'ng build --prod '
}
}
stage('Move to Var') {
steps {
sh 'chown -R root:jenkins /var/lib/jenkins/workspace/Angular-CI-CD--Test_master/dist/ang-CICD/. && /var/www/html'
}
}
}
}
But it shows me this error:
Branch indexing
Connecting to https://api.github.com using kiadr9372/****** (GitHub Access Token)
Obtained Jenkinsfile from d57840a79c46a88969381cc978f378c7d6804cec
Running in Durability level: MAX_SURVIVABILITY
GitHub has been notified of this commit’s build result
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 8: Unknown stage section "checkout". Starting with version 0.5, steps in a stage must be in a ‘steps’ block. # line 8, column 9.
stage('check out scm') {
^
WorkflowScript: 8: Expected one of "steps", "stages", or "parallel" for stage "check out scm" # line 8, column 9.
stage('check out scm') {
^
What is the problem?
Solution
You need to place checkout scm within a step closure. You also have an additional closing bracket.
pipeline {
triggers {
pollSCM('*/1 * * * * ')
}
agent any
stages {
stage('check out scm') {
when {
branch 'master'
}
steps {
checkout scm
}
}
stage('Install npm') {
steps {
sh 'npm install'
}
}
stage('Build Project Develop') {
when {
branch 'develop'
}
steps {
sh 'ng build --prod '
}
}
stage('Build Project Realase') {
when {
branch 'master'
}
steps {
sh 'ng build --prod '
}
}
stage('Move to Var') {
steps {
sh 'chown -R root:jenkins /var/lib/jenkins/workspace/Angular-CI-CD--Test_master/dist/ang-CICD/. && /var/www/html'
}
}
}
}

Jenkins "No such DSL method 'steps' found among steps"

Jenkins output error..
[Checks API] No suitable checks publisher found.
java.lang.NoSuchMethodError: No such DSL method 'steps' found among steps
My jenkinsfile.
node {
stage('Clone repository') {
checkout scm
}
stage('Build packer') {
steps {
dir('packer') {
sh 'git clone https://github.com/changhyuni/packer'
sh 'packer build ec2.json'
}
}
}
stage('Build image') {
app = docker.build("475667265637.dkr.ecr.ap-northeast-2.amazonaws.com/chang")
}
stage('Create ECR') {
sh 'pip3 install boto3 --upgrade'
sh 'python3 ecr.py'
}
stage('Push image') {
sh 'rm ~/.dockercfg || true'
sh 'rm ~/.docker/config.json || true'
docker.withRegistry('https://475667265637.dkr.ecr.ap-northeast-2.amazonaws.com', 'ecr:ap-northeast-2:chang-aws-ecr') {
app.push("chang")
app.push("${env.BUILD_NUMBER}")
app.push("latest")
}
}
}
steps is a directive from declarative syntax https://www.jenkins.io/doc/book/pipeline/syntax/#steps
Your example is scripted syntax https://www.jenkins.io/doc/book/pipeline/syntax/#scripted-pipeline

Is it possible to check if checked out from a specific repository in a Jenkins declarative pipeline?

I would like to have a release stage in my Jenkinsfile that only runs when it's checked out from the original repository. This is to avoid error messages on cloned repositories, because of missing keys etc. there.
stage('Release')
{
when
{
allOf
{
// TODO Check for repository url https://github.com/PowerStat/TemplateEngine.git
branch 'master'
}
}
steps
{
script
{
if (isUnix())
{
sh 'mvn --batch-mode release:clean'
sh 'mvn --batch-mode release:prepare'
sh 'mvn --batch-mode release:perform'
}
else
{
bat 'mvn --batch-mode release:clean'
bat 'mvn --batch-mode release:prepare'
bat 'mvn --batch-mode release:perform'
}
}
}
}
I have studied Pipeline Syntax: when but have no idea how to do the test I would like to have.
Also I thought about using an environment variable Global Variable Reference, but found non with the repository URL in it.
So my question is: how to implement this check in a decalarative pipeline?
You can get remote repository URL from git config remote.origin.url command. You can execute this command using expression directive inside the when block - it defines a closure that returns a boolean value.
Consider the following example:
def expectedRemoteUrl = "https://github.com/PowerStat/TemplateEngine.git"
pipeline {
agent any
stages {
stage("Release") {
when {
allOf {
branch 'tmp'
expression {
def remoteUrl = isUnix() ?
sh(script: "git config remote.origin.url", returnStdout: true)?.trim() :
bat(script: "git config remote.origin.url", returnStdout: true)?.trim()
return expectedRemoteUrl == remoteUrl
}
}
}
steps {
echo "Do your release steps here..."
}
}
}
}
Alternatively, if git command is not available in the node that runs the pipeline, you can get the remote repository URL with scm.userRemoteConfigs?.first()?.url. Consider the following example:
def expectedRemoteUrl = "https://github.com/PowerStat/TemplateEngine.git"
pipeline {
agent any
stages {
stage("Release") {
when {
allOf {
branch 'tmp'
expression {
def remoteUrl = scm.userRemoteConfigs?.first()?.url
return expectedRemoteUrl == remoteUrl
}
}
}
steps {
echo "Do your release steps here..."
}
}
}
}

Jenkinsfile - use Global properties in post

Here is my Jenkinsfile for multi-branch pipeline project:
pipeline {
agent any
stages {
stage('MASTER build') {
when {
branch 'master'
}
steps {
sh 'mvn -P x clean deploy'
}
}
stage('BRANCH build') {
when {
not { branch 'master' }
}
steps {
sh 'mvn -P x clean package'
}
}
}
post {
failure {
emailext "${EMAIL_TEMPLATE}"
}
}
}
When I build my project in Jenkis following error occurs:
WorkflowScript: 26: Step does not take a single required parameter - use named parameters instead # line 26, column 13.
emailext "${EMAIL_TEMPLATE}"
Why I cant use EMAIL_TEMPLATE global variable containing all emailext definition?

Resources