How to read value from config file (groovy script) in Jenkins? - jenkins

I want to read some value(ex. user Login info) from config file in Jenkins pipeline script.
downloaded plugin "Config File Provider Plugin(ver.3.10.0)"
and i create config file.
I want to read that user info (line 2)
anyone have ideas ?
thank you.

Here is how you can use the Config File Provider with a Groovy script. First, you have to load it to your pipeline and then execute it. So for that, you have to restructure your Groovy script as well. Please check the below.
Jenkins Pipeline
pipeline {
agent any
stages {
stage('ConfigTest') {
steps {
configFileProvider([configFile(fileId: '078d4943-231c-4156-9b88-8334cd8a9402', variable: 'GroovyScript')]) {
echo " =========== Reading Groovy Script"
script {
def script = load("$GroovyScript")
script.setProperties()
echo "${USER_ID}"
}
}
}
}
}
}
Content of the Script
import groovy.transform.Field
#Field def USER_ID;
def setProperties() {
USER_ID = "abcd#gmail.com"
}
return this

Related

How to use file parameter in Jenkins declarative pipeline?

I am currently using the following code to upload file in Jenkins declarative pipeline and read the content from file. But the file is not stored in the Jenkins workspace or anywhere. So, whenever I run pipelines, it shows file not found error.
I tried other ways which are available on Internet but did not get output. Can anyone suggest a proper way to upload file in Jenkins and read the data from it?
pipeline {
agent any
parameters {
file(name: 'yamlFile', description: 'Upload file test')
}
stages {
stage ("Checkout demo repo") {
steps {
script{
echo "${WORKSPACE}"
def configVal = readYaml file: yamlFile
}
}
}
}
}
I never had luck using the default File Input with a declarative Pipeline. Instead, I used the File Parameters plugin. Here is an example.
pipeline {
agent any
parameters {
base64File 'yamlFile'
}
stages {
stage('Example') {
steps {
withFileParameter('yamlFile') {
def configVal = readYaml file: yamlFile
}
}
}
}
}

How to use inject environment variables (Properties File Path) in Jenkins Pipeline

Want to use the below functionality(shown in image link) in Jenkins as code, but i'm failing to do, kindly help me replicate the functionality in the image to groovy script
stage ('Build Instance') {
sh '''
bash ./build.sh -Ddisable-rpm=false
'''
env "/fl/tar/ver.prop"
}
Jenkins GUI usage of Env Inject
Got a simple workaround :
script {
def props = readProperties file: '/fl/tar/ver.prop' //readProperties is a step in Pipeline Utility Steps plugin
env.WEATHER = props.WEATHER //assuming the key name is WEATHER in properties file
}

How to execute Jenkins shared library functions on slave instead of master?

I need to write shared library that reads files in build workspace and shared library functions cannot read files because pipeline is on slave and shared library is executed in master. Is there any way tho change execution context of library functions?
Found out answer. You can read library file and give the file to writeFile pipeline step
writeFile(file:"foo.groovy", text: libraryResource("bar.groovy"))
"groovy foo.groovy"
writeFile neads BOTH parameters as named parameters so answer given in https://issues.jenkins-ci.org/browse/JENKINS-54646 is not fully right.
To execute Jenkins shared library functions on slave instead of master. You can implement de argument node("slaveName") in the call:
def call(Map config=[:], Closure body) {
def label = 'slave'
node("${label}") {
pipeline {
stage('Sonarqube') {
script {
withSonarQubeEnv('Sonar8') {
withMaven(maven: 'apache-maven') {
sh 'mvn sonar:sonar -Dmaven.test.skip=true -Dsonar.java.binaries=./target'
}
}
}
}//pipeline
} // call
You Can actually do it without writeFile, This shared Library Code will be executed in Master, but it will use RemoteDignostic to Execute commands to Slave
to execute uname -a in worker node
import hudson.util.RemotingDiagnostics
import jenkins.model.Jenkins
class test_exec{
def env
def propertiesFilePath
#NonCPS
def call(cmd) {
def trial_script = """
println "uname -a".execute().text
""".trim()
String result
Jenkins.instance.slaves.find { agent ->
agent.name == "${env.NODE_NAME}"
}.with { agent ->
result = RemotingDiagnostics.executeGroovy(trial_script, agent.channel)
}
return result
}
}
In your pipeline
steps{
println(new test_exec().call())
}

How to read log file from within pipeline?

I have a pipeline job that runs a maven build. In the "post" section of the pipeline, I want to get the log file so that I can perform some failure analysis on it using some regexes. I have tried the following:
def logContent = Jenkins.getInstance()
.getItemByFullName(JOB_NAME)
.getBuildByNumber(
Integer.parseInt(BUILD_NUMBER))
.logFile.text
Error for the above code
Scripts not permitted to use staticMethod jenkins.model.Jenkins
getInstance
currentBuild.rawBuild.getLogFile()
Error for the above code
Scripts not permitted to use method hudson.model.Run getLogFile
From my research, when I encounter these, I should be able to go to the scriptApproval page and see a prompt to approve these scripts, but when I go to that page, there are no new prompts.
I've also tried loading the script in from a separate file and running it on a different node with no luck.
I'm not sure what else to try at this point, so that's why I'm here. Any help is greatly appreciated.
P.S. I'm aware of the BFA tool, and I've tried manually triggering the analysis early, but in order to do that, I need to be able to access the log file, so I run into the same issue.
You can use pipeline step httpRequest from here
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Test fetch build log'
}
post {
always {
script {
def logUrl = env.BUILD_URL + 'consoleText'
def response = httpRequest(
url: logUrl,
authentication: '<credentialsId of jenkins user>',
ignoreSslErrors: true
)
def log = response.content
echo 'Build log: ' + log
}
}
}
}
}
}
If your jenkins job can run on linux machine, you can use curl to archive same goal.
pipeline {
agent any
stages {
stage('Build') {
environment {
JENKINS_AUTH = credentials('< credentialsId of jenkins user')
}
steps {
sh 'pwd'
}
post {
always {
script {
def logUrl = env.BUILD_URL + 'consoleText'
def cmd = 'curl -u ${JENKINS_AUTH} -k ' + logUrl
def log = sh(returnStdout: true, script: cmd).trim()
echo 'Build log: ' +
echo log
}
}
}
}
}
}
Above two approaches both require the credentials is Username and password format. More detail about what is it and how to add in Jenkins, please look at here
Currently this is not possible via the RunWrapper object that is made available. See https://issues.jenkins.io/browse/JENKINS-46376 for a request to add this.
So the only options are:
explicitly whitelisting the methods
read the log via the URL as described in the other answer, but this requires either anonymous read access or using proper credentials.

how to read from configfile in jenkins pipeline BEFORE stages

I have configfile, which is a JSON file. I want to be able to read it before any steps, as it provides variables I need to execute them. However, I don't know where do I put that. To contain config file provider call, I tried creating a separate node before pipeline, to no avail, also tried to set up script in stages, stage (also as post).
I did a simple practice on my jenkins as following.
def config;
node(){
configFileProvider([configFile(fileId: '<your config file id>', targetLocation: 'myConfig')]) {
config = readJSON file: 'myConfig'
}
}
pipeline {
agent any
stages {
stage('Build') {
steps {
echo config.myKey // or config['myKey']
}
}
}
}

Resources