Jenkinsfile Not able to push docker image - jenkins-pipeline

I'm not able to push docker images into docker hub registry from jenkinsfile, i have created global credentials in jenkins with ID of dockerhub-id
stage('Push Docker Image') {
container('docker') {
withCredentials([usernamePassword(credentialsId: 'dockerhub-id', passwordVariable: 'docker-hub-password', usernameVariable: 'docker-hub-username')]) {
sh "docker login -u username -p ${dockerhub-id}"
sh "docker push username/${image_name}:${image_tag}"
build log
Successfully tagged palani160385/frontend-app:master-e002b6bd
[Pipeline] sh
+ docker tag frontend-app frontend-app:master-e002b6bd
[Pipeline] }
[Pipeline] // container
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Push Docker Image)
[Pipeline] container
[Pipeline] {
[Pipeline] withCredentials
Masking supported pattern matches of $docker-hub-username or $docker-hub-password
[Pipeline] {
[Pipeline] }
[Pipeline] // withCredentials
[Pipeline] }
[Pipeline] // container
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // podTemplate
[Pipeline] End of Pipeline
groovy.lang.MissingPropertyException: No such property: dockerhub for class: groovy.lang.Binding

Related

Malformed input or input contains unmappable characters when installing go-1.17 via Jenkins tool

Hi, i'm trying to set up go-1.17 env to a jenkins agent but i have an issue related to unmappable characters
Is there are any solution ?
Output:
Unpacking Go from https://golang.org/dl/go1.17.linux-amd64.tar.gz to /home/ubuntu/Jenkins/tools/org.jenkinsci.plugins.golang.GolangInstallation/go-1.17 on api2
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Also: hudson.remoting.Channel$CallSiteStackTrace: Remote call to JNLP4-connect connection from <some_ip>
at hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1797)
at hudson.remoting.UserRequest$ExceptionResponse.retrieve(UserRequest.java:356)
at hudson.remoting.Channel.call(Channel.java:1001)
at hudson.FilePath.act(FilePath.java:1165)
at hudson.FilePath.act(FilePath.java:1154)
at hudson.FilePath.installIfNecessaryFrom(FilePath.java:1010)
at hudson.FilePath.installIfNecessaryFrom(FilePath.java:946)
at org.jenkinsci.plugins.golang.GolangInstaller.performInstallation(GolangInstaller.java:57)
at hudson.tools.InstallerTranslator.getToolHome(InstallerTranslator.java:70)
at hudson.tools.ToolLocationNodeProperty.getToolHome(ToolLocationNodeProperty.java:107)
at hudson.tools.ToolInstallation.translateFor(ToolInstallation.java:220)
at org.jenkinsci.plugins.golang.GolangInstallation.forNode(GolangInstallation.java:44)
at org.jenkinsci.plugins.golang.GolangInstallation.forNode(GolangInstallation.java:22)
at org.jenkinsci.plugins.workflow.steps.ToolStep$Execution.run(ToolStep.java:155)
at org.jenkinsci.plugins.workflow.steps.ToolStep$Execution.run(ToolStep.java:136)
at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution.lambda$start$0(SynchronousNonBlockingStepExecution.java:47)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
java.nio.file.InvalidPathException: Malformed input or input contains unmappable characters: /home/ubuntu/Jenkins/tools/org.jenkinsci.plugins.golang.GolangInstallation/go-1.17/go/test/fixedbugs/issue27836.dir/Äfoo.go
Jenkinsfile
pipeline {
agent any
tools {
go 'go-1.17'
}
environment {
GO111MODULE = 'on'
}
stages {
stage('Setting up dependencies'){
steps {
echo 'Setting up dependencies'
sh 'go mod vendor'
}
}
stage('Build') {
steps {
echo 'Running build automation'
sh 'go build -o main'
}
}
}
}
Agent and master file encodings are UTF-8 (Checked via system information)
In the agent configuration click Advanced and in JWM Options type
-Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8
Then reconnect your agent and it will probably OK

Nexus Artifact Upload Plugin does not fail pipeline, if upload fails

I have created a declarative pipeline which
Builds the artifact using maven
Uploads the artifact to Nexus repository
Plugins Used-
Nexus Artifact Uploader Plugin
Nexus-
Sonatype Nexus OSS 3.17
But here, when the upload artifact to nexus repo fails, pipeline does not fail, it shows as success. I checked that many other people have reported this issue.
So can I add any workaround here, to fail my pipeline if upload fails?
I have attached the publish artifact stage and the screenshot
stage("Publish to Nexus") {
environment {
tag_version= sh (returnStdout: true, script: 'mvn -f core build-helper:parse-version help:evaluate -Dexpression=project.version -q -DforceStdout').trim()
}
steps {
sh 'echo "tag_version=$tag_version"'
script {
nexusArtifactUploader(
nexusVersion: NEXUS_VERSION,
protocol: NEXUS_PROTOCOL,
nexusUrl: NEXUS_URL,
groupId: "com.cable",
version: tag_version,
repository: NEXUS_REPOSITORY,
credentialsId: NEXUS_CREDENTIAL_ID,
artifacts: [
// Artifact generated such as .jar, .ear and .war files.
[artifactId: 'core',
classifier: '',
file: "./core/target/core-$tag_version-jar-with-dependencies.jar",
type: 'jar'],
]
);
}
}
}
Console Output
Failed to deploy artifacts: Could not transfer artifact com.cable:core:jar:8.6.1 from/to snapshots (https://nexus.yo-digital.com/repository/snapshots): Failed to transfer file: https://nexus.yo-digital.com/repository/snapshots/com/cable/core/8.6.1/core-8.6.1.jar. Return code is: 400, ReasonPhrase:Repository version policy: SNAPSHOT does not allow version: 8.6.1.
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // ws
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
I found that this is an issue with the plugin (Nexus Artifact Uploader). So in order to fail the pipeline if any such condition occurs, we can add a stage which will check the console output logs, and will fail the pipeline if any "error" string appears.
stage('Results')
{
steps
{
script
{
def logz = currentBuild.rawBuild.getLog(10000);
def result = logz.find { it.contains('Failed to deploy artifacts') }
if (result)
{
error (result)
}
}
}
}

Terraform is not recognized as internal or external command in jenkins

I installed jenkins in local windows machine. Then i installed terraform plug in and did the config changed in global tool configuration in jenkins but when i run the jenkin pipeline i get 'terraform' is not recognized as an internal or external command,
operable program or batch file.
Code :
pipeline {
agent any
stages {
stage('Hello') {
steps {
bat 'terraform --version'
echo 'Hello World'
}
}
}
}
can you help me what i am doing wrong in this?
Started by user admin
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in C:\Program Files (x86)\Jenkins\workspace\actimize2
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Hello)
[Pipeline] script
[Pipeline] {
[Pipeline] tool
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: No tool named terraform found
Finished: FAILURE
terraform config :
You'll need to get the Terraform home using a tool command and then add it to the Path environment variable so that the shell interpreterinvoked by bat can find the terraform command:
def tfHome = tool name: 'Terraform', type: 'com.cloudbees.jenkins.plugins.customtools.CustomTool'
env.Path = "${tfHome};${env.Path}"
In your pipeline, this would look like:
pipeline {
agent any
stages {
stage('Hello') {
steps {
def tfHome = tool name: 'Terraform', type: 'com.cloudbees.jenkins.plugins.customtools.CustomTool'
env.Path = "${tfHome};${env.Path}"
bat 'terraform --version'
echo 'Hello World'
}
}
}
}
You can also use tool directly in the bat command (this is what I used to do when I was using Jenkins regularly):
pipeline {
agent any
stages {
stage('Hello') {
steps {
bat "${tool name: 'Terraform', type: 'com.cloudbees.jenkins.plugins.customtools.CustomTool'}\terraform --version"
echo 'Hello World'
}
}
}
}
You can see a worked example in this Automating Terraform Projects with Jenkins article.

Jenkins Pipeline : docker not found with Maven docker image

I have a Jenkins pipeline which is running fine but it depends upon JDK and maven installed tools. There were few instances in the past that these JDK and maven tool's name was changed(e.g. Maven 3.6.2 -> Maven 3.6.3 and it results in my pipeline failure.
stage ("build") {
withMaven(jdk: 'Java SE 8u221', maven: 'Maven 3.6.3', tempBinDir: '') {
sh 'mvn clean package jib:dockerBuild verify'
}
}
I want my pipeline to be independent of what tools are installed. So I rewrite my Jenkins pipeline like below to provide docker image of maven(since JDK is bundled with it)
pipeline {
agent {
docker {
image 'maven:3-alpine'
args '-v /root/.m2:/root/.m2'
}
}
stages {
stage('Checkout') {
steps {
git branch: "master", url: "repo url", credentialsId: 'id'
}
}
stage ("build") {
steps {
sh 'mvn clean package jib:dockerBuild verify'
}
}
}
}
But now I am getting an error Failed to execute goal com.google.cloud.tools:jib-maven-plugin:2.3.0:dockerBuild (default-cli) : Build to Docker daemon failed, perhaps you should make sure Docker is installed and you have correct privileges to run it
It seems that docker daemon is not visible after I provided a maven docker image.
I did solve this by adding docker agent inside of my maven docker image
pipeline {
agent any
stages {
stage('build Dockerfile') {
steps {
sh '''echo "FROM maven:3-alpine
RUN apk add --update docker openrc
RUN rc-update add docker boot" >/var/lib/jenkins/workspace/Dockerfile'''
}
}
stage('run Dockerfile') {
agent{
dockerfile {
filename '/var/lib/jenkins/workspace/Dockerfile'
args '--user root -v $HOME/.m2:/root/.m2 -v /var/run/docker.sock:/var/run/docker.sock'
}
}
steps {
sh 'docker version'
sh 'mvn -version'
sh 'java -version'
}
}
}
}

Jenkins pipeline: use of a global variable within the pipeline

I've got a Jenkins pipeline with multiple stages, that will need to know how the build was triggered (by user, timer, etc.) and I'd like to avoid having to duplicate the following line in each stage:
currentBuild.rawBuild.getCauses()[0].class.getName().contains('TimerTriggerCause')
When using that command in each when blockm it works as expected, but when placed in the environment block it keeps failing:
[Pipeline] node
Running on Jenkins in /var/lib/jenkins/jobs/test-pipeline/workspace
[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Stage on timer)
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.lang.NoSuchMethodError: No such DSL method '$' found among steps [archive, bat, build, catchError...zip] or globals [currentBuild, docker, env, params, pipeline, scm]
at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:199)
at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:122)
at sun.reflect.GeneratedMethodAccessor513.invoke(Unknown Source)
Jenkins script:
pipeline {
agent {
label 'master'
}
environment {
DAY = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
HOUR = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
ONTIMER = currentBuild.rawBuild.getCauses()[0].class.getName().contains('TimerTriggerCause')
}
stages {
stage('Stage on timer') {
when {
expression {
return (${ONTIMER} && (${DAY} != Calendar.SATURDAY && ${DAY} != Calendar.SUNDAY))
}
}
steps {
echo "on timer..."
}
}
}
}
The 2 other variables DAY and HOUR do work fine when used in the when block. Any idea?
After some more trial and error, I got the behaviour I wanted.
The when condition when dealing with environmental variables uses a slightly different syntax. It has its own environment keyword to use then:
when {
environment name: 'ONTIMER', value: 'true'
}
As a bonus, using integer value as well in the when block:
when {
allOf {
environment name: 'ONTIMER', value: 'true'
expression { return Integer.parseInt(env.HOUR) < 11 }
}
}
Even better, it's possible to use the triggeredBy keyword and act on this:
when {
anyOf {
expression { return params.RUN }
allOf {
triggeredBy "TimerTrigger"
expression {
Integer.parseInt(env.HOUR) < 13
}
}
}
}
Values to be used with triggeredBy include:
TimerTrigger
UserId
(others? like SCM trigger?)

Resources