Jenkins CopyArtifact step - Unable to find project for artifact copy - jenkins

Based on this post, I'm trying to test this pipeline code in my environment:
pipeline {
agent any
stages {
stage ('push artifact') {
steps {
sh '[ -d archive ] || mkdir archive'
sh 'echo test > archive/test.txt'
sh 'rm -f test.zip'
zip zipFile: 'test.zip', archive: false, dir: 'archive'
archiveArtifacts artifacts: 'test.zip', fingerprint: true
}
}
stage('pull artifact') {
steps {
sh 'pwd'
sh 'ls -l'
sh 'env'
step([ $class: 'CopyArtifact',
filter: 'test.zip',
projectName: '${JOB_NAME}',
fingerprintArtifacts: true,
selector: [$class: 'SpecificBuildSelector', buildNumber: '${BUILD_NUMBER}']
])
unzip zipFile: 'test.zip', dir: './archive_new'
sh 'cat archive_new/test.txt'
}
}
}
}
but it gives the error message:
ERROR: Unable to find project for artifact copy: test
This may be due to incorrect project name or permission settings; see help for project name in job configuration.
Finished: FAILURE
How can I fix his pipeline code?

If you enable authorization(like rbac), you must grant permission 'Copy Artifact' to the project. In project configuration, General -> Permission to Copy Artifact, check the box and set the projects that can copy the artifact

Rather than using projectName: '${JOB_NAME}', what worked for me is using projectName: env.JOB_NAME. I.e. your complete copy-artifacts step would look like this:
step([ $class: 'CopyArtifact',
filter: 'test.zip',
projectName: env.JOB_NAME,
fingerprintArtifacts: true,
selector: [$class: 'SpecificBuildSelector', buildNumber: env.BUILD_NUMBER]
])
Or using the more modern syntax:
copyArtifacts(
filter: 'test.zip',
projectName: env.JOB_NAME,
fingerprintArtifacts: true,
selector: specific(env.BUILD_NUMBER)
)

Related

Making the jenkins build failure if cypress TC failure

Currently , my cypress testes are runnning in docker container on one stage
stage('Run E2E tests') {
steps {
withCredentials([
sshUserPrivateKey(credentialsId: '*********', keyFileVariable: 'SSH_KEY_FILE', usernameVariable: 'SSH_USER')
]) {
sh """
eval `ssh-agent -s`
ssh-add ${SSH_KEY_FILE}
~/earthly \
--no-cache \
--config=.earthly/config.yaml \
+e2e
eval `ssh-agent -k`
"""
}
}
}
And publishing the test report to via publishHTML.
post {
always {
echo "-- Archive report artifacts"
archiveArtifacts artifacts: 'results', allowEmptyArchive: 'true'
echo "-- Publish HTLM test result report"
publishHTML (target: [
allowMissing: false,
alwaysLinkToLastBuild: false,
keepAll: true,
reportDir: 'results/html/',
reportFiles: 'mochawesome-bundle.html',
reportName: "Test Result Report"
])
}
}
But i need to make the build failure if any of the TC failure in the cypress mocha report
what can be the solution for this..?
Thanks in advance

Caching downloaded browser in Jenkins declarative pipeline

Hi I have a project with e2e tests. The goal is to run these tests in jenkins many times. Before actuall running I have to install every time chrome browser. I mean exactly commands in JenkinsFile:
sh 'wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb'
sh 'apt-get update && apt-get install -y ./google-chrome-stable_current_amd64.deb'
In case when I will run this pipeline let's say 30 times in the minute then the browser will be downloaded 30 times from scratch. I would like to cache this browser. As I know I can achieve that with volumes.
My whole JenkinsFile with declarative syntax is:
pipeline {
agent {
docker {
registryCredentialsId 'dockerhub-read'
image 'node:17.3-buster'
args '-v $HOME/google-chrome-stable_current_amd64.deb:/root/google-chrome-stable_current_amd64.deb'
reuseNode true
}
}
parameters {
string(name: 'X_VAULT_TOKEN', defaultValue: '', description: 'Token for connection with Vault')
string(name: 'SUITE_ACCOUNT', defaultValue: '', description: 'Account on which scenario/scenarios will be executed')
string(name: 'Scenario', defaultValue: '', description: 'Scenario for execution')
choice(name: 'Environment', choices:
['latest', 'sprint', 'production (EU1)', 'production (EU3)', 'production (US2)', 'production (US8)', 'production (AU3)'],
description: 'Environment for tests')
}
options {
disableConcurrentBuilds()
}
stages {
stage("Initialize") {
steps {
sh 'wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb'
sh 'apt-get update && apt-get install -y ./google-chrome-stable_current_amd64.deb'
sh 'yarn install'
sh "./init.sh ${params.Environment} ${params.X_VAULT_TOKEN} ${params.SUITE_ACCOUNT}"
}
}
stage("Run Feature tests") {
steps {
echo 'Running scenario'
sh 'yarn --version'
sh 'node --version'
sh """yarn test --tags "#${params.Scenario}" """
}
}
}
}
I'm trying to add in docker section:
args '-v $HOME/google-chrome-stable_current_amd64.deb:/root/google-chrome-stable_current_amd64.deb'
based on section Caching data for containers in the article https://www.jenkins.io/doc/book/pipeline/docker/
This dosen't work. Browser downloads again and again. What's wrong?

How to view cypress mochawesome reports in jenkins after running test step inside docker container?

I'm running my cypress tests on Jenkins inside a dockerized container and I generate cypress mocha awesome report, but I don't know how to display it inside Jenkins.
This is my cypress.json content
{
"integrationFolder": "test/specs",
"supportFile": "test/support/index.js",
"video": true,
"reporter": "node_modules/cypress-multi-reporters",
"reporterOptions": {
"reporterEnabled": "mochawesome",
"mochawesomeReporterOptions": {
"reportDir": "results/mocha",
"overwrite": false,
"html": false,
"json": true,
"timestamp": "mmddyyyy_HHMMss",
"showSkipped": true,
"charts": true,
"quite": true,
"embeddedScreenshots": true
}
},
"screenshotOnRunFailure": true,
"screenshotsFolder": "results/mochareports/assets/screenshots",
"videosFolder": "results/mochareports/assets/videos",
"baseUrl": "http://testurl.com",
"viewportWidth": 1920,
"viewportHeight": 1080,
"requestTimeout": 10000,
"responseTimeout": 10000,
"defaultCommandTimeout": 10000,
"watchForFileChanges": true,
"chromeWebSecurity": false
}
And here is my scripts which I run locally.
"clean:reports": "rm -R -f results && mkdir results && mkdir results/mochareports",
"pretest": "npm run clean:reports",
"cypress:interactive": "cypress open",
"scripts:e2e": "cypress run",
"combine-reports": "mochawesome-merge results/mocha/*.json > results/mochareports/report.json",
"generate-report": "marge results/mochareports/report.json -f report -o results/mochareports -- inline",
"posttest": "npm run combine-reports && npm run generate-report",
"test:e2e": "npm run pretest && npm run scripts:e2e || npm run posttest",
I can view my generated report successfully in the local environment.
Here is my jenkinsfile content
#!groovy
pipeline {
agent any
stages {
stage('Checkout') {
steps {
echo 'Checking out the PR'
checkout scm
}
}
stage('Build') {
steps {
echo 'Destroy Old Build'
sh 'make destroy'
echo 'Building'
sh 'make upbuild_d'
}
}
stage('Test') {
steps {
echo 'Running Tests'
sh 'make test-e2e'
}
}
stage('Destroy') {
steps {
echo 'Destroy Build'
sh 'make destroy'
}
}
}
}
The make test-e2e actually runs the test:e2e script inside a docker container, the tests actually run and I can see the reports get generated on Jenkins but I don't know how to view it.
I need to view it in a separate inside Jenkins, also I don't know why I can't access it via Jenkins workspace.
btw. I'm adding the results file in .gitignore
This is my local report preview
You can use the HTML publisher plugin for Jenkins for this:
https://plugins.jenkins.io/htmlpublisher/
Within your Jenkinsfile add a stage to publish the HTML reports
e.g.
publishHTML([
allowMissing: false,
alwaysLinkToLastBuild: false,
keepAll: true,
reportDir: 'cypress/cypress/reports/html',
reportFiles: 'index.html',
reportName: 'HTML Report',
reportTitles: ''])
I used the HTML Publisher plugin as the mentioned solution above however my problem was that my results file was in the docker container not in Jenkins workspace and I fixed this problem by copying the folder from a docker container to Jenkins workspace.
docker cp container_name:/app/results ./results

gradle jenkins pipeline with codecov

I have a pipeline job for Spring and gradle:
pipeline {
agent any
triggers {
pollSCM '* * * * *'
}
tools {
jdk 'jdk-16'
}
stages {
stage('Build') {
steps {
sh 'java -version'
sh "chmod +x gradlew"
sh './gradlew assemble'
}
}
stage('Test') {
steps {
sh 'java -version'
sh "chmod +x gradlew"
sh './gradlew test'
}
}
stage('Publish Test Coverage Report') {
steps {
step([$class: 'JacocoPublisher',
execPattern: '**/build/jacoco/*.exec',
classPattern: '**/build/classes',
sourcePattern: 'src/main/java',
exclusionPattern: 'src/test*'
])
}
}
}
}
I am uploading the coverage it is available on the jenkins server, but I also want to upload it to codecov on the codecov page for jenkins and java there is a guide for freestyle job: https://about.codecov.io/blog/how-to-set-up-codecov-with-java-and-jenkins/
name: Jenkins CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
- name: Set up JDK 11
uses: actions/setup-java#v2
with:
java-version: '11'
distribution: 'adopt'
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Build with Gradle
run: ./gradlew clean build
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
- name: Run tests
run: ./gradlew clean build
- name: Coverage Report
run: ./gradlew jacocoTestReport
- name: Upload coverage to Codecov
uses: codecov/codecov-action#v1
with:
fail_ci_if_error: false
How can I integrate this in my pipline flow instead of a jenkins.yml file?
I ended up adding codecov commands to the Publish Test Coverage Report stage:
sh 'curl -Os https://uploader.codecov.io/latest/linux/codecov'
sh 'chmod +x codecov'
sh './codecov -t ${token}'
The Report Stage:
stage('Publish Test Coverage Report') {
steps {
step([$class: 'JacocoPublisher',
execPattern: '**/build/jacoco/*.exec',
classPattern: '**/build/classes',
sourcePattern: 'src/main/java',
exclusionPattern: 'src/test*'
])
sh 'curl -Os https://uploader.codecov.io/latest/linux/codecov'
sh 'chmod +x codecov'
sh './codecov -t ${TOKEN}'
}
}
It is the new beta Uploader that is replacing the deprecating bash. Commands for other OS: https://about.codecov.io/blog/introducing-codecovs-new-uploader/

How to use variable in Jenkins scripted pipeline?

I found Jenkins just ignore my variable ${BuildFolder}, thanks for the help.
node {
def BuildFolder = '/Build/${JOB_NAME}'+ '.' +'${BUILD_ID}'
stage ('prepare'){
sh "echo Build Folder: ${BuildFolder}"
sh "rm -rf ${BuildFolder} && mkdir -p ${BuildFolder}"
}
stage ('Checkout'){
checkout([$class: 'GitSCM',
branches: [[name: '*/master']],
doGenerateSubmoduleConfigurations: false,
extensions: [[$class: 'RelativeTargetDirectory',
relativeTargetDir: '${BuildFolder}']],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId: '',
url: '']]])
}
You can create variables before the pipeline block starts. Then it should be work.
For Example,
def BuildFolder = '/Build/${JOB_NAME}'+ '.' +'${BUILD_ID}'
node
{
stage ('prepare')
{
sh "echo Build Folder: ${BuildFolder}"
sh "rm -rf ${BuildFolder} && mkdir -p ${BuildFolder}"
}
}

Resources