Jenkins and PowerShell: Passing Credentials into PowerShell Scripts

With Jenkins, you can use the PowerShell Plugin to have jobs executing PowerShell scripts. You can also use the Credentials Binding Plugin to pass in usernames/passwords, that are stored on Jenkins in an encrypted credential store, to your scripts!

I wanted to make this short post to show how easy it is to take advantage of credentials that can be used by multiple jobs, and only have to change them in the credential store (as opposed to changing their value in every single job).

When the proper plugins are installed on Jenkins, new jobs should have the ability to pass bound credentials into your scripts (be it PowerShell, bash, etc.) as environmental variables. Your jobs will have a Use secret text(s) or file(s) checkbox that, when checked, provides the ability to select the types of bindings you are using. In my case in the screenshot below, I pass the Username and Password (separated) credential option, as to provide two separate environmental variables into the script:

PassingCredentialsInJenkins2Now your scripts can have credential objects passed to them, if they have -Credential parameters that can take the appropriate object types. You would create credential objects as so:

$SrvPassword = ConvertTo-SecureString "$($ENV:SrvPassword)" -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ("$ENV:SrvUser", $SrvPassword)
Invoke-Command -ComputerName node1 -Credential $Credential -ScriptBlock {Get-Process}

With that, you should be able to start utilizing credentials in your jobs that need to pass them into scripts. Special thanks to Ken, from DevOpsLibrary, for helping me out on this!

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s