I have a Jenkinsfile that is running a shell command and I want to send the output of that sh method as the message: of the slackSend method.
I have the following so far, but the message to the slack channel is empty. I'm not certain how to capture the output in a way that I can reference it in the message section:
node {
checkout scm
stage 'run shell command'
def shell_command = sh "ls -l"
def shell_output = apply_cluster
stage 'notify slack-notification'
slackSend channel: '#slack-notifications', color: 'good', message: shell_output, teamDomain: 'company', token: env.SLACK_TOKEN
}
After a little more research, I discovered a couple of things I did not initially understand: The first is that even with defining a function in a Jenkinsfile, if it's a DSL method like sh, it will still get executed, so the second function I defined isn't necessary. Second, if you want to return stdout, you have to specify that as part of the command. The new code looks like this:
node {
checkout scm
stage 'run shell command'
def shell_command = sh script: "ls -l", returnStdout: true
stage 'notify slack-notification'
slackSend channel: '#slack-notifications', color: 'good', message: shell_command, teamDomain: 'company', token: env.SLACK_TOKEN
}
Related
We have Jenkins stage which is calling a "GetVMPassword" function from library. The function returns credential and it will be used to login remote server. We dont want to print the "ssh command" and "calling a funtion command" and its reponse on stage logs. So we used ā#!/bin/sh -e \nā before every command. Because if we print, this could reveal the remote server credentials in the stage log. This was working when we don't use "parallel execution" block.
When we include "ssh command" and "calling a function command" inside "parallel execution" block, passwords are printed in stage logs.
How can we avoid printing in stage logs the library command and its response when we use "parallel execution" block ?
This is snippet of my stage and parallel execution block.
Jenkins Version: 2.235.3
#Library ('MyLib_API') _
pipeline{
agent {
label 'master'
}
stages{
stage('BuildAll'){
steps{
script{
def executions = APPSERVERS.split(',').collectEntries {APPS ->
["Execution ${APPS}": {
stage(APPS) {
APP_USERNAME = "ubuntu"
response = getPassword("${APPS}","${APP_USERNAME}")
sh '#!/bin/sh -e \n' + "sshpass -p '${response}' ssh -o StrictHostKeyChecking=no ${APP_USERNAME}#${APPS} 'ls'"
sleep 2
}
}]
}
parallel executions
}
}
}
}
}
"getPassword" is the function in library used to get the vm password dynamically.
"APPSERVERS" values we are getting from Active choice parameters option.This has list of IP's of servers.
Please help me to hide those library commands and responses from stage logs.
We have tried below options.
Used set +x and it is not worked for us.
Password masking plugin will not work. Since response from the command will get print for our case.
We tried routing all the execution of commands to file and tried fetching it from there. In this option, also while parsing the file logs are printed in stage logs.
Try starting your script with set +x, if not use password masking plugins
as mentioned here - https://issues.jenkins.io/browse/JENKINS-36007
You can use input to pass the credential and mask it in log.
Here is a detailed answer stackoverflow credentials masking
you can use this as well it works for me.
node('Node Name'){
println('Please enter the username')
def userName = input(
id: 'userName', message: 'VPN Username', parameters: [
[$class: 'hudson.model.TextParameterDefinition', defaultValue :'', name: 'Username', description: 'Please enter your username']
])
println('Please enter the password')
def userPassword = input(
id: 'userPassword', message: 'VPN Password', parameters: [
[$class: 'hudson.model.PasswordParameterDefinition', defaultValue :'', name: 'Password', description: 'Please enter your password']
])
connectToClient = bat(returnStdout: true, script: 'start Forticlient connect -h v3 -u ' + userName+ ':' + userPassword)
stage('Deploy (Test)'){
withCredentials([usernamePassword(credentialsId: 'IH_IIS_JENKINS', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
bat"msdeploy command"
}
}
}
im trying to post Jenkins job script output to slack notification: but i cant able to access the output in slack notification setting.
other than /env-vars.html/ the variables here i can't able to access any other variable.
At the moment there is no support to get the variables other than env vars in Jenkins. We can use "Environment Injector" plugin but I am not sure about that plugin.
For your case you can create a "Pipeline" with the below scripted pipeline
node('JENKINS_NODE') {
git([url: 'GITHUB_REPO_URL', branch: 'BRANCH'])
def getResult
stage ('Execute Script') {
getResult = sh(
script: "python test.py",
returnStdout: true,
)
}
stage ('Send Slack Notification') {
slackSend channel: '#YOUR_SLACK_CHANNEL', color: 'good', message: getResult'
}
}
I am trying to email the output of a file after a build. The build updates the file file1.json. Her is my problem. After build I am trying to create a variable which cat the file1.json ( this is working) , then I am trying to email that variable in emailext.
Stage {
stage('Build'){\
sh """
npm install // builds and update the value in json file
UUID="`cat file1.json`" //outputs the string inside file which is what I want
echo \$UUID //shows the value here
"""
emailext body: "$UUID", //need the value here
subject: "$currentBuild.currentResult-$JOB_NAME",
to: 'someone#test.com'
}
`
The error message is groovy.lang.MissingPropertyException: No such property: UUID for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:63)
at
You can use option returnStdout: true of sh() step to get the output of shell.
stage('Build'){
script {
sh 'npm install' // builds and update the value in json file
UUID = sh (script: 'cat file1.json', returnStdout: true).trim()
emailext body: "$UUID", subject: "$currentBuild.currentResult-$JOB_NAME", to: 'someone#test.com'
}
}
I have downloaded & installed Slack Notification Plugin in jenkins and using slackSend in the pipeline, it was working before but now getting an error as below: After this i downloaded Global Slack Notifier plugin, but still the same error,is there any setup required? Please advice
[Pipeline] slackSend
run slackstepsend, step null:false, desc null:false
Slack Send Pipeline step configured values from global config - baseUrl: true, teamDomain: true, token: true, channel: false, color: false
ERROR: Slack notification failed. See Jenkins logs for details.
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: FAILURE
Code is as below:
if (dstry) {
def status = sh(returnStatus: true, script: "set +e; terraform plan -destroy -var-file=my.tfvars -out=destroy.tfplan")
echo "Plan Status : ${status}"
def destroyExitCode = sh(returnStatus: true, script: "set +e; terraform destroy -auto-approve")
echo "Terraform Destroy Exit Code: ${destroyExitCode}"
if (destroyExitCode == "0") {
slackSend channel: '#ci', color: 'good', message: "Destroy Applied ${env.JOB_NAME} - ${env.BUILD_NUMBER} ()"
currentBuild.result = 'SUCCESSFUL'
} else {
slackSend channel: '#ci', color: 'danger', message: "Destroy Failed: ${env.JOB_NAME} - ${env.BUILD_NUMBER} ()"
currentBuild.result = 'FAILURE'
}
}
Did you add the slack Jenkins token for integration?
Go to this Jenkins CI url, search for your team domain, then add a new configuration. Copy the name of the token or the token itself. Then go to your Jenkins pipeline script and add to slackSend, the domain and the token credential ID or the token in plain text (not secured). Should look something like this:
slackSend channel: '#ci', color: 'good', message: "Destroy Applied ${env.JOB_NAME} - ${env.BUILD_NUMBER}", teamDomain: 'your_domain.slack.com', tokenCredentialId: 'your_id'
or if you want to use the token in plain text token:'your_token' instead of the tokenCredentialId
Hope this helps!
I have a playbook with section "pause" and prompt. If I create job within Jenkins with Pipeline plugin and run this job I get
[WARNING]: Not waiting from prompt as stdin is not interactive
and job is failed. The question is how I can run job in interactive mode or how I can pause playbook within exact task and push combination Ctrl+c+c (because ansible module 'pause' is working only like that)? I have googled a few time and tried to do that with
def userInput = input(
id: 'Password', message: 'input your input: ', ok: 'ok',
parameters: [string(defaultValue: '', description: '.....', name: 'INPUT_TEST')])
But I can't push keys combination and can't understand how I can pause jenkins job on specific ansible task within playbook.
Pipeline example:
pipeline {
agent { label 'master' }
environment {
WORKDIR = '/home/jenkins/'
}
stages {
stage('Checkout') {
agent { label 'master' }
steps {
sh '''cd $WORKDIR
ansible-playbook -vvvv manual_playbooks/test.yml'''
}
}
stage ('Echo') {
agent { label 'master' }
steps {
sh 'echo something'
}
}
}
}
Playbook example:
---
- name: test
hosts: localhost
tasks:
- name: Echo start
shell: echo 'start playbook'
- pause:
prompt: "do you want to continue?"
echo: yes
private: no
register: prompt_status
- name: Continue tasks
shell: echo 'Continue full flow'
register: reset_account_response
when: prompt_status.user_input is defined and
prompt_status.user_input == "yes"
- fail:
msg: "Unexpected user input while prompting approval"
when: prompt_status.user_input is defined and
prompt_status.user_input != "yes"
Many thanks.
Why not put a when clause on your pause task to check for the existence of some other variable and then pass that in using Ansible's -e option when running the playbook through Jenkins.