conditionalize Parameter in Jenkins - jenkins

we are trying to parameter below code
If choice = dev and Method = post then show SITE_ID as an input
else show SITE_ID,CUSTOMER_ID,REGION,PLATFORM_ACCOUNT_ID,PLATFORM_TYPE as an input
right now it is showing all columns SITE_ID,CUSTOMER_ID,REGION,PLATFORM_ACCOUNT_ID,PLATFORM_TYPE independent of choice selection
pipeline {
parameters {
choice(
name: 'STAGE',
choices: ['dev', 'stable', 'preprod'],
description: 'The environment name (will not allow deploy on prod)'
)
choice(
name: 'METHOD',
choices: ['post', 'delete'],
description: 'Method name'
)
string(
name: 'SITE_ID', trim: true,
description: 'Please provide SITE_ID'
)
string(
name: 'CUSTOMER_ID', trim: true,
description: 'Please provide CUSTOMER_ID'
)
string(
name: 'REGION', trim: true,
description: 'Please provide REGION'
)
string(
name: 'PLATFORM_ACCOUNT_ID', trim: true,
description: 'Please provide PLATFORM_ACCOUNT_ID'
)
string(
name: 'PLATFORM_TYPE', trim: true,
description: 'Please provide PLATFORM_TYPE'
)
}
}

Related

Pipeline run on new branch - fails on first build, but succeeds if the build is replayed

I have a build job which is showing strange behavior. When I create a new branch, or tag, the first deploy will fail in my "Build config" stage. If I replay that same build with no alterations, it works beautifully. I assume it has something to do with the workspace, but the logs are truly unhelpful.
The log is just as unhelpful:
15:57:34 [Pipeline] stage
15:57:34 [Pipeline] { (Building config)
15:57:34 [Pipeline] withEnv
15:57:34 [Pipeline] {
15:57:34 [Pipeline] echo
15:57:34 Building config file /home/jenkins/workspace/MyProject_1.11.111/src/globals.inc.php
15:57:34 [Pipeline] script
15:57:34 [Pipeline] {
15:57:35 [Pipeline] readFile
15:57:35 [Pipeline] }
15:57:35 [Pipeline] // script
15:57:35 [Pipeline] }
15:57:35 [Pipeline] // withEnv
15:57:35 [Pipeline] }
15:57:35 [Pipeline] // stage
stage ('Building config'){
when {
anyOf{
buildingTag()
expression{
return params.DEPLOY == true
}
}
}
environment {
TEMPLATE_FILE="globals.template.inc.php"
CONFIG_FILE="globals.inc.php"
}
steps {
echo "Building config file ${SOURCE_DIR}/${CONFIG_FILE}"
script {
def inptext = readFile file: "${SOURCE_DIR}/${TEMPLATE_FILE}"
//save deploydate
def deployDate = (new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm")).format((new Date()))
inptext = inptext.replaceAll(~/¤SITE_TITLE¤/, "${SITE_TITLE}")
inptext = inptext.replaceAll(~/¤SITE_NAME¤/, "${SITE_NAME}")
inptext = inptext.replaceAll(~/¤SITE_FQDN¤/, "${SITE_FQDN}")
inptext = inptext.replaceAll(~/¤DEFAULT_FROM_EMAIL¤/, "${DEFAULT_FROM_EMAIL}")
inptext = inptext.replaceAll(~/¤SESSION_NAME¤/, "${SESSION_NAME}")
inptext = inptext.replaceAll(~/¤CERT_LOCATION¤/, "${CERT_LOCATION}")
inptext = inptext.replaceAll(~/¤MYSQL_HOSTNAME¤/, "${MYSQL_HOSTNAME}")
inptext = inptext.replaceAll(~/¤MYSQL_PORT¤/, "${MYSQL_PORT}")
inptext = inptext.replaceAll(~/¤MYSQL_DB_NAME¤/, "${MYSQL_DB_NAME}")
inptext = inptext.replaceAll(~/¤MYSQL_USERNAME¤/, "${MYSQL_USERNAME}")
inptext = inptext.replaceAll(~/¤MYSQL_PASSWORD¤/, "${MYSQL_PASSWORD}")
inptext = inptext.replaceAll(~/¤DEPLOY_DATE¤/, "${deployDate}")
inptext = inptext.replaceAll(~/¤GIT_BRANCH¤/, "${env.GIT_BRANCH}")
inptext = inptext.replaceAll(~/¤GIT_COMMIT¤/, "${env.GIT_COMMIT}")
inptext = inptext.replaceAll(~/¤GIT_TAG¤/, "${env.TAG_NAME}")
writeFile file: "${SOURCE_DIR}/${CONFIG_FILE}", text: inptext
}
}
}
I am aware that solutions like dotenv exist, but I can't implement that at the moment
If it has any relevance, here is the preceding stage as well..
stage ('Staging'){
steps {
script {
properties([
parameters([
booleanParam(
defaultValue: false,
description: 'whether to trigger a deploy',
name: 'DEPLOY'
),
string(
defaultValue: "${env.BRANCH_NAME}",
name: 'BUILD_NAME'
),
string(
defaultValue: '',
description: 'path to deploy to',
name: 'DEPLOY_DIR'
),
string(
defaultValue: '',
description: 'SSH server name to deploy to',
name: 'SSH_SERVER_NAME'
),
string(
defaultValue: '',
description: 'Username for SSH connection',
name: 'SSH_USERNAME'
),
string(
defaultValue: '',
description: 'Title of the site',
name: 'SITE_TITLE'
),
string(
defaultValue: '',
name: 'SITE_NAME'
),
string(
defaultValue: '',
description: 'Fully Qualified Domain Name',
name: 'SITE_FQDN',
trim: true
),
string(
defaultValue: '',
description: 'email to send from',
name: 'DEFAULT_FROM_EMAIL',
trim: true
),
string(
defaultValue: '',
description: 'Sessionname (this should be unique foer every environment)',
name: 'SESSION_NAME',
trim: true
),
string(
defaultValue: '',
description: 'full path to certificate location',
name: 'CERT_LOCATION',
trim: true
),
string(
defaultValue: 'localhost',
description: 'MySQL Servername',
name: 'MYSQL_HOSTNAME',
trim: true
),
string(
defaultValue: '3306',
description: 'MySQL port number',
name: 'MYSQL_PORT',
trim: true
),
string(
defaultValue: '',
description: 'MySQL database name',
name: 'MYSQL_DB_NAME',
trim: true
),
string(
defaultValue: '',
description: 'MySQL username ',
name: 'MYSQL_USERNAME',
trim: true
),
string(
defaultValue: '',
description: 'Password for MYSQL_USERNAME',
name: 'MYSQL_PASSWORD',
trim: true
)
])
])
currentBuild.displayName = "${params.BUILD_NAME}-${env.BUILD_NUMBER}"
}
echo "Cleanup build artifacts"
dir("${WORKSPACE}/build"){
deleteDir()
}
dir("${WORKSPACE}/src/!devHelpers"){
deleteDir()
}
echo "Prepare for build"
//re-create folders
sh "mkdir ${WORKSPACE}/build ${WORKSPACE}/build/api ${WORKSPACE}/build/coverage ${WORKSPACE}/build/logs ${WORKSPACE}/build/pdepend ${WORKSPACE}/build/phpdox"
echo "Running composer"
sh "composer install -o -d ${SOURCE_DIR}"
}
}

Jenkins declarative pipeline: if-else statement inside parameters directive

I'm trying to display a choice parameter if I have options to choose from, or else display an input text, something like this (which does not work):
pipeline {
agent any
parameters {
if (someOptions) {
choice(name: 'FIELD_NAME', choices: "$someOptions", description: 'Field description')
} else {
string(name: 'FIELD_NAME', defaultValue: '', description: 'Field description')
}
}
environment {
// environment params
}
stages {
// stages
}
}
Is there a way of doing this?
To expand on #Matt Schuchard's comment, here's what this might look like:
def my_param = []
if (someOptions) {
my_param = [$class: 'ChoiceParameter',
name: 'FIELD_NAME',
choiceType: 'PT_SINGLE_SELECT',
description: 'Choose the desired option',
script:
[$class: 'GroovyScript',
fallbackScript:
[classpath: [], sandbox: false, script: 'return ""'],
script:
[classpath: [], sandbox: false, script: "return $someOptions"]
]
]
} else {
my_param = [$class: 'StringParameterDefinition',
name: 'FIELD_NAME',
defaultValue: false,
description: '']
}
properties([
parameters([my_param,
// other parameters
Don't forget to approve Groovy scripts in script approval console.

Jenkins pipeline input script with one prompt only

Don't need 2 prompt in Jenkins pipeline with input script. In snippet, there is highlighted 1 and 2 where pipeline prompt 2 times for user input.
If execute this pipeline, prompt 1 will provide user to "Input requested" only, so no option to "Abort". Prompt 2 is okay as it ask to input the value and also "Abort" option.
Prompt 1 is almost useless, can we skip promt this and directly reach to prompt 2?
pipeline {
agent any
parameters {
string(defaultValue: '', description: 'Enter the Numerator', name: 'Num')
string(defaultValue: '', description: 'Enter the Denominator', name: 'Den')
}
stages {
stage("foo") {
steps {
script {
if ( "$Den".toInteger() == 0) {
echo "Denominator can't be '0', please re-enter it."
env.Den = input message: 'User input required', ok: 'Re-enter', // 1-> It will ask whether to input or not
parameters: [string(defaultValue: "", description: 'Enter the Denominator', name: 'Den')] // 2-> It will ask to input the value
}
}
sh'''#!/bin/bash +x
echo "Numerator: $Num\nDenominator: $Den"
echo "Output: $((Num/Den))"
'''
}
}
}
}
Yes, you can simplify the input by using $class: 'TextParameterDefinition'.
e.g.
pipeline {
agent any
parameters {
string(defaultValue: '', description: 'Enter the Numerator', name: 'Num')
string(defaultValue: '', description: 'Enter the Denominator', name: 'Den')
}
stages {
stage("foo") {
steps {
script {
if ( "$Den".toInteger() == 0) {
env.Den = input(
id: 'userInput', message: 'Wrong denominator, give it another try?', parameters: [
[$class: 'TextParameterDefinition', defaultValue: '', description: 'Den', name: 'den']
]
)
}
}
sh'''#!/bin/bash +x
echo "Numerator: $Num\nDenominator: $Den"
echo "Output: $((Num/Den))"
'''
}
}
}
}
If you want to go the extra mile and ask for both values:
def userInput = input(
id: 'userInput', message: 'Let\'s re-enter everything?', parameters: [
[$class: 'TextParameterDefinition', defaultValue: '', description: 'Denominator', name: 'den'],
[$class: 'TextParameterDefinition', defaultValue: '', description: 'Numerator', name: 'num']
]
)
print userInput
env.Den = userInput.den
env.Num = userInput.num

Jenkins: How to use jenkins pipeline Multiple parameters

I have a Jenkinsfile instance using ansible-playbook to deploy webmachine.
I need to specified ansible-playbook parameters more than one at once.
I got
WorkflowScript: 25: Multiple occurrences of the parameters section
my jenkinsfile like this,
pipeline {
agent none
stages {
stage('docker-compose up') {
input {
message "Should we continue?"
ok "Yes, do it!"
parameters {
string(name: 'KIBANA_TAG', defaultValue: '', description: 'input tag for ansible command.')
}
parameters {
string(name: 'FLUENT_TAG', defaultValue: '', description: 'input tag for ansible command.')
}
parameters {
string(name: 'ES_TAG', defaultValue: '', description: 'input tag for ansible command.')
}
parameters {
string(name: 'HOST', defaultValue: '', description: 'input tag for ansible command.')
}
}
steps {
sh "rd6-admin#qa ansible-playbook /tmp/qa/docker-compose-up.yml -e fluent_tag=${params.FLUENT_TAG} -e kibana_tag=${params.KIBANA_TAG} -e es_tag=${params.ES_TAG} -e host=${params.HOST}"
}
}
}
}
what part should i fix?
The comma separator is not working in version 2.222.1. I removed the comma and it is now working.
parameters {
string(name: 'KIBANA_TAG', defaultValue: 'default', description: 'input tag for ansible command.')
string(name: 'FLUENT_TAG', defaultValue: 'default', description: 'input tag for ansible command.')
string(name: 'ES_TAG', defaultValue: 'default', description: 'input tag for ansible command.')
string(name: 'HOST', defaultValue: 'default', description: 'input tag for ansible command.')
}
parameters {
string(name: 'KIBANA_TAG', defaultValue: 'default', description: 'input tag for ansible command.')
string(name: 'FLUENT_TAG', defaultValue: 'default', description: 'input tag for ansible command.')
string(name: 'ES_TAG', defaultValue: 'default', description: 'input tag for ansible command.')
string(name: 'HOST', defaultValue: 'default', description: 'input tag for ansible command.')
}
Try this. Multiple occurrences of the parameters section means that there is only one parameters{} allowed and you have to place your parameters inside there.

What's the syntax of get the user's input from jenkins's pipeline step?

I build my job throuth jenkins's pipeline and useing the Snippet Generator to create my code like this :
node {
stage 'input'
input id: 'Tt', message: 'your password:', ok: 'ok', parameters: [string(defaultValue: 'mb', description: 'vbn', name: 'PARAM'), string(defaultValue: 'hj', description: 'kkkk', name: 'PARAM2')]
// here I need get the text user input , like `PARAM` or `PARAM2`
}
As described above, what's the syntax of get parameter ?
I'm kind of limited to test the code but I think it should be like:
node {
stage 'input'
def userPasswordInput = input(
id: 'userPasswordInput', message: 'your password', parameters: [
[$class: 'TextParameterDefinition', defaultValue='mb', description: 'vbn', name: 'password']
]
)
echo ("Password was: " + userPasswordInput)
}
node {
stage 'input'
def userPasswordInput = input(
id: 'Password', message: 'input your password: ', ok: 'ok', parameters: [string(defaultValue: 'master', description: '.....', name: 'LIB_TEST')]
)
echo ("Password was: " + userPasswordInput)
}
with the idea Joschi give , the code above works well .Thanks for Joschi again very much.

Resources