jenkins|October 07, 2022|2 min read

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

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

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…

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…

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…

Example Jenkin Groovy Pipeline Script for Building Python Projects with Git Events and Push to Artifactory

Example Jenkin Groovy Pipeline Script for Building Python Projects with Git Events and Push to Artifactory

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

Python - How to Maintain Quality Build Process Using Pylint and Unittest Coverage With Minimum Threshold Values

Python - How to Maintain Quality Build Process Using Pylint and Unittest Coverage With Minimum Threshold Values

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

Latest Posts

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Most developers use Claude Code like a search engine — ask a question, get an…

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Every office lobby has the same problem: a visitor walks in, nobody’s at the…

Server Security Best Practices — Complete Hardening Guide for Production Systems

Server Security Best Practices — Complete Hardening Guide for Production Systems

Every breach post-mortem tells the same story: an unpatched service, a…

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

If you’re a Senior Engineer (L5) preparing for Staff (L6+) roles at MAANG…

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF have been in the OWASP Top 10 for over a decade. They’re among the…

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

The OWASP Top 10 is the industry standard for web application security risks. If…