Skip to content

Mastering Jenkins Parameterized Builds

  • 14 min read

Automating your software builds and deployments with Jenkins? That’s a smart move. But are you making the most of it? Imagine a world where your pipelines can adapt to any scenario, where one size doesn’t fit all, and where flexibility reigns supreme. This is the power of Jenkins parameterized builds.

This article will show you how to use Jenkins parameterized builds. You’ll see how they can transform your pipelines into reusable and adaptable assets. This will give you the edge needed for the modern DevOps landscape. We will cover why they’re crucial, how to set them up, and how to get the most out of them. Let’s begin this journey of mastery.

Why Use Jenkins Parameterized Builds?

Why bother with parameterized builds? Can’t you just create specific pipelines for every scenario? You could, but that would soon become a chaotic mess. Parameterized builds bring structure and efficiency, with a sprinkle of magic. Let’s dive into the key reasons why you need this in your DevOps arsenal:

  • Reusability: Instead of creating separate pipelines for different environments (development, staging, production), one parameterized pipeline can handle them all. You simply pass in environment-specific parameters, which avoids code duplication and saves time. This alone justifies their importance.
  • Flexibility: Each project and environment have their own needs. Parameterized builds let you adapt your pipelines to those needs. It could be choosing the branch, setting the target server, or even deciding which test to run. This means a single pipeline can be used in many different ways.
  • Consistency: Having parameters ensures that all your deployments are done with the same, structured process, reducing the risk of errors. By defining the parameters and their possible values, you’re enforcing standards and reducing deployment inconsistencies.
  • Efficiency: Manual changes are prone to error. Parameters will bring repeatability and reduce the need for manual intervention. You no longer have to dive into the pipeline code every time a small change is needed.
  • Collaboration: Parameters make it easier for teams to understand, use, and modify pipelines. Others can grasp what parameters exist and how they impact the process. This results in more efficient teamwork.
  • Reduced Maintenance: When the time comes to make changes, a single parameterized pipeline is easier to maintain than many copies. Updates to the deployment process now happen in one place, making life much easier for everyone.
  • Customized Workflows: Parameters can be used to create diverse workflows. Based on the parameter used, you can change the steps. Maybe one parameter calls for a quick check, while another launches a full-fledged deployment.
  • Adapt to Change: Businesses evolve, and so do your deployment processes. Parameterized builds make it easier to change these processes. It’s now simpler to adjust variables without rewriting entire pipelines.

Types of Parameters in Jenkins

Jenkins provides a variety of parameter types to suit different needs. Let’s explore what’s available so you know how to create effective parameterized builds:

  • String Parameter: For text input (e.g., branch name, application version). It allows any string value. Use it for any arbitrary text input like a server address or a version number.
  • Boolean Parameter: For true/false choices (e.g., run unit tests, deploy to production). Very simple, with just two options. Good for on/off switches for build steps.
  • Choice Parameter: For a drop-down list of predefined options (e.g., environment type, build target). Great when you need to pick from set options. Think of deployment targets or build types.
  • Multi-line String Parameter: For multi-line text input (e.g., configuration files). Similar to string parameters, but it allows text to span multiple lines. Useful when you need to paste configuration code or similar long texts.
  • Password Parameter: For sensitive input (e.g., API keys, passwords). It’s like a string, but the value is masked. Ideal for credentials and secrets.
  • File Parameter: To upload files to the build process. This could be configuration files or data files needed in your builds.
  • Text Parameter: A variation of the string parameter, it allows a longer text input (e.g., commit message). This is useful when you expect long input from the user, like an explanation for a change.

Setting Up a Parameterized Build in Jenkins

Ready to create your first parameterized build? Follow these steps, and you’ll be there in no time:

  1. Create a New Job: Go to your Jenkins dashboard and click “New Item”. Choose a project type (e.g., Freestyle project, Pipeline) and enter a name for your job. Click “OK”.
  2. Enable Parameterization: In the job’s configuration page, find the “This project is parameterized” checkbox and select it. This action will reveal the area where parameters are defined.
  3. Add Parameters:
    • Click “Add Parameter”.
    • Choose the desired parameter type from the drop-down menu (e.g., String Parameter, Choice Parameter).
    • Configure the parameter based on your choice.
      • For string parameters:
        • Name: Use a descriptive name (e.g., BRANCH_NAME).
        • Default value: Set a default value (e.g., main).
        • Description: Add a description (e.g., “The branch to build”).
      • For choice parameters:
        • Name: Define a name for your parameter.
        • Choices: List options, with each on a new line.
        • Description: Add a help text for the parameter.
      • For boolean parameters:
        • Name: Give the parameter a name.
        • Default Value: Set to either True or False.
        • Description: Provide a quick explanation of what this parameter does.
      • For password parameters:
        • Name: Name your password parameter.
        • Description: Briefly describe what you’re using it for.
    • Add as many parameters as needed. Remember, you want to tailor the flexibility of your process, so plan well.
  4. Use Parameters in Your Build: After you defined your parameters, you can use them in your build process.
    • In a Freestyle project:
      • Access the parameter value as ${PARAMETER_NAME}. For example, if you defined a parameter named BRANCH_NAME, use ${BRANCH_NAME} in your Git branch specification field.
      • Use the parameters in the scripts you run in the build steps.
    • In a Pipeline project:
      • Use parameters in your Jenkinsfile, using params.PARAMETER_NAME syntax. For example, use params.BRANCH_NAME to refer to the previously defined BRANCH_NAME parameter.
      • Make use of them in your pipeline’s various stages.
  5. Save and Build: After setting everything up, click “Save”. You can initiate a build by clicking “Build with Parameters”. The parameters you defined will be visible, and you can adjust the value before the build starts.
  6. Test your Build: Confirm that your build process uses the parameters as expected. Double check the log for the values you used, and if your test runs as expected.

Example: Using Parameters in a Pipeline

Let’s see how to use parameters inside a Jenkinsfile. Here’s a simple example:

pipeline {
    agent any
    parameters {
        string(name: 'BRANCH_NAME', defaultValue: 'main', description: 'The branch to build')
        choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'prod'], description: 'Target environment')
        booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run unit tests?')
    }
    stages {
        stage('Checkout') {
            steps {
                git branch: "${params.BRANCH_NAME}",
                url: 'https://your-repo-url.git'
            }
        }
        stage('Build') {
            steps {
                sh 'mvn clean install'
            }
        }
        stage('Tests') {
            when {
                expression { params.RUN_TESTS == true }
            }
            steps {
                sh 'mvn test'
            }
        }
        stage('Deploy') {
            steps {
                script {
                    if(params.ENVIRONMENT == 'prod') {
                        echo "Deploying to production"
                        sh './deploy.sh prod'
                    }
                    else if (params.ENVIRONMENT == 'staging') {
                       echo "Deploying to staging"
                       sh './deploy.sh staging'
                    }
                    else {
                        echo "Deploying to development"
                        sh './deploy.sh dev'
                    }
                }
            }
        }
    }
}

In this example, we’ve defined three parameters:

  • BRANCH_NAME: The branch to checkout, with main as the default value.
  • ENVIRONMENT: The target deployment environment from a list of choices.
  • RUN_TESTS: A boolean which will decide if tests are ran.

The pipeline uses these parameters to:

  • Checkout the correct branch.
  • Conditionally run the tests based on the value of RUN_TESTS.
  • Deploy to different environments according to the selected ENVIRONMENT.

Advanced Techniques with Parameterized Builds

Once you’ve got the basics down, explore the advanced techniques to really boost your Jenkins skills:

  • Conditional Steps:
    • Use parameters to decide whether certain build steps are executed.
    • For instance, run a certain step only when deploying to production.
    • In pipelines, the when directive will help you to conditionally execute stages or steps based on conditions.
  • Dynamic Parameter Options:
    • Generate your parameter options dynamically using scripts, not hardcoded.
    • For instance, you can pull branch names from your Git repo.
    • The “Active Choice Parameter” plugin can be a great help.
  • Parameter Validation:
    • Ensure that your parameters fit expected formats.
    • Use scripts to validate the provided values.
    • The “Extended Choice Parameter” plugin offers validation functionality.
  • Chained Parameters:
    • Use one parameter to dictate the available options for another parameter.
    • For example, choose an environment and then see available servers for that environment.
    • Again, the “Active Choice Parameter” is very useful for this.
  • Parameter Defaults Based on Environment Variables:
    • Use environment variables to determine default parameter values.
    • This will help to configure your builds based on the system running the build.
    • Access environment variables using ${ENV_VARIABLE_NAME} in your parameters’ default value.
  • Secure Storage:
    • Avoid hardcoding sensitive data, like passwords.
    • Store sensitive parameters using plugins such as the “Credentials Binding” plugin, to access those stored values.
    • Use Jenkins credentials to securely manage your secrets.
  • Pipeline Library:
    • Store common pipeline code in a shared library and use parameters to tailor your builds.
    • This promotes the reuse of code across different pipelines.
    • It helps standardize the build process.
  • Plugin Integration:
    • Use plugins such as the “Parameterized Trigger Plugin” to trigger downstream jobs with different parameters.
    • This will help to chain build process and create more complex workflows.
    • Use it to create a complete continuous delivery pipeline.

Plugin Spotlight: Enhancing Parameterized Builds

Here are some plugins to take your Jenkins parameterized builds to the next level:

  • Active Choice Parameter: Allows dynamic parameter options. You can populate parameter values based on the selection of a previous one.
  • Extended Choice Parameter: Offers extended parameter configuration options, such as descriptions, validations, and multiple selection, which goes beyond the basics.
  • Parameterized Trigger Plugin: Lets you trigger other builds with customized parameters.
  • Credentials Binding Plugin: Securely injects credentials into your builds without exposing them in your Jenkinsfile or build configuration.
  • EnvInject Plugin: Injects environment variables into your build environment, which can be useful when setting up parameters based on your environment.

Best Practices for Parameterized Builds

Let’s explore some best practices to keep in mind when using parameterized builds:

  • Use Clear Names: Make the parameter names clear and easy to understand. Names such as ENVIRONMENT or BRANCH_NAME are better than var1 or p2.
  • Provide Descriptions: Give descriptions for each parameter that explain their purpose. This will help others (including your future self) understand them.
  • Set Default Values: Define sensible default values. This simplifies the build execution, especially for routine builds.
  • Validate Inputs: Use validation to avoid errors. You can validate the parameter’s input through scripts. Or with plugins.
  • Group Parameters: Group your parameters into sections in order to enhance the visibility and use of your parameters.
  • Secure Sensitive Parameters: Store sensitive data properly, and never expose it in your builds. Make use of Jenkins credentials or other secret management tools.
  • Keep it Simple: Start simple, then add complexity as you go. Too many parameters at once can make your builds harder to manage.
  • Test Often: Check the build with different parameter combinations to avoid unexpected issues. This will catch potential problems early.
  • Document Everything: Explain how to use the parameters in your project documentation. This will make your pipelines easier for others to use and maintain.
  • Avoid Magic Values: Never hard code values in the pipeline that should be parameters. All values that can vary between environments, or should be flexible, should be parameters.

Troubleshooting Common Issues

Even with the best planning, things can go wrong. Here are some common problems with parameterized builds and how to fix them:

  • Parameter not being recognized: Check the parameter names and that you have used the correct syntax (e.g., ${PARAMETER_NAME} or params.PARAMETER_NAME). Check for typos.
  • Build failing due to wrong input: Check and validate the inputs to make sure they follow the correct format. Do not hesitate to add more validation rules.
  • Default values not being used: Check that you have set up default values correctly in your job configuration. Also, make sure those values are correctly used in the build.
  • Sensitive data being exposed: Never print secure data in build logs. Use credential plugins to avoid that. Check that sensitive parameters are being used correctly, and that they aren’t exposed to anyone.
  • Plugin conflicts: If you are using many plugins, they may conflict with each other. Try to disable a few plugins and recheck, or upgrade them to the latest version.
  • Incorrect conditional steps: Check the when directive or other conditional logic in your pipeline to ensure they are written correctly.

Jenkins Parameterized Builds: A Deep Dive

Let’s examine different ways of how to get the most out of parameterized builds:

  • Dynamic Environments: Combine choice parameters with dynamic scripts to create environments on the fly. For example, the environment name is a parameter, and the pipeline creates a new environment based on that parameter.
  • Rolling Deployments: Trigger rolling deployments by using a parameter to specify the number of instances to deploy. The pipeline then deploys new versions gradually.
  • Customized Test Runs: Use multiple choice parameters to select which tests to run based on code changes. For instance, you could select from a drop-down menu to run functional, integration or unit tests.
  • Pipeline as Code: Use a Jenkinsfile to define your pipeline, and leverage parameters to create flexible, yet maintainable pipelines. Storing your pipelines as code promotes code reuse.
  • Automated Promotion: Use parameters to promote builds through different environments. Your pipeline can deploy to staging and then use another parameter to promote to production.
  • Triggering Downstream Jobs: Use the “Parameterized Trigger Plugin” to start other Jenkins jobs. Use a parameter to decide which job to trigger. This will help you chain workflows and orchestrate complex deployments.
  • Automated Rollbacks: Add a parameter that triggers an automated rollback if the deployment fails. Use conditional steps to detect a failed deployment. Then use another parameter to roll back to the previous stable version.
  • Blue/Green Deployments: Set parameters to enable or disable blue/green deployment strategies. You can use this parameter to decide between doing a blue/green or canary release.

Future Trends in Jenkins Parameterized Builds

The world of DevOps is constantly changing, and this also impacts Jenkins and parameterized builds. Here’s a few future trends:

  • AI-Powered Parameter Configuration: Using AI to suggest ideal parameters and values based on previous builds and patterns. AI may also create new values based on the patterns.
  • Improved User Interface: A modern UI for setting and managing parameters. Providing a more friendly user experience. This might include a UI where you could use drag and drop parameters, and visually configure them.
  • More Integration with Cloud Platforms: Deeper integration with cloud services, like AWS, Azure, and Google Cloud. This will allow you to create and use parameters from the different cloud services, to improve your builds.
  • Enhanced Security: More secure ways to handle sensitive parameters through integration with secret management systems. This will help developers work without compromising security.
  • Automated Parameter Recommendations: Jenkins may provide suggestions for the right parameters to use, based on the project being developed.
  • Event-Driven Builds: Parameters can be used based on events or external triggers to start automated builds. So, you might want to trigger builds when a commit is made, based on parameters in the commit.
  • More Granular Control: Additional control over how and when parameters are used. New settings might help you determine who can change specific parameters, improving security.

Embracing Parameterized Builds: A Flexible Future

Jenkins parameterized builds are not just a feature; they’re a mindset. You should move away from rigid, inflexible pipelines. Use parameters to create adaptable, reusable, and efficient automated workflows. By embracing parameterized builds, you’re investing in a future-proof approach to continuous integration and continuous delivery.

This journey towards mastery of Jenkins parameterization might look like a long one. But once you start using parameters, you’ll quickly see the power and flexibility they bring. You will no longer have to manage separate pipelines, but instead a set of configurable builds. So, go ahead, explore, experiment, and transform your Jenkins builds today.