I have a pipeline to get the csr and approve.
I am able to get the pending csrs and approve them with the below command.
sh "oc get csr "
sh "xargs oc adm certificate approve"
Now coming to the actual issue. When there are CSRs pending the above method works fine. When there are no resources found the pipeline ends in Failure which should not happen. I still want the pipeline to succeed with a message stating all nodes are up to date and no csrs are pending for approval.
PFB the error:
+ oc get csr
No resources found.
+ xargs oc adm certificate approve
error: one or more CSRs must be specified as <name> or -f <filename>
ERROR: script returned exit code 123
Finished: FAILURE
Since you have two separate commands there is nothing to prevent the second one from running which causes the error.
You shouldn’t be running the approval step unless there are any pending certificates.
I found a solution here which should work for you:
sh "for i in `oc get csr --no-headers | grep -i pending | awk '{ print $1 }'`; do oc adm certificate approve $i; done"
Related
Jenkins Pipeline job doesn't trigger pipeline job using jenkins cli. When i run jenkins as anaonymous this works, but when i create a user/admin it fails.
I have a job A which has parameters and passes the same to Pipeline Job. This is a Master-slave setup. This is how i run:
sudo java -jar /home/user/jenkins-cli.jar -s $JENKINS_URL build pipeline_job -p parameter_Name="$parameter_Name" -p parameter_Name2="$parameter2_Name"
1.) I tried using options, "-auth" , "-username -password" but doesn't work.
errors:
No such command: -auth
No such command: -ssh
2.) Another option is paste the public key in SSH section http://jenkin_url/me/configure , but still it fails
error:
java.io.IOException: Invalid PEM structure, '-----BEGIN...' missing
Is there i am missing anything ?
I Found the solution,
1.) used SSH CLI.
In my case i was using master-slave environment, connection was made using SSH keys vice-versa. In order to trigger the build using Jenkins CLI, place the SSH keys both public & private and place them in http://jenkinsURL/user/username/configure
Here username= the one used to connect the nodes.
Trigger the job as below:
java -jar /home/username/jenkins-cli.jar -s $JENKINS_URL -i /home/username/.ssh/id_rsa build JOBNAME
Note: This is one way but cloudbees doesn't encourage this approach.
2.) There is new approach i.e., using API token authentication.
Go to http://jenkinsURL/user/username/configure
Copy the API token
trigger the build as below:
java -jar /home/username/jenkins-cli.jar -s $JENKINS_URL -auth username:apitoken /home/username/.ssh/id_rsa build JOBNAME
Note: For using API token option, download the latest jar file
I'm trying to use the Jenkins Ansible plugin to deploy a project. I figured this should be pretty easy as i'm pretty familiar with both Jenkins and Ansible. However, i'm having issues getting the Ansible command to successfully execute. I believe the problem lies in the use of the credentials. We have a jenkins user that owns the Jenkins execution process and we have a jenkins user setup on the machine being deployed to. We are using SSH keys and I have added the jenkins users private key to the Jenkins credential store and selected those in the Ansible configuration. However, when i run the job, this is the snippet of my output (replaced some information).
[my-job] $ ansible-playbook my-job.yml -i inventories/dev -l 1_2_3_4 -f 1 --private-key /tmp/ssh7229752594712048879.key -u jenkins --diff --vault-password-file ~/.vault-pass
PLAY [tag_ansible_groups_my_job] ***********************
TASK [setup] *******************************************************************
fatal: [1_2_3_4]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password).\r\n", "unreachable": true}
to retry, use: --limit #/data/jenkinsdata/workspace/my-job/my-job.retry
PLAY RECAP *********************************************************************
1_2_3_4 : ok=0 changed=0 unreachable=1 failed=0
FATAL: command execution failed
hudson.AbortException: Ansible playbook execution failed
at org.jenkinsci.plugins.ansible.AnsiblePlaybookBuilder.perform(AnsiblePlaybookBuilder.java:227)
at org.jenkinsci.plugins.ansible.AnsiblePlaybookBuilder.perform(AnsiblePlaybookBuilder.java:200)
at hudson.tasks.BuildStepCompatibilityLayer.perform(BuildStepCompatibilityLayer.java:78)
at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:779)
at hudson.model.Build$BuildExecution.build(Build.java:205)
at hudson.model.Build$BuildExecution.doRun(Build.java:162)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:534)
at hudson.model.Run.execute(Run.java:1729)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:98)
at hudson.model.Executor.run(Executor.java:404)
ERROR: Ansible playbook execution failed
Finished: FAILURE
I've run the same command successfully from the Jenkins machine and it works just fine. The only difference was that I referenced the original SSH private key instead of the copied temporary key. To see if this was the issue, I decided to check the contents of the copied temporary SSH private key and the file was empty. I checked the file before the job finished executing as I am assuming it stays there for the life of the job and removed only after the job has finished executing. To verify this, I removed the use of credentials from the configuration and added in the private-key and user parameters pointing directly to the appropriate key and the job runs successfully.
[my-job] $ ansible-playbook my-job.yml -i inventories/dev -l 1_2_3_4 -f 1 --private-key ~/.ssh/id_rsa -u jenkins --diff --vault-password-file ~/.vault-pass
PLAY [tag_ansible_groups_my_job] ***********************
TASK [setup] *******************************************************************
ok: [1_2_3_4]
So, to me, it seems that Jenkins is failing to copy the SSH private key to the temporary file(s). I've tried with other SSH keys but still the same problem each time. I've tried specifying the private key in Jenkins credential store itself rather than specifying the location and that also did not work. I've checked the Jenkins logs and there is nothing that would indicate why the private SSH key would fail to copy to the /tmp directory.
I'd prefer not to reference the key directly in the additional parameters as this limits me to only keys located on that server. Any suggestions?
I found this solution at Edureka. It worked for me.
set "host_key_checking = False" in /etc/ansible/ansible.cfg
https://www.edureka.co/community/42595/not-able-connect-remote-host-via-jenkins-run-ansible-playbook
Jenkins HockeyApp plugin can automatically create reasonably nicely formatted release notes from git changes. However, this does not seem to work if HockeyApp upload is done in promotion phase, using promotion plugin. In that case the change log is empty.
This can be partially solved by selecting "Load Release Notes from File" and giving path to changelog.xml in the project (../builds/${PROMOTED_NUMBER}/changelog.xml), but the output is not as clean as it is with the "Use Change Log" selection, containing also the file names and commit id's.
What is the best way to automatically create nicely formatted logs for HockeyApp transfer, when the transfer happens in promotion phase and possibly on a Jenkins slave machine?
Answering to myself: It is possible to get the change log from jenkins master to jenkins slave
and parsing the obtained changelog.xml to more user readable by using this simple script:
#!/bin/bash
PROJECT_NAME="$1"
BUILD_NUMBER="$2"
BUILD_DATE="$3"
CHANGELOG=changelog.xml
echo "project=${PROJECT_NAME} build=${BUILD_NUMBER}"
PROJECT_NAME=`basename ${PROJECT_NAME}`
curl ${PROMOTED_URL}api/xml?xpath=/*/changeSet/item/comment\&wrapper=changelog > ${CHANGELOG}
PARSEDLOG=`sed -e 's/<\/[^>]*>/€€/g' ${CHANGELOG} | sed -e 's/<[^>]*>/- /g' | tr €€, '\r' | sed '/^ \s*$/d'`
echo "${PROJECT_NAME} ${BUILD_NUMBER} ${BUILD_DATE} change log:
=====================================================================
${PARSEDLOG}" > changelog.txt
I know there are much better and reliable ways to clean up the xml than the sequence of sed and tr commands I have used, but this works for now.
I want to use the Slack plugin in Jenkins to ping notifications to a Slack channel.
Jenkins says success when I test the connection, but I don't receive any notifications in my Slack channel.
Are there any known problems?
How can I get Jenkins to send notifications to Slack?
I think that you should add post-build action "Slack Notification" in your Jenkins. Please see the image below
And are you sure that you have a correct configuration.
In Build Configuration (Do not forget # character)
In General Configuration
There are two steps to configure a Jenkins job to be posting on a slack channel.
Go to jenkins job configurations and add a post-build action on each job that you wish to ping the slack channel.
Next, again under the job configurations, you have to configure on each job on which cases you wish to send slack notifications: (true - false)
f.e.
In the case that you have to configure a great number of Jenkins jobs, you could configure only one of them manually and verify it is working fine. Then check the config.xml of this Jenkins job to find the auto-generated xml elements for the slack plugin preferences and apply those configs on all Jenkins jobs by using regex or xslt. In this case, you will have to reload the Jenkins configs for the job configurations updates to be applied. ("Manage Jenkins" / "Reload Configuration from Disk")
Prerequisites:
Install slack plugin in Jenkins.
Obtain a Jenkins CI integration token in your slack domain.
Go in Jenkins "Manage Jenkins" / "Configure System". There you have to configure the "Global Slack Notifier Setting".
I didn't use the Slack Notification because I wanna customize style/state/message, etc. So I wrote a job called send_slack_notification instead. Every time I want to notify slack API I just call this job after build.
Here's the code in "Execute Shell", I used curl, sed and jsawk to do the job:
# URL to get the built info json
# will get "http://JENKINS_PATH/job/JOB_NAME/97/api/json"
NEW_URL="http://jks_username:jks_password#"$(echo ${BUILD_URL} | sed -r 's/http:\/\///g')"/api/json"
# Cut the JOB_NAME part from BUILD_URL
JOB_NAME=$(echo ${BUILD_URL} | sed -n 's/.*\/job\/\(.*\)\/[0-9].*/\1/p' | sed "s#+# #g;s#%#\\\\x#g" | xargs -0 printf "%b")
# Get the built info json
JSON=$(curl $NEW_URL)
STATUS=$(echo $JSON | /usr/local/bin/jsawk "return this.result")
BUILD_INFO=$(echo $JSON | /usr/local/bin/jsawk "return this.displayName")
TIME=$(echo $JSON | /usr/local/bin/jsawk "return this.duration")
TIME=$(echo "scale=4; $TIME/1000" | bc -l)
# Cut the username
USER=$(echo $JSON | /usr/local/bin/jsawk "return this" | sed -n "s/.*Started\ by\ \([^\"]*\).*/\1/p")
# Customize the message sending to slack
TEXT=$JOB_NAME" Built by "$USER", it took "$TIME" seconds."
# Send notification using Slack API
# will send to https://hooks.slack.com/services/BLABLABLA/BLABLABLA
curl -X POST -H 'Content-type: application/json' --data '{"channel": "#production_info","username": "jenkins-bot","icon_emoji": ":lol:","text": "'"$TEXT"' (<'"$BUILD_URL"'|Open>)", "attachments": [{"color": "#36a64f", "fields": [{"title":"UPDATE INFO","value":"'"$BUILD_INFO"'","short":true},{"title":"RESULT","value":"'"$STATUS"'","short":true}]}]}' https://hooks.slack.com/services/BLABLABLA/BLABLABLA/BLABLABLABLABLABLA
I though of adding it here for the greater good of the community. This is how you get the integration token
Jenkins Instructions
Get a Slack account: https://slack.com/
Configure the Jenkins integration: https://my.slack.com/services/new/jenkins-ci
Install this plugin on your Jenkins server
Configure it in your Jenkins job and add it as a Post-build action.
https://github.com/jenkinsci/slack-plugin
import os
import sys
from slacker import Slacker
import base64
def main():
myPass=sys.argv[1]
msgStr= sys.argv[2]
channel = sys.argv[3]
slack = Slacker(myPass)
slack.chat.post_message(channel, msgStr)
print msgStr
if __name__ == '__main__':
main()
python slack.py <token> < message str > <#channel>
I couldn't get anything but 'failure' from the slack connection test in the config. I can use python from the same box so I don't know what the issue is so I may just use this simple script.
If you want to receive notifications using Jenkins declarative pipelines, you can install the Slack plugin, and then use it in the pipeline in this way:
stage('Clone sources') {
steps {
slackSend (channel: "#mychannel", color: '#FFFF00', message: "STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.BUILD_URL})")
git credentialsId: 'git_credentials', poll: false, branch: 'develop', url: 'https://mysource.com/mysimplenodejsexample.git'
}
}
Result:
You can customize your message of course. Full example at:
https://pillsfromtheweb.blogspot.com/2020/05/send-notifications-to-slack-from.html
I had similar issues.
It worked for me when i unchecked "is Bot User?"
starting Jenkins in console with 'jenkins' not with brew demon, though.
Maybe that helps :)
Greetings ^__^
I have Gerrit 2.5 server and Jenkins server (with Gerrit Trigger).
For some branches I configured Jenkins Gerrit Trigger so, that it not only verifies but also approves reviews, if the build and tests were successful.
My question is: How can I configure Gerrit or Jenkins so, that by Jenkins verified and approved review get merged automatically?
Tried solutions:
Using "Post Build Task" Jenkins plugin add a script to merge reviews (as suggested in Gerrit - how to auto publish change after Jenkins run). Problem: It merges builds with failing tests.
Add Gerrit "comment-added" hook to check, if a review was verified and approved, then merge. Problem: It's complicated and it can't be configured well to auto-submit only from specified branches.
The solution I found is to use Groovy Postbuild plugin. Following script executed after JUnit post build action does the trick:
if(manager.build.result.isBetterThan(hudson.model.Result.UNSTABLE)) {
def cmd = 'ssh -p 29418 HOST gerrit review --verified +1 --code-review +2 --submit --project $GERRIT_PROJECT $GIT_COMMIT'
cmd = manager.build.environment.expand(cmd)
manager.listener.logger.println("Merge review: '$cmd'")
def p = "$cmd".execute()
manager.listener.logger.println(p.in.text)
manager.addShortText("M")
}
Your Jenkins account needs +1 verify, +2 review and submit permissions of course. You have also to set up public key authentication.
On Windows: You may use following command to run ssh from the git distribution
"C:\Program Files (x86)\Git\bin\sh.exe" --login -c "ssh -p 29418 HOST ..."
This is a currently working command for me using gerrit 2.10-rc0
if(manager.build.result.isBetterThan(hudson.model.Result.UNSTABLE)) {
def cmd = 'ssh -p 29418 $host gerrit review --verified +1 --code --review +2 --submit $GERRIT_CHANGE_NUMBER,$GERRIT_PATCHSET_NUMBER'
cmd = manager.build.environment.expand(cmd)
manager.listener.logger.println("Merge review: '$cmd'")
def p = "$cmd".execute()
manager.listener.logger.println(p.in.text)
manager.addShortText("M")
}