github.com/xgoffin/jenkins-library@v1.154.0/cmd/helmExecute_generated.go (about)

     1  // Code generated by piper's step-generator. DO NOT EDIT.
     2  
     3  package cmd
     4  
     5  import (
     6  	"fmt"
     7  	"os"
     8  	"time"
     9  
    10  	"github.com/SAP/jenkins-library/pkg/config"
    11  	"github.com/SAP/jenkins-library/pkg/log"
    12  	"github.com/SAP/jenkins-library/pkg/splunk"
    13  	"github.com/SAP/jenkins-library/pkg/telemetry"
    14  	"github.com/SAP/jenkins-library/pkg/validation"
    15  	"github.com/spf13/cobra"
    16  )
    17  
    18  type helmExecuteOptions struct {
    19  	AdditionalParameters      []string `json:"additionalParameters,omitempty"`
    20  	ChartPath                 string   `json:"chartPath,omitempty"`
    21  	TargetRepositoryURL       string   `json:"targetRepositoryURL,omitempty"`
    22  	TargetRepositoryName      string   `json:"targetRepositoryName,omitempty" validate:"required_if=HelmCommand install"`
    23  	TargetRepositoryUser      string   `json:"targetRepositoryUser,omitempty"`
    24  	TargetRepositoryPassword  string   `json:"targetRepositoryPassword,omitempty"`
    25  	HelmDeployWaitSeconds     int      `json:"helmDeployWaitSeconds,omitempty"`
    26  	HelmValues                []string `json:"helmValues,omitempty"`
    27  	Image                     string   `json:"image,omitempty"`
    28  	KeepFailedDeployments     bool     `json:"keepFailedDeployments,omitempty"`
    29  	KubeConfig                string   `json:"kubeConfig,omitempty"`
    30  	KubeContext               string   `json:"kubeContext,omitempty"`
    31  	Namespace                 string   `json:"namespace,omitempty"`
    32  	DockerConfigJSON          string   `json:"dockerConfigJSON,omitempty"`
    33  	HelmCommand               string   `json:"helmCommand,omitempty" validate:"possible-values=upgrade install lint test uninstall package publish"`
    34  	AppVersion                string   `json:"appVersion,omitempty"`
    35  	DependencyUpdate          bool     `json:"dependencyUpdate,omitempty"`
    36  	DumpLogs                  bool     `json:"dumpLogs,omitempty"`
    37  	FilterTest                string   `json:"filterTest,omitempty"`
    38  	CustomTLSCertificateLinks []string `json:"customTlsCertificateLinks,omitempty"`
    39  	Publish                   bool     `json:"publish,omitempty"`
    40  }
    41  
    42  // HelmExecuteCommand Executes helm3 functionality as the package manager for Kubernetes.
    43  func HelmExecuteCommand() *cobra.Command {
    44  	const STEP_NAME = "helmExecute"
    45  
    46  	metadata := helmExecuteMetadata()
    47  	var stepConfig helmExecuteOptions
    48  	var startTime time.Time
    49  	var logCollector *log.CollectorHook
    50  	var splunkClient *splunk.Splunk
    51  	telemetryClient := &telemetry.Telemetry{}
    52  
    53  	var createHelmExecuteCmd = &cobra.Command{
    54  		Use:   STEP_NAME,
    55  		Short: "Executes helm3 functionality as the package manager for Kubernetes.",
    56  		Long: `Alpha version: please expect incompatible changes
    57  
    58  Executes helm functionality as the package manager for Kubernetes.
    59  
    60  * [Helm](https://helm.sh/)  is the package manager for Kubernetes.
    61  * [Helm documentation https://helm.sh/docs/intro/using_helm/ and best practies https://helm.sh/docs/chart_best_practices/conventions/]
    62  * [Helm Charts] (https://artifacthub.io/)
    63  ` + "`" + `` + "`" + `` + "`" + `
    64  Available Commands:
    65    install     install a chart
    66    lint        examine a chart for possible issues
    67    package     package a chart directory into a chart archive
    68    repo        add, list, remove, update, and index chart repositories
    69    test        run tests for a release
    70    uninstall   uninstall a release
    71    upgrade     upgrade a release
    72    verify      verify that a chart at the given path has been signed and is valid
    73    push        upload a chart to a registry
    74  
    75  ` + "`" + `` + "`" + `` + "`" + `
    76  
    77  Note: piper supports only helm3 version, since helm2 is deprecated.`,
    78  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    79  			startTime = time.Now()
    80  			log.SetStepName(STEP_NAME)
    81  			log.SetVerbose(GeneralConfig.Verbose)
    82  
    83  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    84  
    85  			path, _ := os.Getwd()
    86  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    87  			log.RegisterHook(fatalHook)
    88  
    89  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    90  			if err != nil {
    91  				log.SetErrorCategory(log.ErrorConfiguration)
    92  				return err
    93  			}
    94  			log.RegisterSecret(stepConfig.TargetRepositoryUser)
    95  			log.RegisterSecret(stepConfig.TargetRepositoryPassword)
    96  			log.RegisterSecret(stepConfig.KubeConfig)
    97  			log.RegisterSecret(stepConfig.DockerConfigJSON)
    98  
    99  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
   100  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
   101  				log.RegisterHook(&sentryHook)
   102  			}
   103  
   104  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   105  				splunkClient = &splunk.Splunk{}
   106  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
   107  				log.RegisterHook(logCollector)
   108  			}
   109  
   110  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
   111  			if err != nil {
   112  				return err
   113  			}
   114  			if err = validation.ValidateStruct(stepConfig); err != nil {
   115  				log.SetErrorCategory(log.ErrorConfiguration)
   116  				return err
   117  			}
   118  
   119  			return nil
   120  		},
   121  		Run: func(_ *cobra.Command, _ []string) {
   122  			stepTelemetryData := telemetry.CustomData{}
   123  			stepTelemetryData.ErrorCode = "1"
   124  			handler := func() {
   125  				config.RemoveVaultSecretFiles()
   126  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   127  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   128  				stepTelemetryData.PiperCommitHash = GitCommit
   129  				telemetryClient.SetData(&stepTelemetryData)
   130  				telemetryClient.Send()
   131  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   132  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   133  				}
   134  			}
   135  			log.DeferExitHandler(handler)
   136  			defer handler()
   137  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   138  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   139  				splunkClient.Initialize(GeneralConfig.CorrelationID,
   140  					GeneralConfig.HookConfig.SplunkConfig.Dsn,
   141  					GeneralConfig.HookConfig.SplunkConfig.Token,
   142  					GeneralConfig.HookConfig.SplunkConfig.Index,
   143  					GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   144  			}
   145  			helmExecute(stepConfig, &stepTelemetryData)
   146  			stepTelemetryData.ErrorCode = "0"
   147  			log.Entry().Info("SUCCESS")
   148  		},
   149  	}
   150  
   151  	addHelmExecuteFlags(createHelmExecuteCmd, &stepConfig)
   152  	return createHelmExecuteCmd
   153  }
   154  
   155  func addHelmExecuteFlags(cmd *cobra.Command, stepConfig *helmExecuteOptions) {
   156  	cmd.Flags().StringSliceVar(&stepConfig.AdditionalParameters, "additionalParameters", []string{}, "Defines additional parameters for Helm like  \"helm install [NAME] [CHART] [flags]\".")
   157  	cmd.Flags().StringVar(&stepConfig.ChartPath, "chartPath", os.Getenv("PIPER_chartPath"), "Defines the chart path for helm.")
   158  	cmd.Flags().StringVar(&stepConfig.TargetRepositoryURL, "targetRepositoryURL", os.Getenv("PIPER_targetRepositoryURL"), "URL of the target repository where the compiled helm .tgz archive shall be uploaded - typically provided by the CI/CD environment.")
   159  	cmd.Flags().StringVar(&stepConfig.TargetRepositoryName, "targetRepositoryName", os.Getenv("PIPER_targetRepositoryName"), "set the chart repository")
   160  	cmd.Flags().StringVar(&stepConfig.TargetRepositoryUser, "targetRepositoryUser", os.Getenv("PIPER_targetRepositoryUser"), "Username for the char repository where the compiled helm .tgz archive shall be uploaded - typically provided by the CI/CD environment.")
   161  	cmd.Flags().StringVar(&stepConfig.TargetRepositoryPassword, "targetRepositoryPassword", os.Getenv("PIPER_targetRepositoryPassword"), "Password for the target repository where the compiled helm .tgz archive shall be uploaded - typically provided by the CI/CD environment.")
   162  	cmd.Flags().IntVar(&stepConfig.HelmDeployWaitSeconds, "helmDeployWaitSeconds", 300, "Number of seconds before helm deploy returns.")
   163  	cmd.Flags().StringSliceVar(&stepConfig.HelmValues, "helmValues", []string{}, "List of helm values as YAML file reference or URL (as per helm parameter description for `-f` / `--values`)")
   164  	cmd.Flags().StringVar(&stepConfig.Image, "image", os.Getenv("PIPER_image"), "Full name of the image to be deployed.")
   165  	cmd.Flags().BoolVar(&stepConfig.KeepFailedDeployments, "keepFailedDeployments", false, "Defines whether a failed deployment will be purged")
   166  	cmd.Flags().StringVar(&stepConfig.KubeConfig, "kubeConfig", os.Getenv("PIPER_kubeConfig"), "Defines the path to the \"kubeconfig\" file.")
   167  	cmd.Flags().StringVar(&stepConfig.KubeContext, "kubeContext", os.Getenv("PIPER_kubeContext"), "Defines the context to use from the \"kubeconfig\" file.")
   168  	cmd.Flags().StringVar(&stepConfig.Namespace, "namespace", `default`, "Defines the target Kubernetes namespace for the deployment.")
   169  	cmd.Flags().StringVar(&stepConfig.DockerConfigJSON, "dockerConfigJSON", os.Getenv("PIPER_dockerConfigJSON"), "Path to the file `.docker/config.json` - this is typically provided by your CI/CD system. You can find more details about the Docker credentials in the [Docker documentation](https://docs.docker.com/engine/reference/commandline/login/).")
   170  	cmd.Flags().StringVar(&stepConfig.HelmCommand, "helmCommand", os.Getenv("PIPER_helmCommand"), "Helm: defines the command `install`, `lint`, `package`, `test`, `upgrade` and etc.")
   171  	cmd.Flags().StringVar(&stepConfig.AppVersion, "appVersion", os.Getenv("PIPER_appVersion"), "set the appVersion on the chart to this version")
   172  	cmd.Flags().BoolVar(&stepConfig.DependencyUpdate, "dependencyUpdate", false, "set the appVersion on the chart to this version")
   173  	cmd.Flags().BoolVar(&stepConfig.DumpLogs, "dumpLogs", false, "dump the logs from test pods (this runs after all tests are complete, but before any cleanup)")
   174  	cmd.Flags().StringVar(&stepConfig.FilterTest, "filterTest", os.Getenv("PIPER_filterTest"), "specify tests by attribute (currently `name`) using attribute=value syntax or `!attribute=value` to exclude a test (can specify multiple or separate values with commas `name=test1,name=test2`)")
   175  	cmd.Flags().StringSliceVar(&stepConfig.CustomTLSCertificateLinks, "customTlsCertificateLinks", []string{}, "List of download links to custom TLS certificates. This is required to ensure trusted connections to instances with repositories (like nexus) when publish flag is set to true.")
   176  	cmd.Flags().BoolVar(&stepConfig.Publish, "publish", false, "Configures helm to run the deploy command to publish artifacts to a repository.")
   177  
   178  	cmd.MarkFlagRequired("chartPath")
   179  	cmd.MarkFlagRequired("image")
   180  }
   181  
   182  // retrieve step metadata
   183  func helmExecuteMetadata() config.StepData {
   184  	var theMetaData = config.StepData{
   185  		Metadata: config.StepMetadata{
   186  			Name:        "helmExecute",
   187  			Aliases:     []config.Alias{},
   188  			Description: "Executes helm3 functionality as the package manager for Kubernetes.",
   189  		},
   190  		Spec: config.StepSpec{
   191  			Inputs: config.StepInputs{
   192  				Secrets: []config.StepSecrets{
   193  					{Name: "dockerCredentialsId", Type: "jenkins"},
   194  					{Name: "dockerConfigJsonCredentialsId", Description: "Jenkins 'Secret file' credentials ID containing Docker config.json (with registry credential(s)).", Type: "jenkins"},
   195  				},
   196  				Resources: []config.StepResources{
   197  					{Name: "deployDescriptor", Type: "stash"},
   198  				},
   199  				Parameters: []config.StepParameters{
   200  					{
   201  						Name:        "additionalParameters",
   202  						ResourceRef: []config.ResourceReference{},
   203  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   204  						Type:        "[]string",
   205  						Mandatory:   false,
   206  						Aliases:     []config.Alias{{Name: "helmDeploymentParameters"}},
   207  						Default:     []string{},
   208  					},
   209  					{
   210  						Name:        "chartPath",
   211  						ResourceRef: []config.ResourceReference{},
   212  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   213  						Type:        "string",
   214  						Mandatory:   true,
   215  						Aliases:     []config.Alias{{Name: "helmChartPath"}},
   216  						Default:     os.Getenv("PIPER_chartPath"),
   217  					},
   218  					{
   219  						Name: "targetRepositoryURL",
   220  						ResourceRef: []config.ResourceReference{
   221  							{
   222  								Name:  "commonPipelineEnvironment",
   223  								Param: "custom/helmRepositoryURL",
   224  							},
   225  
   226  							{
   227  								Name:  "commonPipelineEnvironment",
   228  								Param: "custom/repositoryUrl",
   229  							},
   230  						},
   231  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   232  						Type:      "string",
   233  						Mandatory: false,
   234  						Aliases:   []config.Alias{},
   235  						Default:   os.Getenv("PIPER_targetRepositoryURL"),
   236  					},
   237  					{
   238  						Name:        "targetRepositoryName",
   239  						ResourceRef: []config.ResourceReference{},
   240  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   241  						Type:        "string",
   242  						Mandatory:   false,
   243  						Aliases:     []config.Alias{},
   244  						Default:     os.Getenv("PIPER_targetRepositoryName"),
   245  					},
   246  					{
   247  						Name: "targetRepositoryUser",
   248  						ResourceRef: []config.ResourceReference{
   249  							{
   250  								Name:  "commonPipelineEnvironment",
   251  								Param: "custom/helmRepositoryUsername",
   252  							},
   253  
   254  							{
   255  								Name:  "commonPipelineEnvironment",
   256  								Param: "custom/repositoryUsername",
   257  							},
   258  						},
   259  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   260  						Type:      "string",
   261  						Mandatory: false,
   262  						Aliases:   []config.Alias{},
   263  						Default:   os.Getenv("PIPER_targetRepositoryUser"),
   264  					},
   265  					{
   266  						Name: "targetRepositoryPassword",
   267  						ResourceRef: []config.ResourceReference{
   268  							{
   269  								Name:  "commonPipelineEnvironment",
   270  								Param: "custom/helmRepositoryPassword",
   271  							},
   272  
   273  							{
   274  								Name:  "commonPipelineEnvironment",
   275  								Param: "custom/repositoryPassword",
   276  							},
   277  						},
   278  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   279  						Type:      "string",
   280  						Mandatory: false,
   281  						Aliases:   []config.Alias{},
   282  						Default:   os.Getenv("PIPER_targetRepositoryPassword"),
   283  					},
   284  					{
   285  						Name:        "helmDeployWaitSeconds",
   286  						ResourceRef: []config.ResourceReference{},
   287  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   288  						Type:        "int",
   289  						Mandatory:   false,
   290  						Aliases:     []config.Alias{},
   291  						Default:     300,
   292  					},
   293  					{
   294  						Name:        "helmValues",
   295  						ResourceRef: []config.ResourceReference{},
   296  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   297  						Type:        "[]string",
   298  						Mandatory:   false,
   299  						Aliases:     []config.Alias{},
   300  						Default:     []string{},
   301  					},
   302  					{
   303  						Name: "image",
   304  						ResourceRef: []config.ResourceReference{
   305  							{
   306  								Name:  "commonPipelineEnvironment",
   307  								Param: "container/imageNameTag",
   308  							},
   309  						},
   310  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   311  						Type:      "string",
   312  						Mandatory: true,
   313  						Aliases:   []config.Alias{{Name: "deployImage"}},
   314  						Default:   os.Getenv("PIPER_image"),
   315  					},
   316  					{
   317  						Name:        "keepFailedDeployments",
   318  						ResourceRef: []config.ResourceReference{},
   319  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   320  						Type:        "bool",
   321  						Mandatory:   false,
   322  						Aliases:     []config.Alias{},
   323  						Default:     false,
   324  					},
   325  					{
   326  						Name: "kubeConfig",
   327  						ResourceRef: []config.ResourceReference{
   328  							{
   329  								Name: "kubeConfigFileCredentialsId",
   330  								Type: "secret",
   331  							},
   332  
   333  							{
   334  								Name:    "kubeConfigFileVaultSecretName",
   335  								Type:    "vaultSecretFile",
   336  								Default: "kube-config",
   337  							},
   338  						},
   339  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   340  						Type:      "string",
   341  						Mandatory: false,
   342  						Aliases:   []config.Alias{},
   343  						Default:   os.Getenv("PIPER_kubeConfig"),
   344  					},
   345  					{
   346  						Name:        "kubeContext",
   347  						ResourceRef: []config.ResourceReference{},
   348  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   349  						Type:        "string",
   350  						Mandatory:   false,
   351  						Aliases:     []config.Alias{},
   352  						Default:     os.Getenv("PIPER_kubeContext"),
   353  					},
   354  					{
   355  						Name:        "namespace",
   356  						ResourceRef: []config.ResourceReference{},
   357  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   358  						Type:        "string",
   359  						Mandatory:   false,
   360  						Aliases:     []config.Alias{{Name: "helmDeploymentNamespace"}},
   361  						Default:     `default`,
   362  					},
   363  					{
   364  						Name: "dockerConfigJSON",
   365  						ResourceRef: []config.ResourceReference{
   366  							{
   367  								Name: "dockerConfigJsonCredentialsId",
   368  								Type: "secret",
   369  							},
   370  
   371  							{
   372  								Name:    "dockerConfigFileVaultSecretName",
   373  								Type:    "vaultSecretFile",
   374  								Default: "docker-config",
   375  							},
   376  						},
   377  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   378  						Type:      "string",
   379  						Mandatory: false,
   380  						Aliases:   []config.Alias{},
   381  						Default:   os.Getenv("PIPER_dockerConfigJSON"),
   382  					},
   383  					{
   384  						Name:        "helmCommand",
   385  						ResourceRef: []config.ResourceReference{},
   386  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   387  						Type:        "string",
   388  						Mandatory:   false,
   389  						Aliases:     []config.Alias{},
   390  						Default:     os.Getenv("PIPER_helmCommand"),
   391  					},
   392  					{
   393  						Name:        "appVersion",
   394  						ResourceRef: []config.ResourceReference{},
   395  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   396  						Type:        "string",
   397  						Mandatory:   false,
   398  						Aliases:     []config.Alias{},
   399  						Default:     os.Getenv("PIPER_appVersion"),
   400  					},
   401  					{
   402  						Name:        "dependencyUpdate",
   403  						ResourceRef: []config.ResourceReference{},
   404  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   405  						Type:        "bool",
   406  						Mandatory:   false,
   407  						Aliases:     []config.Alias{},
   408  						Default:     false,
   409  					},
   410  					{
   411  						Name:        "dumpLogs",
   412  						ResourceRef: []config.ResourceReference{},
   413  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   414  						Type:        "bool",
   415  						Mandatory:   false,
   416  						Aliases:     []config.Alias{},
   417  						Default:     false,
   418  					},
   419  					{
   420  						Name:        "filterTest",
   421  						ResourceRef: []config.ResourceReference{},
   422  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   423  						Type:        "string",
   424  						Mandatory:   false,
   425  						Aliases:     []config.Alias{},
   426  						Default:     os.Getenv("PIPER_filterTest"),
   427  					},
   428  					{
   429  						Name:        "customTlsCertificateLinks",
   430  						ResourceRef: []config.ResourceReference{},
   431  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   432  						Type:        "[]string",
   433  						Mandatory:   false,
   434  						Aliases:     []config.Alias{},
   435  						Default:     []string{},
   436  					},
   437  					{
   438  						Name:        "publish",
   439  						ResourceRef: []config.ResourceReference{},
   440  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   441  						Type:        "bool",
   442  						Mandatory:   false,
   443  						Aliases:     []config.Alias{},
   444  						Default:     false,
   445  					},
   446  				},
   447  			},
   448  			Containers: []config.Container{
   449  				{Image: "dtzar/helm-kubectl:3.8.0", WorkingDir: "/config", Options: []config.Option{{Name: "-u", Value: "0"}}},
   450  			},
   451  		},
   452  	}
   453  	return theMetaData
   454  }