~/jenkins/how-create-ui-form-drop-down-jenkinsfile-run-for-different-condition.md

Jenkinsfile - How to Create UI Form Text fields, Drop-down and Run for Different Conditions

2 min readOctober 07, 2022by Gorav Singal#cicd#build#jenkins
// TL;DR

Use the parameters block in your Jenkinsfile with choice() and string() to create UI dropdowns and text fields. Conditional stages then use when { expression } to run only for selected environments.

Jenkinsfile - How to Create UI Form Text fields, Drop-down and Run for Different Conditions

Introduction

I had to write a CICD system for one of our project. I had to deploy artifacts on different environments. We did not want it to be fully automated. This deployment job should be manually run, when we are fully sure.

The job should provide user the option of:

  • Which Environment (Dev/Stage/Prod)
  • Which Artifact to deploy
  • What is the version of artifact

Jenkinsfile for UI and Run Automation

Here is the complete Jenkinsfile.

pipeline {
    agent {
        node {
            label "MyNode"
        }
    }
    stages {
        stage('Take User Input') {
            steps {
                script {
                    properties([
                        parameters([
                            choice(
                                choices: ['Dev', 'Stage', 'Prod'], 
                                name: 'DeployEnv',
                                description: "Select the environment"
                            ),
                            choice(
                                choices: ['ws-1', 'ws-1', 'worker-1'], 
                                name: 'ArtifactId', 
                                description: "Which artifact",
                            ),
                            string(
                                defaultValue: 'version of build', 
                                name: 'Version', 
                                description: "Write the version of build",
                                trim: true
                            )
                        ])
                    ])
                }
            }
        }
        stage('Run deployer') {
            steps {
                echo 'Deploying Artifacts to Kubernetes Env...'

                withCredentials([
                    [$class: 'UsernamePasswordMultiBinding', 
                    credentialsId:"MY_CRED_ID",
                        usernameVariable: 'AZURE_SERVICE_USERNAME', 
                        passwordVariable: 'AZURE_SERVICE_SECRET'],
                    [$class: 'UsernamePasswordMultiBinding', credentialsId:"MY_API_KEY",
                        usernameVariable: 'ARTIFACTORY_USERNAME', 
                        passwordVariable: 'ARTIFACTORY_PASSWORD']
                ]) {
                    sh """
                        # installing kubectl
                        sudo curl -LO "https://dl.k8s.io/release/v1.25.2/bin/linux/amd64/kubectl"
                        sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
                        kubectl version --client

                        echo "deploy to env=${params.DeployEnv}, artifact=${params.ArtifactId}, version=${params.Version}"
                        
                        echo "Preparing runtime env..."
                        python3.8 -m pip install virtualenv
                        python3.8 -m venv python_env
                        source python_env/bin/activate
                        python3.8 -m pip install --upgrade pip
                        python3.8 -m pip install -r requirements.txt -i https://${ARTIFACTORY_USERNAME}:${ARTIFACTORY_PASSWORD}@artifactory.myorg.com/artifactory/api/pypi/pypi-myorg-release/simple

                        echo "Ready to run deployment..."
                        python3.8 deploy.py "${params.DeployEnv}" "${params.ArtifactId}" "${params.Version}"

                        deactivate
                    """
                }
            }
        }
    }
}

Lets break down the file in following parts:

Taking User Input from UI WIdgets

Jenkins provides option to render few UI widgets and taking their values. In my case, the values are static. But, you can take dynamic values too.

For example, a drop down is rendered by:

choice(
    choices: ['Dev', 'Stage', 'Prod'], 
    name: 'DeployEnv',
    description: "Select the environment"
)

Accessing selected UI widget values

Whatever user selects, its value will be stored in variable name mentioned in name attribute. To access above mentioned value, I will use ${params.DeployEnv} in shell script step.

Example, this is how I’m using it:

echo "deploy to env=${params.DeployEnv}, artifact=${params.ArtifactId}, version=${params.Version}"

Fetching Multiple Credentials

You can store as many credentials in Jenkins, and I’ve fetched two credentials at the same time by:

withCredentials([
        [$class: 'UsernamePasswordMultiBinding', 
        credentialsId:"MY_CRED_ID",
            usernameVariable: 'AZURE_SERVICE_USERNAME', 
            passwordVariable: 'AZURE_SERVICE_SECRET'],
        [$class: 'UsernamePasswordMultiBinding', credentialsId:"MY_API_KEY",
            usernameVariable: 'ARTIFACTORY_USERNAME', 
            passwordVariable: 'ARTIFACTORY_PASSWORD']
    ]) {
        ...
}

For example, MY_CRED_ID is the key stored in Jenkins, and I’m exposing its username and password in environment variables: AZURE_SERVICE_USERNAME, AZURE_SERVICE_SECRET

And finally, I’m running a python code, which has the automation to deploy files on kubernetes.

And again, if you do not want to run this job on every code commit, i.e. you want this job to run manually only. See How not to run Jenkin job on Code-commit

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Jenkins Pipeline with Jenkinsfile - How To Schedule Job on Cron and Not on Code Commit

Jenkins Pipeline with Jenkinsfile - How To Schedule Job on Cron and Not on Code Commit

Introduction In this post we will see following: How to schedule a job on cron…

How to Fetch Multiple Credentials and Expose them in Environment using Jenkinsfile pipeline

How to Fetch Multiple Credentials and Expose them in Environment using Jenkinsfile pipeline

Introduction In this post, we will see how to fetch multiple credentials and…

Jenkins Pipeline - How to run Automation on Different Environment (Dev/Stage/Prod), with Credentials

Jenkins Pipeline - How to run Automation on Different Environment (Dev/Stage/Prod), with Credentials

Introduction I have an automation script, that I want to run on different…

How to Git Clone Another Repository from Jenkin Pipeline in Jenkinsfile

How to Git Clone Another Repository from Jenkin Pipeline in Jenkinsfile

Introduction There are some cases, where I need another git repository while…

A Jenkins Groovy Pipeline for Building Python Projects and Pushing to Artifactory

A Jenkins Groovy Pipeline for Building Python Projects and Pushing to Artifactory

Introduction In this post, we will see a sample Jenkin Pipeline Groovy script…

Python Build Quality Gates with Pylint and Unittest Coverage Thresholds

Python Build Quality Gates with Pylint and Unittest Coverage Thresholds

Introduction It is very important to introduce few process so that your code and…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…