DeployHubProject / DeployHub-Pro

DeployHub Pro Pipeline Status Project
https://www.openmakesoftware.com/application-release-automation-for-continuous-delivery/
Other
11 stars 4 forks source link

Jenkins credentials inside groovy pipeline script #272

Closed piyush94 closed 5 years ago

piyush94 commented 5 years ago

Way to use Jenkins credentials inside groovy pipeline script for deployhub library.

CC: @svisagan83

piyush94 commented 5 years ago

Reference: https://jenkins.io/doc/book/using/using-credentials/

sbtaylor15 commented 5 years ago

@piyush94

First add the fetch of credentials to the top of your pipeline as follows:

#!/usr/bin/env groovy

@Library('deployhub') _

withCredentials([usernamePassword(credentialsId: 'deployhub-creds', passwordVariable: 'pw', usernameVariable: 'user')]) 
{   
 def app="ChiliUptimeApp"
 def environment=""
 def cmd=""
 def url="http://192.168.3.118:8181"

 def dh = new deployhub();

 node {

Create the Jenkins Credentials id=deployhub-creds as plain userid/password.
Make sure the def user= and def pw= have been removed.

CC: @svisagan83

piyush94 commented 5 years ago

@sbtaylor15 Thanks, it's working.

CC: @svisagan83

piyush94 commented 5 years ago

@sbtaylor15 Will users be able to echo the password variable?

CC: @svisagan83

sbtaylor15 commented 5 years ago

@piyush94 - we moved the withCredentials into the DeployHub groovy. If the user value starts with @ then we treat it as a credential. Otherwise its used as regular user/password. Also, if user is "" then the default credential "deployhub-cred". This will hide the cred name as well from the end user.

Make sure to remove the withCredentials from your Jenkinsfile.

CC: @svisagan83

piyush94 commented 5 years ago

@sbtaylor15 The above fix was not working: image image

I replaced it with below:

 if (userid.indexOf('@') == 0)
   {
    def cred = userid.substring(1);
      def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
  com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class, Jenkins.instance, null, null ).find{
    it.id == cred};
    def username = creds.username;
    def password = creds.password;
     URL url = new URL(requestUrl);
     HttpURLConnection connection = url.openConnection();

     connection.setRequestMethod(verb);
     connection.setRequestProperty("Content-Type", "application/json");
     connection.setRequestProperty("Cookie", "p1=$username; p2=$password");

It started working.

CC: @svisagan83

sbtaylor15 commented 5 years ago

Hi @piyush94, thanks for digging up at alternative way of getting the credentials. Did we hide it well enough from the end user?

CC: @svisagan83

piyush94 commented 5 years ago

@sbtaylor15 Yes, i think it's good enough for now. Thanks.

CC: @svisagan83