Syntax Hidden Parameter Plugin in groovy script - jenkins

I have an issue with the writing pipelines with a hidden parameter.
I installed Hidden Parameter Plugin to my Jenkins and I would like to hide some parameters.
Actually I understand how to use StringParameterDefinition, but I can not hide this parameter
[$class: 'StringParameterDefinition', defaultValue: 'N/A', description: 'some text', name: 'variable', hidden: true]
After installation Hidden Parameter Plugin I can see "Hidden Parameter" during adding a parameter, but I have the groovy file, which is downloaded on each build, that's why I would like to write it in the groovy pipe.
Could you please help me with syntax for hidden parameter?

Related

Jenkins pipeline perfReport: Use "Expert Mode" constraints

I know how to use the "Standard Mode" thresholds when publishing a performance report via jenkins pipelines:
perfReport errorFailedThreshold: 5, errorUnstableThreshold: 1, sourceDataFiles: 'result.jtl'
But how can I use these "Expert Mode" constraints like "Absolute Contraint"? (see screenshot)
The easiest way to figure out how to use the perfReport step (and any other step' in a pipeline script is to use the Pipeline Snippet Generator that will create the pipeline code according to your UI configuration.
This feature is crucial as the official documentation of the step lacks some advance configuration options.
To use the snippet generator just click on the Pipeline Syntax link on the left side menu of your Pipeline Job (it wont be available in freestyle jobs), You can also navigate to that page using the following URL: <Your_Project_URL>/pipeline-syntax/
Once in the page select the perfReport step, the UI configuration of the plugin will be presented, configure it how you want and click the Generate button at the button of the page, that will give you the relevant pipeline code for execution the step with the relevant parameters you have configured.
Here are some examples for configuration:
Expert Mode with Absolute Constraint
perfReport constraints: [absolute(escalationLevel: 'INFORMATION', meteredValue: 'AVERAGE', operator: 'NOT_GREATER', relatedPerfReport: 'result.xml', success: false, value: 0)],
filterRegex: '', modeEvaluation: true, showTrendGraphs: true, sourceDataFiles: ''
Expert Mode with Relative Constraint
perfReport constraints: [relative(escalationLevel: 'INFORMATION', meteredValue: 'AVERAGE', operator: 'NOT_GREATER', previousResultsBlock: previous(value: 'BASELINE'), relatedPerfReport: 'results.xml', success: false, tolerance: 0.0)],
filterRegex: '', modeEvaluation: true, showTrendGraphs: true, sourceDataFiles: ''

Jenkins Active Choice Reactive Reference Parameter Formatted HTML in MultiBranch pipeline job get current branch name in script

I am trying for a lot of time to get the current branch name in MultibranchPipeline Job inside an Active Choice Reactive Reference Parameter Formatted HTML parameter script block
[
$class: 'DynamicReferenceParameter',
choiceType: 'ET_FORMATTED_HTML',
name: 'TestParam',
omitValueField: true,
description: 'Test.',
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: false,
script: '''
return """
<p>FallbackScript. Error in main script</p>
"""
'''
],
script: [
classpath: [],
sandbox: false,
script: '''
String branchName = env.BRANCH_NAME
return """
<p>${branchName}</p>
"""
'''
]
]
]
The thing is that, I believe, the BRANCH_NAME param is injected after you press the Build button.
I've tried a lot of things, and I mean, A LOT, still I didn't manage to find a way. The scm variable doesn't exist as well, I tried to find something with the jenkins.model.Jenkins.instance but no luck.
Is it possible? I would love to ask this question on their Github repo, but issues are not allowed to be opened. Also to open an issue on Jenkins you need a Jira account or something. SO is the only place.
Thanks to Michael's answer, I managed to find a way to make this work. There are a lot more to it than meets the eye, but I will get through all details. I also answered this question here.
I make the assumption that the reader is familiar with the Active Choices plugin. Also, I played with this in a multibranch pipeline job. You might encounter different behaviours with other kinds of jobs.
The parameters sadly don't have access to the environment variables. This is a bit of a limitation which I hope will be fixed/thought of in the future by the plugin's maintainers.
Some environment variables are only populated at build time, like BRANCH_NAME. In this case, even if we had access to the env vars we wouldn't have the actual value at hand.
To be able to use the env.BRANCH_NAME we need two reactive parameters.
The plugin has a parameter named FORMATTED_HIDDEN_HTML. This parameter doesn't get displayed to the user. This is great since we wouldn't want to see in a multibranch pipeline job a parameter with the same name as the branch we are currently on.
To set this parameter, we can write something like this in a Jenkinsfile.
[
$class: 'DynamicReferenceParameter',
choiceType: 'ET_FORMATTED_HIDDEN_HTML',
name: 'BranchName',
omitValueField: true,
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: true,
script: '''
return '<p>error</p>'
'''
],
script: [
classpath: [],
sandbox: true,
script: """
return '<input name="value" value="${env.BRANCH_NAME}" type="text">'
"""
]
]
]
There are a lot of things to note here.
The sandbox property is set to true. If you don't do that, you would need to accept the script in the ScriptApproval menu in Jenkins.
We use triple-double quotes when we define the script property.
script: """
return '<input name="value" value="${env.BRANCH_NAME}" type="text">'
"""
When the job is started for the first time, the BRANCH_NAME variable is populated. This results in a string interpolation which gets your script property in the following state:
script: """
return '<input name="value" value="myBranchName" type="text">'
"""
If we would've used triple-single quotes, we would get an error like:
hudson.remoting.ProxyException: groovy.lang.MissingPropertyException: No such property: env for class: WorkflowScript
This gets us back to the fact that we don't have access to the environment variables.
What to conclude from this? Well, if we use triple-double quotes, first we have a string interpolation, then the script is run.
The HTML element that must be used is input. This is explained in the docs if you read it carefully. Not only that but also the name property must be set to value. This is also explained in the docs.
omitValueField should be set to true, or else you will get a trailing comma in your value. E.g.: myBranchName,
Basically, the first time you run the job you get your branch name populated via string interpolation. Only after the second build, you will have the value to use. You will always reference the previous value.
After all that, you can reference this parameter in other Active Choices parameter types via referencedParameters property.
I desperately needed this because I have a complex use case scenario. I'm making requests to an Azure Container Registry to get all the tags for a certain image for a certain branch.
This plugin is great, I'm glad it exists. I would've loved a lot more documentation and examples thoguh.
Have a look at Groovy's string interpolation.
tl;dr You can access values by using """ and ${variable}
script: """
return <p>${env.BRANCH_NAME}</p>
"""

Jenkins declarative pipeline : How to configure the klocwork result display on the job page

I am creating a pipeline using the declarative pipeline flavour, with clockwork steps enclosed within a klockwork wrapper where I can define the klocwork setup :
klocworkWrapper(installConfig: 'My Klocwork', ltoken: "${HOME}/.klocwork/ltoken", serverConfig: 'Klocwork#XYZ', serverProject: 'S3cr3TPr0j3ct') {
klocworkBuildSpecGeneration([additionalOpts: '', buildCommand: 'make', ignoreErrors: true, output: 'kwinject.out', tool: 'kwinject'])
klocworkIntegrationStep1([additionalOpts: '', buildSpec: 'kwinject.out', disableKwdeploy: false, ignoreCompileErrors: true, importConfig: '', incrementalAnalysis: false, tablesDir: 'kwtables'])
klocworkIntegrationStep2([additionalOpts: '', buildName: "${JOB_BASE_NAME}_${BUILD_NUMBER}", tablesDir: 'kwtables'])
}
Ok, analysis is launched, and I can see the results on the Klocwork server web interface.
But I cannot find a way to retrieve resulting diagrams on the Jenkins web interface, even when using the pipeline script generator.
Unless I am totally wrong, I think that I should use klocworkQualityGateway, but the generated script snippet is not correct.
Once copied within the wrapper, it fails lacking for some enableXYGateway or gatewayXYConfig property.
For example this line :
klocworkQualityGateway([enableCiGateway: false, enableServerGateway: true, gatewayServerConfigs: [[conditionName: 'Issues', jobResult: 'failure', query: 'state:+Status,Fix', threshold: '1']]])
fails with an error message :
WorkflowScript: 92: Missing required parameter: "gatewayCiConfig" # line 92, column 1.
klocworkQualityGateway([enableCiGateway: false, enableServerGateway: true, gatewayServerConfigs: [[conditionName: 'Issues', jobResult: 'failure', query: 'state:+Status,Fix', threshold: '1']]])
I really cannot find a way to make it work, and I guess I can take a wrong turn... so any help would be appreciate.
Thanks for your help and best regards
J-L
Well, after a fruitful discussion with the plugin maintainer (M. Baron) it appears that there is currently no simple and direct solution to display Klocwork result on a pipeline job page.
He said :
This step doesn't have a native pipeline interface and a few people
have tried, but haven't had much success with workarounds to use this
in a pipeline.
The simplest thing to do seems to trigger a freestyle job that will only do that.
As far as I have understood, a new plugin version with full pipeline support will replace the current one.
So, I think this discussion can be closed.

Jenkins pipeline mandatory text parameters in input step

We are building several pipeline tasks in Jenkins to make life easier on some deploy jobs. One of them requires manual input of several parameters. For that we are using an input step like this:
def userInput = input ( message : 'Select deployment versiĆ³n and input deployment code:',
parameters: [[$class: 'TextParameterDefinition', defaultValue: '', description: 'Clarive code', name: 'code']] )
Those parameters are mandatory. We didn't find in the documentation any property that will make the TextParameterDefinition mandatory. For now we are re running the step until all parameters are not null, but the solution is a bit confusing for the user.
Is there another way to handle mandatory parameters that avoids running the same step on a loop?
There was a plugin that did that but is no longer maintained.
There's an open bug to support it.
In the meantime what you can do is check if your parameter is present and if not throw an error like:
if (params.SomeParam == null) {
error("Build failed because of this and that..")
}

pass parameter to pipeline script

I'm trying to switch from using a freestyle Jenkins build to a pipeline project.
I like many things about it, but I wish that I could use the multibranch pipeline as that matches our company a bit better, but at present that is a not an option.
What we do currently is create a new build job with the name of <project name> - <environment>.
So I need to keep that going for now. I have a basic outline of a script that I can either copy and paste into the box or even better is to use the jenkins file from scm.
I like this one the most and that is what I'm currently using on my local Jenkins.
If I hard code the solution file and the environment I want in my script in scm it builds fine.
I don't like that option because that means I'd have to have lots of scripts with similar names just changing the branch. If I add build parameters with the solution name and environment I can easily make the script handle those as well, however what I don't like is that when I click build button it confirms that those are the parameters I want to use.
So is there a way that I can hardcode/get a plugin that lets me add those parameters as constants or environment variables or whatever so it is just part of the job?
EDIT
As an update to show what I tried yesterday and got to work for our needs is this. First was that I installed multibranch defaults plugin and followed the steps outline on their github page. With that installed and configured I added a new multibranch project, pointed it to my git repository. It now found 2 branches (as expected) and used the default config file. So far this seems like it will work for about 90% of our cases. The only problem I can see is if some people had custom steps in their existing freestyle project. But for now those can always just stay a freestyle project.
If I understand you correctly what you're looking for is a way to supply default parameters to your build.
In one of my builds I do something like that:
stage ('Setup') {
try {
timeout(time: 1, unit: 'MINUTES') {
userInput = input message: 'Configure build parameters:', ok: '', parameters: [
[$class: 'hudson.model.ChoiceParameterDefinition', choices: 'staging\nproduction\nfree', description: 'Choose build flavor', name: 'BUILD_FLAVOR'],
[$class: 'hudson.model.ChoiceParameterDefinition', choices: 'Debug\nRelease', description: 'Choose build type', name: 'BUILD_TYPE'],
[$class: 'hudson.model.ChoiceParameterDefinition', choices: 'NONE\ndevelop\nmaster\nrelease/core_0.5.0\nrelease/core_0.1.8.1\nrelease/core_0.1.9', description: 'Product core branch', name: 'CORE_BRANCH'],
[$class: 'hudson.model.ChoiceParameterDefinition', choices: '4.1.12\n4.1.11\n4.1.10\n4.1.9\n4.1.8\n4.1.4\n3.5.5\n3.1.8\ncore\nOldVersion', description: 'Version Name', name: 'VERSION_NAME'],
[$class: 'hudson.model.ChoiceParameterDefinition', choices: 'origin/develop\norigin/hotfix/4.1.11\norigin/release/4.1.8\norigin/hotfix/4.1.7\norigin/hotfix/4.1.9\norigin/hotfix/4.1.10\norigin/release/4.1.6\norigin/release/4.1.5\norigin/hotfix/3.5.5', description: 'Git branch', name: 'GIT_BRANCH'],
[$class: 'BooleanParameterDefinition', defaultValue: false, description: 'Enable Gradle debug?', name: 'DEBUG']
] // According to Jenkins Bug: https://issues.jenkins-ci.org/browse/JENKINS-26143
}
} catch (err) {
userInput = [BUILD_FLAVOR: 'staging', BUILD_TYPE: 'Debug', CORE_BRANCH: 'NONE', VERSION_NAME: '4.1.12', GIT_BRANCH: 'origin/develop'] // if an error is caught set these values
}
}
Explanation:
I'm using the Try/Catch method to handle exceptions and then within the "try" section, I configured the question and possible answers to select from that I want to display to the user which starts the build.
Then, in the "catch" section I've put the default values I want to set in each one of the variables incase an exception is caught, which means that 1 minute has passed without selecting the relevant items.
Here are some useful links:
Pipeline: How to manage user inputs
pipeline-plugin/TUTORIAL.md

Resources