1

I am trying to get a list of Vsphere templates and use them as parameters in Jenkins. I have tried using a function and running the PowerShell command.

def findtemplates() {
  def $vmTemplate = "powershell -command 'Connect-VIServer -server server -User user -Password pass -Force; Get-Template | select name'"
    return $vmTemplate
}

And in parameter section:

      parameters {
    choice(name: 'Template', choices: findtemplates(), description: 'test')
  }

But does not work. Any help would be appreciated.

1 Answer 1

3

Call the powershell step (or pwsh for PS 7+) with argument returnStdout: true to get the output of the PowerShell command:

def findtemplates() {
  return powershell( returnStdout: true, script: '''
      Connect-VIServer -server server -User user -Password pass -Force
      Get-Template | select name'
    ''')
}

Note the use of ''' to pass a multiline script to the powershell step.

I guess you hardcoded user name and password only for brevity. A more complete example would look like:

def findtemplates() {                       
  withCredentials([ usernamePassword( credentialsId: 'ReplaceWithYourCredentialsId',
                                      usernameVariable: 'VIServerUser', 
                                      passwordVariable: 'VIServerPassword') ]) {
                
     return powershell( returnStdout: true, script: '''
       Connect-VIServer -server server -User $env:VIServerUser -Password $env:VIServerPassword -Force
       Get-Template | select name'
     ''')
                        
  }
}

Note the use of environment variables instead of Groovy string interpolation for security reasons (see String interpolation).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, It solved my issue. Just the only thing that was missing is to put the code in a node block. node {}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.