github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/cloudfoundry/Services.go (about) 1 package cloudfoundry 2 3 import ( 4 "bytes" 5 "fmt" 6 "strings" 7 8 "github.com/SAP/jenkins-library/pkg/command" 9 "github.com/SAP/jenkins-library/pkg/log" 10 ) 11 12 // ReadServiceKey reads a cloud foundry service key based on provided service instance and service key name parameters 13 func (cf *CFUtils) ReadServiceKey(options ServiceKeyOptions) (string, error) { 14 15 _c := cf.Exec 16 17 if _c == nil { 18 _c = &command.Command{} 19 } 20 cfconfig := LoginOptions{ 21 CfAPIEndpoint: options.CfAPIEndpoint, 22 CfOrg: options.CfOrg, 23 CfSpace: options.CfSpace, 24 Username: options.Username, 25 Password: options.Password, 26 } 27 err := cf.Login(cfconfig) 28 29 if err != nil { 30 // error while trying to run cf login 31 return "", fmt.Errorf("Login to Cloud Foundry failed: %w", err) 32 } 33 var serviceKeyBytes bytes.Buffer 34 _c.Stdout(&serviceKeyBytes) 35 36 // we are logged in --> read service key 37 log.Entry().WithField("cfServiceInstance", options.CfServiceInstance).WithField("cfServiceKey", options.CfServiceKeyName).Info("Read service key for service instance") 38 cfReadServiceKeyScript := []string{"service-key", options.CfServiceInstance, options.CfServiceKeyName} 39 err = _c.RunExecutable("cf", cfReadServiceKeyScript...) 40 41 if err != nil { 42 // error while reading service key 43 log.SetErrorCategory(log.ErrorConfiguration) 44 return "", fmt.Errorf("Reading service key failed: %w", err) 45 } 46 47 // parse and return service key 48 var serviceKeyJSON string 49 if len(serviceKeyBytes.String()) > 0 { 50 var lines []string = strings.Split(serviceKeyBytes.String(), "\n") 51 serviceKeyJSON = strings.Join(lines[2:], "") 52 } 53 54 err = cf.Logout() 55 if err != nil { 56 return serviceKeyJSON, fmt.Errorf("Logout of Cloud Foundry failed: %w", err) 57 } 58 59 return serviceKeyJSON, err 60 } 61 62 // ServiceKeyOptions for reading CF Service Key 63 type ServiceKeyOptions struct { 64 CfAPIEndpoint string 65 CfOrg string 66 CfSpace string 67 CfServiceInstance string 68 CfServiceKeyName string 69 Username string 70 Password string 71 }