Why does retry not working in my Jenkins pipeline? - jenkins

Jenkins v2.263.3
I have the following code that just aims to upload a zip file to our private Nexus repo. I want it to try 3 times. Note all the variables used are defined somewhere else in the script, and are all valid.
withCredentials([[$class: 'UsernamePasswordMultiBinding',
credentialsId:'nexus-user',
usernameVariable: 'NEXUS_USR',
passwordVariable: 'NEXUS_PW']]) {
final Integer maxTries = 3
Integer numTries = 1
retry(maxTries) {
timeout(time: 5) { // Timeout in minutes
println "Trying $numTries/$maxTries upload to file server."
numTries++
sh """
curl -v -u $NEXUS_USR:$NEXUS_PW --upload-file $artifact $remoteUrl/$remoteDir/$artifact
"""
}
}
}
However, when the pipeline just quits if it fails after the first try, that is, it just ignores the retry{} block. What am I missing?

Related

Use GITHUB_ACCESS_TOKEN in Jenkins inside docker for authentication

I've followed the solution provided by #biolauri in this post, in using GITHUB_ACCESS_TOKEN in Jenkins inside a docker container. Below is my stage code:
stage('Push git tag') {
agent { label 'docker' }
steps {
script {
try {
container = docker.build("git", "-f git.dockerfile .")
container.inside {
withCredentials([usernamePassword(
credentialsId: "<credential-name-stored-in-jenkins>",
usernameVariable: "GITHUB_APP",
passwordVariable: "GITHUB_ACCESS_TOKEN")]) {
withEnv(["GITHUB_TOKEN=$GITHUB_ACCESS_TOKEN"]) {
sh "git tag ${version_g}"
sh "git push origin ${version_g}"
}
}
}
} catch (Exception e) {
// sh "git tag -d ${version_g} || true"
throw e
}
}
}
}
But I am still getting this error:
fatal: could not read Username for 'https://github.com': No such
device or address
What am I doing wrong here?
Just to make sure that I am getting the correct Github App ID, I actually echoed it and it is indeed the correct Github App ID. And I also echoed the generated GITHUB_ACCESS_TOKEN, and it indeed looks like a generated token. But the docker image built seems to be not recognizing the GITHUB_TOKEN environment variable set, to be able to do a git push

Jenkins Pipeline Displays Password in Plaintex

I am retrieving the username password from the credentials plugin.
The values are then saved as environmental variables. I am using the password in later stages of the pipeline, in sh block as an argument for curl.
At this point the password is displayed in plaintext in the build logs. Is there a way to avoid this? I assumed by using the credentials plugin the password will be masked.
pipeline {
stages {
stage ('One') {
steps {
withCredentials([userNamePassword(credentialsId: 'my_cred', userNameVariable: 'User_Name', passwordVariable: 'Password')]){
env.User_Name = User_Name
env.Password = Password
}
}
}
stage ('Two') {
sh '''
curl -v -u ${User_Name}:${Password} ...
'''
}
}
}
Note: I am using the curl to upload a file to a remote host.
Thats true. The password will be displayed in plaintext.
The best way for your request, ist to use the HTTP Request Plugin.
You can pass credentials in "Authorization" in the Header inestead of URL.
I ended up using the curl inside the withCredentialsblock.
withCredentials([userNamePassword(credentialsId: 'my_cred', userNameVariable: 'User_Name', passwordVariable: 'Password')]){
sh '''
curl -v -u ${User_Name}:${Password} ...
'''
}

How to invoke Jenkins credentials in a jenkins scripted pipeline (not declarative)

i am trying to use jenkins scripted pipeline to invoke config file provider plugin along with fetching credentials from jenkins for the username and password, but the below doesn't seem to work.
node {
def mvnHome
def mvnSettings
stage('Prepare') {
mvnHome = tool 'maven-3.5.4'
}
stage('Checkout') {
checkout scm
}
stage('Deploy'){
def usernameLocal, passwordLocal, usr, psw
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'xyz', passwordVariable: 'PASSWORD', usernameVariable: 'USERNAME']]) {
usernameLocal = env.USERNAME
passwordLocal = env.PASSWORD
}
configFileProvider(
[configFile(fileId: '*********', variable: 'MAVEN_SETTINGS', replaceTokens: true)])
{
usr="${usernameLocal}"
psw="${passwordLocal}"
sh "echo $usr"
sh "'${mvnHome}/bin/mvn' -s $MAVEN_SETTINGS deploy -Dserver.username="${usernameLocal}" -Dserver.password="${passwordLocal}""
}
}
}
where server.username and server.password are defined as properties under settings.xml server section for username and password.
Looks like i found out the issue and its nothing to do with withCredentials used here rather to do with the config file provider plugin. So i am able to print the credentials username correctly but somehow the config file provider is unable to substitute the variable value in the settings.xml.
so i don't get any error anymore, its just that the deployment doesn't go through with 401 unauthorized since the below in my settings.xml never gets the correct values :-
<server>
<id>snapshot</id>
<username>${server.username}</username>
<password>${server.password}</password>
</server>
Could you please advise how to resolve this?
The variables created by withCredentials are Groovy variables not environment variables. Try the following:
stage('Deploy'){
withCredentials([usernamePassword(credentialsId:'xyz', passwordVariable: 'Password', usernameVariable: 'Username')]) {
configFileProvider([configFile(fileId: 'abcde', variable:'MAVEN_SETTINGS')]) {
sh "'${mvnHome}/bin/mvn' -s $MAVEN_SETTINGS deploy -Dserver.username=${Username} -Dserver.password=${Password}"
}
}
}
Ok I figured out the solution, declare the configFileProvider entire section under the block of withCredentials and pass:
-Dserver.username='${usernameLocal}' -Dserver.password='${passwordLocal}'
(Please note single quotes). This way the values also get substituted and are outputted in the logs as masked.

enviroment variables on jenkins pipeline for user and password

I´m quite new on using groovy for jenkins pipeline. I have a pipeline that is already running performing some steps like running unitest, sonnarqube anaysis etc. One of the steps is to upload artifact to artifactory using curl -u. I don´t want to show user and pass on output script, so I´m using credential plug in In which I stored user and password and has the ID. But I don´t know how to pass that to the sh command using variables. This is what I have now in that step using withCredentials .
stage ('Upload war to Artifactory') {
withCredentials([usernamePassword(credentialsId: '7c9e8186-1f16-4920-837b-b571ea88a7e8', usernameVariable: 'willy11', passwordVariable: 'hello123')])
sh "sudo curl -u ${willy11}:{$hello123} -T $warPath 'https://artifactory.xxxxx.com:443/artifactory/Platform/$warFile'"
I don´t know how to pass or define values of usernameVariable and passwordVariable to use on the curl command. The way it is now, I get on output script:
java.lang.IllegalStateException: **There is no body to invoke**
at org.jenkinsci.plugins.workflow.cps.CpsStepContext.newBodyInvoker(CpsStepContext.java:283)
at org.jenkinsci.plugins.workflow.cps.CpsStepContext.newBodyInvoker(CpsStepContext.java:95)
How can I achieve this? the credential plug in, I read that supposedly puts *** on the output of the script, is this how this work? should I declare "will11" and "hello123" elsewere and use as env variables?
Thank you.
def call(body) {
def config = [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config
body()
def artifactName = 'extractor'
def artifactExt = '.war'
def artifactVersion = '0.0.1'
def buildPath = 'target/'
def warFile = artifactName + '-' + artifactVersion + artifactExt
def warPath = buildPath + warFile
def warNoVersion = artifactName + artifactExt
def deployPath = '/var/lib/tomcat8/webapps/'
def deployFile = deployPath + warNoVersion
node {
// Clean workspace before doing anything
//deleteDir()
try {
stage ('Code Checkout') {
git branch: 'master',
credentialsId: 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
url: 'ssh://git#bitbucket.org/xxxxxxx/xxxxxxxctor'
}
stage ('Configure Application') {
configFileProvider([configFile(fileId: config.confiFileId, variable: 'CONFIG_FILE_PATH')]) {
sh 'cp $CONFIG_FILE_PATH resources/config.properties'
}
sh "echo 'job_name: $JOB_NAME' > WebContent/version.txt"
sh "echo 'job_number: $BUILD_NUMBER' >> WebContent/version.txt"
}
stage ('Run Unitests') {
sh 'mvn test'
}
/*stage ('SonarQube analysis') {
withSonarQubeEnv('xxxxxxxxxxxxxxxx) {
sh 'mvn sonar:sonar'
}
}*/
stage ('Compile and Build WAR') {
sh 'mvn clean compile war:war'
}
stage ('Upload war to Artifactory') {
withCredentials([usernamePassword(credentialsId: '7c9e8186-1f16-4920-837b-b571ea88a7e8', usernameVariable: 'USER', passwordVariable: 'PASSWORD')])
sh "sudo curl -u ${USER}:{$PASSWORD} -T $warPath 'https://artifactory.xxxxxxx.com:443/artifactory/Platform/$warFile'"
}
} catch (err) {
notifyBuild('FAILURE', config.slackChannel)
throw err
}
}
When you use the credentials binding plugin the credentials will be bound to environment variables and the code to be executed must be inside the curly braces of the withCredentials statement, this is what we've missed.
So use:
stage ('Upload war to Artifactory') {
withCredentials([usernamePassword(credentialsId: '7c9e8186-1f16-4920-837b-b571ea88a7e8', usernameVariable: 'USER', passwordVariable: 'PASSWORD')]) {
sh ("sudo curl -u $USER:$PASSWORD -T $warPath 'https://artifactory.xxxxx.com:443/artifactory/Platform/$warFile'")
}
}
instead of:
stage ('Upload war to Artifactory') {
withCredentials([usernamePassword(credentialsId: '7c9e8186-1f16-4920-837b-b571ea88a7e8', usernameVariable: 'USER', passwordVariable: 'PASSWORD')])
sh "sudo curl -u ${USER}:{$PASSWORD} -T $warPath 'https://artifactory.xxxxxxx.com:443/artifactory/Platform/$warFile'"
}

How to pass username password to Gradle to upload artifacts to Nexus from a Jenkins pipeline

I need to upload artifacts to Nexus from a Jenkins declarative pipeline. There is a Nexus plugin that I can't use because it doesn't allow to publish SNAPSHOTs. Therefore I have to upload them directly through the Gradle upload task. The problem is that I am getting a 401 error code from Nexus and it seems the nexus user and passwords aren't being passed from the pipeline to the ./gradlew upload task.
This is my current configuration:
Pipeline
withCredentials([usernamePassword(credentialsId: 'asdf23432-fe69-1234-2222-ffa65yteec2c', passwordVariable: 'NEXUS_PASSWORD', usernameVariable: 'NEXUS_USER')]) {
sh "./gradlew upload --debug"
}
Gradle: In the ext section I try to access the NEXUS_USER and NEXUS_PASSWORD variables from the withCredentials step.
ext{
nexusUser = System.properties['NEXUS_USER']
nexusPassword = System.properties['NEXUS_PASSWORD']
}
uploadArchives {
repositories {
mavenDeployer {
snapshotRepository(url: 'http://somerepo'){
authentication(userName: nexusUser, password: nexusPassword)
}
}
}
}
You can pass the variables as system properties using this:
withCredentials([usernamePassword(credentialsId: 'asdf23432-fe69-1234-2222-ffa65yteec2c', passwordVariable: 'NEXUS_PASSWORD', usernameVariable: 'NEXUS_USER')]) {
sh "./gradlew -DNEXUS_PASSWORD=$NEXUS_PASSWORD -DNEXUS_USER=$NEXUS_USER upload --debug"
}

Resources