JShorthouse
JShorthouse

Reputation: 1670

Jenkins Declarative Pipeline - Dynamically Populate the Choices of an Input Step from the Output of a Command Run in the Workspace

I want to create an input step that prompts the user to select a git tag. To do this, I want to populate a dropdown box with the values returned by git tag.

Here is my current pipeline:

pipeline {
    agent any
    stages {
        stage('My Stage') {
            input {
                message "Select a git tag"
                parameters {
                    choice(name: "git_tag", choices: TAGS_HERE, description: "Git tag")
                }
            }
            steps {
                echo "The selected tag is: ${git_tag}"
            }
        }
    }
}

I would like TAGS_HERE to be a variable or method that contains the output given by the git tags command.

So far I have tried:

I have searched extensively for a solution but all the examples I can find avoid these two pitfalls by either exclusively using scripted pipeline steps or by using commands that are not workspace dependant.

Upvotes: 1

Views: 6085

Answers (2)

SmartTom
SmartTom

Reputation: 821

By improving the answer of @hakamairi, you can do something like this :

pipeline {
    agent any
    stages {
        stage('My Stage') {
            steps {
                script {
                    def GIT_TAGS = sh (script: 'git tag -l', returnStdout:true).trim()
                    inputResult = input(
                        message: "Select a git tag",
                        parameters: [choice(name: "git_tag", choices: "${GIT_TAGS}", description: "Git tag")]
                    )
                }
            }
        }
        stage('My other Stage'){
            steps{
                echo "The selected tag is: ${inputResult}"
            }
        }
    }
}

Upvotes: 5

hakamairi
hakamairi

Reputation: 4678

Maybe you are not in the node (in the old pipeline script way), you could try this. Possibly the script is not needed.

pipeline {
    agent any
    stages {
        stage('My Stage') {
            steps {
                def inputResult = input {
                    message "Select a git tag"
                    parameters {
                        choice(name: "git_tag", choices: getTags(), description: "Git tag")
                    }
                }
                echo "The selected tag is: ${inputResult.git_tag}"
            }
        }
    }
}

getTags should return choices separated by new line.

Upvotes: 0

Related Questions