TechAnek

In Jenkins, securely passing credentials or secrets to your pipeline jobs is crucial for maintaining security and efficiency. This guide will walk you through the steps to use Jenkins credentials in an Active Choice Parameter Script. Let’s dive into each step required to achieve this.

The Active Choices plugin enhances parametrized freestyle Jenkins jobs by enabling the creation of scripted, dynamic, and interactive job parameters. These parameters can be updated in real-time and displayed as combo-boxes, check-boxes, radio-buttons, or advanced HTML UI components.

Scripting for Active Choices parameters is done using Groovy or optionally through Scriptler Groovy scripts. These scripts allow integration with the Jenkins Java API, system environment variables, global node properties, and can incorporate external Java and JavaScript libraries.

Here’s some use-cases:

Dynamic AWS S3 Bucket Selection

In this use case, you want to dynamically generate a list of AWS S3 buckets based on Jenkins credentials. The script will securely use AWS access keys stored in Jenkins credentials to fetch and display the bucket names as selectable options in jenkins parameters.

Dynamic Git Branch Selection Based on Credentials

This use case involves dynamically listing Git branches from a repository that requires authentication. The Active Choice Parameter Script will use stored Git credentials to access the repository and fetch the branch names.

Dynamic API Endpoint Selection

Here, you want to dynamically populate a list of API endpoints based on credentials. The script will use these credentials to authenticate with the API and retrieve the available endpoints or services.

Prerequisite: Install Active Choice Parameters Plug-in

Before you begin, ensure you have the Active Choice Parameters plugin installed. Follow these steps:

  1. Navigate to Dashboard > Manage Jenkins.
  2. Click on Manage Plugins.
  3. Go to the Available tab.
  4. Search for Active Choice Parameters.
  5. Install the plugin and restart Jenkins if necessary.

 

Step 1: Setting Up Jenkins Credentials/Secrets

Next, you need to create the credentials that will be used in your Jenkins job.

  1. Go to Dashboard > Manage Jenkins > Credentials > System > Global credentials.
  2. Click on Add Credentials.
  3. Choose the appropriate type of credential (e.g., Username with password).
  4. Fill in the required fields and save.

Step 2: Creating a Parameterized Jenkins Job

Create a Jenkins pipeline job that will use these credentials.

  1. Create a new item in Jenkins and choose Pipeline
  2. Under the Build Triggers section, check This project is parameterized.
  3. Add an Active Choice Parameter.

Step 3: Writing Groovy Script for Using Credentials/Secrets

You need to write a Groovy script to fetch and use the credentials within the Active Choice Parameter. Here is an example script:

properties ([
    parameters ([
        [$class: 'CascadeChoiceParameter', 
            choiceType: 'PT_SINGLE_SELECT', 
            description: 'Select from parameter', 
            filterLength: 1, 
            filterable: false, 
            name: 'demo', 
            randomName: 'choice-parameter-1',
            script: [
                $class: 'GroovyScript',
                script: [
                    classpath: [],
                    sandbox: false,
                    script: '''
import com.amazonaws.auth.AWSStaticCredentialsProvider
import com.amazonaws.auth.BasicAWSCredentials
import com.amazonaws.services.s3.AmazonS3ClientBuilder
import com.amazonaws.services.s3.model.Bucket
import hudson.model.*
import jenkins.model.*

// Define the credentials ID used in Jenkins
def credentialsId = 'accessAndSecretKeys' // Replace with your actual AWS credentials ID

// Fetch the AWS credentials from Jenkins
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
    com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl.class,
    jenkins.model.Jenkins.instance,
    null,
    null
).find { it.id == credentialsId }

if (creds == null) {
    throw new RuntimeException("AWS credentials not found in Jenkins with ID: ${credentialsId}")}

// Extract AWS access key and secret key from the credentials
def awsAccessKey = creds.accessKey
def awsSecretKey = creds.secretKey.plainText
def region = 'us-east-1' // Define the AWS region

// Initialize the S3 client
def credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey)
def s3Client = AmazonS3ClientBuilder.standard()
    .withCredentials(new AWSStaticCredentialsProvider(credentials))
    .withRegion(region)
    .build()

// Fetch the list of S3 buckets
List buckets = s3Client.listBuckets()
List hello = []

// Return the list of bucket names
hello = buckets.collect { it.getName() }
return hello ''' ] ] ] ]) ]) pipeline { agent any stages { stage('Hello') { steps { echo 'Hello World' } } } }

Step 4: Approve Groovy Script

Jenkins will require you to approve the script for security reasons.

  1. Go to Dashboard > Manage Jenkins > In-process Script Approval.
  2. Review the script and approve it.

Step 5: Check Output

After approving the script, run your Jenkins job and check the output to ensure that the “Build with Parameters” option appears and that the expected parameters are displayed correctly.

 

Conclusion

By following these steps, you can securely pass Jenkins credentials or secrets to your Active Choice Parameter Script, enhancing your job’s security and functionality. Ensure to regularly check and update your credentials and script approvals to maintain a secure and efficient Jenkins environment.