github.com/codefresh-io/kcfi@v0.0.0-20230301195427-c1578715cc46/pkg/action/codefresh.go (about)

     1  /*
     2  Copyright The Codefresh Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package action
    18  
    19  import (
    20  	"bufio"
    21  	"fmt"
    22  	"io/ioutil"
    23  	"os"
    24  	"path"
    25  	"path/filepath"
    26  	"strings"
    27  
    28  	"github.com/pkg/errors"
    29  	"github.com/stretchr/objx"
    30  
    31  	//helm "helm.sh/helm/v3/pkg/action"
    32  	//"helm.sh/helm/v3/pkg/storage/driver"
    33  	kerrors "k8s.io/apimachinery/pkg/api/errors"
    34  
    35  	c "github.com/codefresh-io/kcfi/pkg/config"
    36  	"k8s.io/cli-runtime/pkg/resource"
    37  )
    38  
    39  // GetDockerRegistryVars - calculater docker registry vals
    40  func (o *CfApply) GetDockerRegistryVars() (map[string]interface{}, error) {
    41  
    42  	var registryAddress, registryUsername, registryPassword string
    43  	var err error
    44  	valsX := objx.New(o.vals)
    45  	usePrivateRegistry := valsX.Get(c.KeyImagesUsePrivateRegistry).Bool(false)
    46  	if !usePrivateRegistry {
    47  		// using Codefresh Enterprise registry
    48  		registryAddress = c.CfRegistryAddress
    49  		registryUsername = c.CfRegistryUsername
    50  		cfRegistrySaVal := valsX.Get(c.KeyImagesCodefreshRegistrySa).Str("sa.json")
    51  		cfRegistrySaPath := o.filePath(cfRegistrySaVal)
    52  		registryPasswordB, err := ioutil.ReadFile(cfRegistrySaPath)
    53  		if err != nil {
    54  			return nil, errors.Wrap(err, fmt.Sprintf("cannot read %s", cfRegistrySaPath))
    55  		}
    56  		registryPassword = string(registryPasswordB)
    57  	} else {
    58  		registryAddress = valsX.Get(c.KeyImagesPrivateRegistryAddress).String()
    59  		registryUsername = valsX.Get(c.KeyImagesPrivateRegistryUsername).String()
    60  		registryPassword = valsX.Get(c.KeyImagesPrivateRegistryPassword).String()
    61  		if len(registryAddress) == 0 || len(registryUsername) == 0 || len(registryPassword) == 0 {
    62  			err = fmt.Errorf("missing private registry data: ")
    63  			if len(registryAddress) == 0 {
    64  				err = errors.Wrapf(err, "missing %s", c.KeyImagesPrivateRegistryAddress)
    65  			}
    66  			if len(registryUsername) == 0 {
    67  				err = errors.Wrapf(err, "missing %s", c.KeyImagesPrivateRegistryUsername)
    68  			}
    69  			if len(registryPassword) == 0 {
    70  				err = errors.Wrapf(err, "missing %s", c.KeyImagesPrivateRegistryPassword)
    71  			}
    72  			return nil, err
    73  		}
    74  	}
    75  	// Creating
    76  	registryTplData := map[string]interface{}{
    77  		"RegistryAddress":  registryAddress,
    78  		"RegistryUsername": registryUsername,
    79  		"RegistryPassword": registryPassword,
    80  	}
    81  	registryValues, err := ExecuteTemplateToValues(RegistryValuesTpl, registryTplData)
    82  	if err != nil {
    83  		return nil, errors.Wrap(err, fmt.Sprintf("Error to parse docker registry values"))
    84  	}
    85  
    86  	return registryValues, nil
    87  }
    88  
    89  func (o *CfApply) applyDbInfra() error {
    90  	valsX := objx.New(o.vals)
    91  	if !valsX.Get(c.KeyDbInfraEnabled).Bool(false) {
    92  		debug("%s is not enabled", c.KeyDbInfraEnabled)
    93  		return nil
    94  	}
    95  	info("%s is enabled", c.KeyDbInfraEnabled)
    96  
    97  	dbInfraConfigFile := o.filePath(c.DbInfraConfigFile)
    98  	dbInfraConfig, err := ReadYamlFile(dbInfraConfigFile)
    99  	if err != nil {
   100  		return errors.Wrapf(err, "failed to parse db-infra config file %s", c.DbInfraConfigFile)
   101  	}
   102  	dbInfraConfig[c.KeyBaseDir] = filepath.Dir(dbInfraConfigFile)
   103  
   104  	dbInfraConfig = MergeMaps(dbInfraConfig, valsX.Get(c.KeyDbInfra).MSI(map[string]interface{}{}))
   105  	dbInfraConfigX := objx.New(dbInfraConfig)
   106  	dbInfraReleaseName := dbInfraConfigX.Get(c.KeyHelmRelease).String()
   107  
   108  	// Checking if dbInfra is already installed
   109  	dbInfraInstalled := IsHelmReleaseInstalled(dbInfraReleaseName, o.cfg)
   110  	codefreshInstalled := IsHelmReleaseInstalled(c.CodefreshReleaseName, o.cfg)
   111  
   112  	if codefreshInstalled && !dbInfraInstalled {
   113  		return fmt.Errorf("db-infra release %s is not installed", dbInfraReleaseName)
   114  	}
   115  
   116  	// Merging values/db-infra into main values
   117  	mainConfigChange, err := ReadYamlFile(o.filePath(c.DbInfraMainConfigChangeValuesFile))
   118  	if err != nil {
   119  		return errors.Wrapf(err, "failed to parse db-infra values file %s", c.DbInfraMainConfigChangeValuesFile)
   120  	}
   121  	debug("merging db-infra config change file %s", c.DbInfraMainConfigChangeValuesFile)
   122  	o.vals = MergeMaps(o.vals, mainConfigChange)
   123  
   124  	dbInfraUpgrade := valsX.Get(c.KeyDbInfraUpgrade).Bool(false)
   125  	debug("dbInfraUpgrade = %t", dbInfraUpgrade)
   126  	if (!codefreshInstalled && !dbInfraInstalled) || dbInfraUpgrade {
   127  		info("Installing db-infra release")
   128  		helmAtomicSave := o.Helm.Atomic
   129  		helmWaitSave := o.Helm.Wait
   130  		o.Helm.Atomic = true
   131  		o.Helm.Wait = true
   132  		defer func() {
   133  			o.Helm.Atomic = helmAtomicSave
   134  			o.Helm.Wait = helmWaitSave
   135  		}()
   136  		dbInfraRelease, err := DeployHelmRelease(
   137  			dbInfraReleaseName,
   138  			c.DbInfraHelmChartName,
   139  			dbInfraConfig,
   140  			o.cfg,
   141  			o.Helm,
   142  		)
   143  		if err != nil {
   144  			return errors.Wrapf(err, "Failed to deploy db-infra chart")
   145  		}
   146  		PrintHelmReleaseInfo(dbInfraRelease, c.Debug)
   147  	}
   148  
   149  	return nil
   150  }
   151  
   152  // ValidateCodefresh validates Codefresh config values
   153  func (o *CfApply) ValidateCodefresh() error {
   154  	valsX := objx.New(o.vals)
   155  
   156  	// 1. Validate appUrl
   157  	appUrl := valsX.Get(c.KeyAppUrl).String()
   158  	if appUrl == "" {
   159  		return fmt.Errorf("Missing %s", c.KeyAppUrl)
   160  	}
   161  	return nil
   162  }
   163  
   164  // WarnIfNotSet - display warning if not set
   165  func (o *CfApply) WarnIfNotSet() error {
   166  	valsX := objx.New(o.vals)
   167  
   168  	if valsX.Get(c.KeyDbInfraEnabled).Bool(false) {
   169  		debug("%s is enabled - do not warn on db passwords", c.KeyDbInfraEnabled)
   170  		return nil
   171  	}
   172  	fieldsWarnIfNotSet := make(map[string]string)
   173  	for f, warnMsg := range c.CodefreshValuesFieldsWarnIfNotSet {
   174  		if valsX.Get(f).String() == "" {
   175  			fieldsWarnIfNotSet[f] = warnMsg
   176  		}
   177  	}
   178  	if len(fieldsWarnIfNotSet) > 0 {
   179  		info("WARNING:")
   180  		for f, warnMsg := range fieldsWarnIfNotSet {
   181  			info("    %s is not set: %s", f, warnMsg)
   182  		}
   183  		info("\nsee https://github.com/codefresh-io/kcfi/blob/master/docs/warnings.md for more details")
   184  		if os.Getenv("CI") != "true" && !IsHelmReleaseInstalled(c.CodefreshReleaseName, o.cfg) {
   185  			reader := bufio.NewReader(os.Stdin)
   186  			fmt.Print("Do you want to continue [Y/n]? ")
   187  			warningAnswer, _ := reader.ReadString('\n')
   188  			warningAnswer = strings.Replace(warningAnswer, "\n", "", -1)
   189  			if strings.ToLower(warningAnswer) != "y" {
   190  				return fmt.Errorf("too many warnings")
   191  			}
   192  		}
   193  	}
   194  
   195  	return nil
   196  }
   197  
   198  // setDbPasswords - adjust passwords from global for local DB pods
   199  func (o *CfApply) setDbPasswords() error {
   200  	valsX := objx.New(o.vals)
   201  
   202  	if localPostrgresEnabled := valsX.Get(c.KeyLocalPostgresEnabled).Bool(true); localPostrgresEnabled {
   203  		globalPostgresUser := valsX.Get(c.KeyGlobalPostgresUser).String()
   204  		globalPostgresPassword := valsX.Get(c.KeyGlobalPostgresPassword).String()
   205  		if globalPostgresUser != "" {
   206  			valsX.Set(c.KeyLocalPostgresUser, globalPostgresUser)
   207  			debug("setting %s", c.KeyLocalPostgresUser)
   208  		}
   209  		if globalPostgresPassword != "" {
   210  			valsX.Set(c.KeyLocalPostgresPassword, globalPostgresPassword)
   211  			debug("setting %s", c.KeyLocalPostgresPassword)
   212  		}
   213  	}
   214  
   215  	// redis
   216  	if localRedisEnabled := valsX.Get(c.KeyLocalRedisEnabled).Bool(true); localRedisEnabled {
   217  		globalRedisPassword := valsX.Get(c.KeyGlobalRedisPassword).String()
   218  		if globalRedisPassword != "" {
   219  			valsX.Set(c.KeyLocalRedisPassword, globalRedisPassword)
   220  			debug("setting %s", c.KeyLocalRedisPassword)
   221  
   222  			redisURL := valsX.Get(c.KeyGlobalRedisURL).String()
   223  			runtimeRedisHost := valsX.Get(c.KeyGlobalRuntimeRedisHost).String()
   224  			runtimeRedisPassword := valsX.Get(c.KeyGlobalRuntimeRedisPassword).String()
   225  
   226  			if runtimeRedisPassword == "" && redisURL == runtimeRedisHost {
   227  				valsX.Set(c.KeyGlobalRuntimeRedisPassword, globalRedisPassword)
   228  				debug("setting %s", c.KeyGlobalRuntimeRedisPassword)
   229  			}
   230  		}
   231  	}
   232  
   233  	//// rabbit
   234  	if localRabbitEnabled := valsX.Get(c.KeyLocalRabbitEnabled).Bool(true); localRabbitEnabled {
   235  		globalRabbitPassword := valsX.Get(c.KeyGlobalRabbitPassword).String()
   236  		if globalRabbitPassword != "" {
   237  			valsX.Set(c.KeyLocalRabbitPassword, globalRabbitPassword)
   238  			debug("setting %s", c.KeyLocalRabbitPassword)
   239  		}
   240  	}
   241  
   242  	//// mongo
   243  	if localMongoEnabled := valsX.Get(c.KeyLocalMongoEnabled).Bool(true); localMongoEnabled {
   244  		// Mongo Root User
   245  		globalMongoRootUser := valsX.Get(c.KeyGlobalMongoRootUser).String()
   246  		globalMongoRootPassword := valsX.Get(c.KeyGlobalMongoRootPassword).String()
   247  
   248  		if globalMongoRootUser != "" {
   249  			valsX.Set(c.KeyLocalMongoRootUser, globalMongoRootUser)
   250  			debug("setting %s", c.KeyLocalMongoRootUser)
   251  		}
   252  		if globalMongoRootPassword != "" {
   253  			valsX.Set(c.KeyLocalMongoRootPassword, globalMongoRootPassword)
   254  			debug("setting %s", c.KeyLocalMongoRootPassword)
   255  		}
   256  
   257  		// Mongo URI and app user password
   258  		globalMongoURI := valsX.Get(c.KeyGlobalMongoURI).String()
   259  		globalMongoUser := valsX.Get(c.KeyGlobalMongoUser).String()
   260  		globalMongoPassword := valsX.Get(c.KeyGlobalMongoPassword).String()
   261  		if globalMongoUser != "" && globalMongoPassword == "" {
   262  			return fmt.Errorf("Cannot set globalMongoUser without setting globalMongoPassword")
   263  		}
   264  
   265  		if globalMongoURI == "" && globalMongoPassword != "" {
   266  			if globalMongoUser == "" {
   267  				globalMongoUser = c.MongoDefaultAppUser
   268  			}
   269  			globalMongoURI = fmt.Sprintf("mongodb://%s:%s@mongodb:27017", globalMongoUser, globalMongoPassword)
   270  			valsX.Set(c.KeyGlobalMongoURI, globalMongoURI)
   271  			debug("setting %s = mongodb://%s:*****@mongodb:27017", c.KeyGlobalMongoURI, globalMongoUser)
   272  		}
   273  	}
   274  	return nil
   275  }
   276  
   277  // ApplyCodefresh -
   278  func (o *CfApply) ApplyCodefresh() error {
   279  
   280  	// Calculating addional configurations
   281  	valsX := objx.New(o.vals)
   282  
   283  	// find if it is upgrade (codefreshInstalled==true) or install
   284  	codefreshInstalled := IsHelmReleaseInstalled(c.CodefreshReleaseName, o.cfg)
   285  
   286  	// display and prompt on warnigs
   287  	if err := o.WarnIfNotSet(); err != nil {
   288  		return err
   289  	}
   290  
   291  	// Set non-default Db Passwords by values
   292  	if err := o.setDbPasswords(); err != nil {
   293  		return err
   294  	}
   295  
   296  	//--- Docker Registry secret
   297  	registryValues, err := o.GetDockerRegistryVars()
   298  	if err != nil {
   299  		return errors.Wrapf(err, "Failed to parse docker registry values")
   300  	}
   301  	usePrivateRegistry := valsX.Get(c.KeyImagesUsePrivateRegistry).Bool(false)
   302  	if usePrivateRegistry {
   303  		privateRegistryAddress := valsX.Get(c.KeyImagesPrivateRegistryAddress).String()
   304  		privateRegistryGlobalValues := map[string]interface{}{
   305  			"global": map[string]interface{}{
   306  				"privateRegistry": true,
   307  				"dockerRegistry":  privateRegistryAddress + "/",
   308  			},
   309  		}
   310  		o.vals = MergeMaps(o.vals, privateRegistryGlobalValues)
   311  		privateRegistryValues, err := ExecuteTemplateToValues(PrivateRegistryValuesTpl, o.vals)
   312  		if err != nil {
   313  			return errors.Wrapf(err, "Failed to generate values.yaml")
   314  		}
   315  		o.vals = MergeMaps(o.vals, privateRegistryValues)
   316  	}
   317  	o.vals = MergeMaps(o.vals, registryValues)
   318  
   319  	//--- WebTls Values
   320  	if !valsX.Get(c.KeyTlsSelfSigned).Bool(true) {
   321  		webTlsValues, err := ExecuteTemplateToValues(WebTlsValuesTpl, o.vals)
   322  		if err != nil {
   323  			return errors.Wrapf(err, "Failed to generate values.yaml")
   324  		}
   325  		o.vals = MergeMaps(o.vals, webTlsValues)
   326  	}
   327  
   328  	//--- MongoTls Values
   329  	//add mongoCaCert and mongoCaKey into values.yaml and codefresh-resource.yaml if mongoTLS: true, skip otherwise
   330  	if valsX.Get(c.KeyGlobalMongoTLS).Bool(false) {
   331  		mongoTlsValues, err := ExecuteTemplateToValues(MongoTlsValuesTpl, o.vals)
   332  		if err != nil {
   333  			return errors.Wrapf(err, "Failed to generate values.yaml")
   334  		}
   335  		o.vals = MergeMaps(o.vals, mongoTlsValues)
   336  	}
   337  
   338  	// Db Infra
   339  	err = o.applyDbInfra()
   340  	if err != nil {
   341  		return errors.Wrapf(err, "Failed apply db-infra")
   342  	}
   343  
   344  	//--- If a release does not exist add seeded jobs
   345  	if !codefreshInstalled {
   346  		seedJobsValues := map[string]interface{}{
   347  			"global": map[string]interface{}{
   348  				"seedJobs":  true,
   349  				"certsJobs": true,
   350  			},
   351  		}
   352  		o.vals = MergeMaps(o.vals, seedJobsValues)
   353  	}
   354  
   355  	// Validating Configurations
   356  	if err = o.ValidateCodefresh(); err != nil {
   357  		return errors.Wrapf(err, "Configuration is not valid")
   358  	}
   359  
   360  	// Rendering values.yaml and codefresh-resource.yaml
   361  	valuesTplResult, err := ExecuteTemplate(ValuesTpl, o.vals)
   362  	if err != nil {
   363  		return errors.Wrapf(err, "Failed to generate values.yaml")
   364  	}
   365  
   366  	valuesYamlPath := path.Join(GetAssetsDir(o.ConfigFile), "values.yaml")
   367  	err = ioutil.WriteFile(valuesYamlPath, []byte(valuesTplResult), 0644)
   368  	if err != nil {
   369  		return errors.Wrapf(err, "Failed to write %s ", valuesYamlPath)
   370  	}
   371  	info("values.yaml has been generated in %s\n", valuesYamlPath)
   372  
   373  	cfResourceTplResult, err := ExecuteTemplate(CfResourceTpl, o.vals)
   374  	if err != nil {
   375  		return errors.Wrapf(err, "Failed to generate codefresh-resource.yaml")
   376  	}
   377  	cfResourceYamlPath := path.Join(GetAssetsDir(o.ConfigFile), "codefresh-resource.yaml")
   378  	err = ioutil.WriteFile(cfResourceYamlPath, []byte(cfResourceTplResult), 0644)
   379  	if err != nil {
   380  		return errors.Wrapf(err, "Failed to write %s ", cfResourceYamlPath)
   381  	}
   382  	info("codefresh-resource.yaml is generated in %s\n", cfResourceYamlPath)
   383  
   384  	//--- Deploying
   385  	installerType := valsX.Get(c.KeyInstallerType).String()
   386  	if installerType == installerTypeOperator {
   387  		// Deploy Codefresh Operator with wait first
   388  		operatorChartValues := valsX.Get(c.KeyOperatorChartValues).MSI(map[string]interface{}{})
   389  		operatorChartValues = MergeMaps(operatorChartValues, registryValues)
   390  		if usePrivateRegistry {
   391  			operatorChartValues = MergeMaps(operatorChartValues, map[string]interface{}{
   392  				c.KeyDockerRegistry: valsX.Get(c.KeyImagesPrivateRegistryAddress).String(),
   393  			})
   394  		}
   395  		if valsX.Get(c.KeyOperatorSkipCRD).Bool(false) {
   396  			o.Helm.SkipCRDs = true
   397  		}
   398  		o.Helm.Atomic = true
   399  		o.Helm.Wait = true
   400  		operatorRelease, err := DeployHelmRelease(
   401  			operatorHelmReleaseName,
   402  			operatorHelmChartName,
   403  			operatorChartValues,
   404  			o.cfg,
   405  			o.Helm,
   406  		)
   407  		if err != nil {
   408  			return errors.Wrapf(err, "Failed to deploy operator chart")
   409  		}
   410  		PrintHelmReleaseInfo(operatorRelease, c.Debug)
   411  
   412  		// Update Codefresh resource
   413  		cfResourceYamlReader, err := os.Open(cfResourceYamlPath)
   414  		if err != nil {
   415  			return errors.Wrapf(err, "Failed to read %s ", cfResourceYamlPath)
   416  		}
   417  		cfResources, err := o.cfg.KubeClient.Build(cfResourceYamlReader, true)
   418  		if err != nil {
   419  			return errors.Wrapf(err, "Failed to write %s ", cfResourceYamlPath)
   420  		}
   421  		info("applying %s\n %v", cfResourceYamlPath, cfResources)
   422  		if o.Helm.DryRun {
   423  			info("\n\nDryRun Mode - Codefresh Resource Definition is generatest in %s", cfResourceYamlPath)
   424  			return nil
   425  		}
   426  		err = cfResources.Visit(func(info *resource.Info, err error) error {
   427  			if err != nil {
   428  				return err
   429  			}
   430  			helper := resource.NewHelper(info.Client, info.Mapping)
   431  			if _, err = helper.Get(info.Namespace, info.Name); err != nil {
   432  				if !kerrors.IsNotFound(err) {
   433  					return errors.Wrapf(err, fmt.Sprintf("retrieving current configuration of:\n%s\nfrom server for:", info.String()))
   434  				}
   435  				_, err = helper.Create(info.Namespace, true, info.Object)
   436  			} else {
   437  				_, err = helper.Replace(info.Namespace, info.Name, true, info.Object)
   438  			}
   439  			return err
   440  		})
   441  		if err != nil {
   442  			return errors.Wrapf(err, "Failed to apply %s\n", cfResourceYamlPath)
   443  		}
   444  	} else if installerType == installerTypeHelm {
   445  		// first we will error if operator chart is installed:
   446  		if operatorReleaseInstalled := IsHelmReleaseInstalled(operatorHelmReleaseName, o.cfg); operatorReleaseInstalled {
   447  			return fmt.Errorf("Error: Codefresh operator release is running. It is incomplatible with helm install type")
   448  		}
   449  		codefreshHelChartName := valsX.Get(c.KeyHelmChart).Str("codefresh")
   450  		codefreshRelease, err := DeployHelmRelease(
   451  			codefreshHelmReleaseName,
   452  			codefreshHelChartName,
   453  			o.vals,
   454  			o.cfg,
   455  			o.Helm,
   456  		)
   457  		if err != nil {
   458  			return errors.Wrapf(err, "Failed to deploy operator chart")
   459  		}
   460  		PrintHelmReleaseInfo(codefreshRelease, false)
   461  	} else {
   462  		return fmt.Errorf("Error: unknown instraller type %s", installerType)
   463  	}
   464  
   465  	info("\nCodefresh has been deployed to namespace %s\n", o.Helm.Namespace)
   466  	return nil
   467  }
   468  
   469  func (o *CfApply) ApplyBackupMgr() error {
   470  	valsX := objx.New(o.vals)
   471  
   472  	mongoURI := valsX.Get(c.KeyBkpManagerMongoURI).Str()
   473  	if mongoURI == "" {
   474  		info("Mongo URI is not specified, trying to get it automatically from the installed Codefresh release")
   475  		var err error
   476  		mongoURI, err = o.getMongoURIFromRelease()
   477  		if err != nil {
   478  			return err
   479  		}
   480  	}
   481  
   482  	debug("Mongo URI is: %s", mongoURI)
   483  	valsX.Set(c.KeyBkpManagerMongoURI, mongoURI)
   484  
   485  	installerType := valsX.Get(c.KeyInstallerType).String()
   486  	if installerType == installerTypeHelm {
   487  		helmChartName := valsX.Get(c.KeyHelmChart).String()
   488  		helmReleaseName := valsX.Get(c.KeyHelmRelease).Str(kindBackupManager)
   489  		rel, err := DeployHelmRelease(
   490  			helmReleaseName,
   491  			helmChartName,
   492  			valsX,
   493  			o.cfg,
   494  			o.Helm,
   495  		)
   496  		if err != nil {
   497  			return errors.Wrapf(err, "Failed to deploy %s chart", helmChartName)
   498  		}
   499  		PrintHelmReleaseInfo(rel, c.Debug)
   500  		info("\n%s has been deployed to namespace %s\n", helmReleaseName, o.Helm.Namespace)
   501  		return nil
   502  	}
   503  	return fmt.Errorf("Wrong installer type %s", installerType)
   504  }
   505  
   506  func (o *CfApply) getMongoURIFromRelease() (string, error) {
   507  
   508  	cfRelVals, err := GetReleaseValues(codefreshHelmReleaseName, o.cfg)
   509  	if err != nil {
   510  		return "", err
   511  	}
   512  
   513  	cfRelValsX := objx.New(cfRelVals)
   514  
   515  	mongoURI := cfRelValsX.Get(c.KeyGlobalMongoURI).Str()
   516  	mongoRootUser := cfRelValsX.Get(c.KeyGlobalMongoRootUser).Str()
   517  	mongoRootPassword := cfRelValsX.Get(c.KeyGlobalMongoRootPassword).Str()
   518  
   519  	if !strings.Contains(mongoURI, "@") || mongoRootUser == "" || mongoRootPassword == "" {
   520  		return "", fmt.Errorf("Failed to get the mongo URI value from an existing release")
   521  	}
   522  
   523  	rootMongoURI := "mongodb://" + mongoRootUser + ":" + mongoRootPassword + "@" + strings.Split(mongoURI, "@")[1]
   524  	return rootMongoURI, nil
   525  }
   526  
   527  // ValuesTpl is a template to format final helm values
   528  var ValuesTpl = `
   529  {{ . | toYaml }}
   530  
   531  `
   532  
   533  //CfResourceTpl template to final Codefresh custom resource
   534  var CfResourceTpl = `
   535  apiVersion: codefresh.io/v1alpha1
   536  kind: Codefresh
   537  metadata:
   538    name: cf
   539    namespace: {{ .kubernetes.namespace }}
   540  spec:
   541  {{ . | toYaml | indent 2 }}
   542  `
   543  
   544  // RegistryValuesTpl template
   545  var RegistryValuesTpl = `
   546  {{ $auth := ((printf "%s:%s" .RegistryUsername .RegistryPassword ) | b64enc) }}
   547  dockerconfigjson:
   548    auths:
   549      {{.RegistryAddress | toString }}:
   550        auth: {{ $auth }}
   551  global:
   552    {{- if .docker.usePrivateRegistry }}
   553    privateRegistry: true
   554    dockerRegistry: {{ printf "%s/" .RegistryAddress }}
   555    {{- end }}
   556    dockerconfigjson:
   557      auths:
   558        {{.RegistryAddress | toString }}:
   559          auth: {{ $auth }}
   560  cfui:
   561    dockerconfigjson:
   562      auths:
   563        {{.RegistryAddress | toString }}:
   564          auth: {{ $auth }}
   565  runtime-environment-manager:
   566    dockerconfigjson:
   567      auths:
   568        {{.RegistryAddress | toString }}:
   569          auth: {{ $auth }}
   570  `
   571  
   572  // WebTlsValuesTpl template
   573  var WebTlsValuesTpl = `
   574  ingress:
   575    webTlsSecretName: "star.codefresh.io"
   576  nomios:
   577    ingress:
   578      webTlsSecretName: "star.codefresh.io"
   579  webTLS:
   580    secretName: star.codefresh.io
   581    key: |
   582  {{ getFileWithBaseDir .tls.key .BaseDir | indent 4}}
   583    cert: |
   584  {{ getFileWithBaseDir .tls.cert .BaseDir | indent 4}}
   585  
   586  cfui:
   587    webTLS:
   588      key: |
   589  {{ getFileWithBaseDir .tls.key .BaseDir | indent 6}}
   590      cert: |
   591  {{ getFileWithBaseDir .tls.cert .BaseDir | indent 6}}
   592  `
   593  
   594  // MongoTlsValuesTpl template
   595  var MongoTlsValuesTpl = `
   596  mongoTLS:
   597    CaCert: |
   598  {{ getFileWithBaseDir .global.mongoCaCert .BaseDir | indent 4}}
   599    CaKey: |
   600  {{ getFileWithBaseDir .global.mongoCaKey .BaseDir | indent 4}}
   601  `
   602  
   603  //PrivateRegistryValuesTpl template
   604  var PrivateRegistryValuesTpl = `
   605  {{- if .global.privateRegistry }}
   606  rabbitmq:
   607    image:
   608      registry: {{ .global.dockerRegistry | toString | trimSuffix "/" }}
   609  redis:
   610    image:
   611      registry: {{ .global.dockerRegistry | toString | trimSuffix "/" }}
   612  ingress-nginx:
   613    controller:
   614      image:
   615        registry: {{ .global.dockerRegistry | toString | trimSuffix "/" }}
   616  {{- end }}
   617  `