github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/cmd/terraformExecute_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 "path/filepath" 9 "time" 10 11 "github.com/SAP/jenkins-library/pkg/config" 12 "github.com/SAP/jenkins-library/pkg/log" 13 "github.com/SAP/jenkins-library/pkg/piperenv" 14 "github.com/SAP/jenkins-library/pkg/splunk" 15 "github.com/SAP/jenkins-library/pkg/telemetry" 16 "github.com/SAP/jenkins-library/pkg/validation" 17 "github.com/spf13/cobra" 18 ) 19 20 type terraformExecuteOptions struct { 21 Command string `json:"command,omitempty"` 22 TerraformSecrets string `json:"terraformSecrets,omitempty"` 23 GlobalOptions []string `json:"globalOptions,omitempty"` 24 AdditionalArgs []string `json:"additionalArgs,omitempty"` 25 Init bool `json:"init,omitempty"` 26 CliConfigFile string `json:"cliConfigFile,omitempty"` 27 Workspace string `json:"workspace,omitempty"` 28 } 29 30 type terraformExecuteCommonPipelineEnvironment struct { 31 custom struct { 32 terraformOutputs map[string]interface{} 33 } 34 } 35 36 func (p *terraformExecuteCommonPipelineEnvironment) persist(path, resourceName string) { 37 content := []struct { 38 category string 39 name string 40 value interface{} 41 }{ 42 {category: "custom", name: "terraformOutputs", value: p.custom.terraformOutputs}, 43 } 44 45 errCount := 0 46 for _, param := range content { 47 err := piperenv.SetResourceParameter(path, resourceName, filepath.Join(param.category, param.name), param.value) 48 if err != nil { 49 log.Entry().WithError(err).Error("Error persisting piper environment.") 50 errCount++ 51 } 52 } 53 if errCount > 0 { 54 log.Entry().Error("failed to persist Piper environment") 55 } 56 } 57 58 // TerraformExecuteCommand Executes Terraform 59 func TerraformExecuteCommand() *cobra.Command { 60 const STEP_NAME = "terraformExecute" 61 62 metadata := terraformExecuteMetadata() 63 var stepConfig terraformExecuteOptions 64 var startTime time.Time 65 var commonPipelineEnvironment terraformExecuteCommonPipelineEnvironment 66 var logCollector *log.CollectorHook 67 var splunkClient *splunk.Splunk 68 telemetryClient := &telemetry.Telemetry{} 69 70 var createTerraformExecuteCmd = &cobra.Command{ 71 Use: STEP_NAME, 72 Short: "Executes Terraform", 73 Long: `This step executes the terraform binary with the given command, and is able to fetch additional variables from vault.`, 74 PreRunE: func(cmd *cobra.Command, _ []string) error { 75 startTime = time.Now() 76 log.SetStepName(STEP_NAME) 77 log.SetVerbose(GeneralConfig.Verbose) 78 79 GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens) 80 81 path, _ := os.Getwd() 82 fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path} 83 log.RegisterHook(fatalHook) 84 85 err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile) 86 if err != nil { 87 log.SetErrorCategory(log.ErrorConfiguration) 88 return err 89 } 90 log.RegisterSecret(stepConfig.CliConfigFile) 91 92 if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 { 93 sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID) 94 log.RegisterHook(&sentryHook) 95 } 96 97 if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 { 98 splunkClient = &splunk.Splunk{} 99 logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID} 100 log.RegisterHook(logCollector) 101 } 102 103 if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil { 104 log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook") 105 } 106 107 validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages()) 108 if err != nil { 109 return err 110 } 111 if err = validation.ValidateStruct(stepConfig); err != nil { 112 log.SetErrorCategory(log.ErrorConfiguration) 113 return err 114 } 115 116 return nil 117 }, 118 Run: func(_ *cobra.Command, _ []string) { 119 stepTelemetryData := telemetry.CustomData{} 120 stepTelemetryData.ErrorCode = "1" 121 handler := func() { 122 commonPipelineEnvironment.persist(GeneralConfig.EnvRootPath, "commonPipelineEnvironment") 123 config.RemoveVaultSecretFiles() 124 stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds()) 125 stepTelemetryData.ErrorCategory = log.GetErrorCategory().String() 126 stepTelemetryData.PiperCommitHash = GitCommit 127 telemetryClient.SetData(&stepTelemetryData) 128 telemetryClient.Send() 129 if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 { 130 splunkClient.Initialize(GeneralConfig.CorrelationID, 131 GeneralConfig.HookConfig.SplunkConfig.Dsn, 132 GeneralConfig.HookConfig.SplunkConfig.Token, 133 GeneralConfig.HookConfig.SplunkConfig.Index, 134 GeneralConfig.HookConfig.SplunkConfig.SendLogs) 135 splunkClient.Send(telemetryClient.GetData(), logCollector) 136 } 137 if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 { 138 splunkClient.Initialize(GeneralConfig.CorrelationID, 139 GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint, 140 GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken, 141 GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex, 142 GeneralConfig.HookConfig.SplunkConfig.SendLogs) 143 splunkClient.Send(telemetryClient.GetData(), logCollector) 144 } 145 } 146 log.DeferExitHandler(handler) 147 defer handler() 148 telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME) 149 terraformExecute(stepConfig, &stepTelemetryData, &commonPipelineEnvironment) 150 stepTelemetryData.ErrorCode = "0" 151 log.Entry().Info("SUCCESS") 152 }, 153 } 154 155 addTerraformExecuteFlags(createTerraformExecuteCmd, &stepConfig) 156 return createTerraformExecuteCmd 157 } 158 159 func addTerraformExecuteFlags(cmd *cobra.Command, stepConfig *terraformExecuteOptions) { 160 cmd.Flags().StringVar(&stepConfig.Command, "command", `plan`, "") 161 cmd.Flags().StringVar(&stepConfig.TerraformSecrets, "terraformSecrets", os.Getenv("PIPER_terraformSecrets"), "") 162 cmd.Flags().StringSliceVar(&stepConfig.GlobalOptions, "globalOptions", []string{}, "") 163 cmd.Flags().StringSliceVar(&stepConfig.AdditionalArgs, "additionalArgs", []string{}, "") 164 cmd.Flags().BoolVar(&stepConfig.Init, "init", false, "") 165 cmd.Flags().StringVar(&stepConfig.CliConfigFile, "cliConfigFile", os.Getenv("PIPER_cliConfigFile"), "Path to the terraform CLI configuration file (https://www.terraform.io/docs/cli/config/config-file.html#credentials).") 166 cmd.Flags().StringVar(&stepConfig.Workspace, "workspace", os.Getenv("PIPER_workspace"), "") 167 168 } 169 170 // retrieve step metadata 171 func terraformExecuteMetadata() config.StepData { 172 var theMetaData = config.StepData{ 173 Metadata: config.StepMetadata{ 174 Name: "terraformExecute", 175 Aliases: []config.Alias{}, 176 Description: "Executes Terraform", 177 }, 178 Spec: config.StepSpec{ 179 Inputs: config.StepInputs{ 180 Secrets: []config.StepSecrets{ 181 {Name: "cliConfigFileCredentialsId", Description: "Jenkins 'Secret file' credentials ID containing terraform CLI configuration. You can find more details about it in the [Terraform documentation](https://www.terraform.io/docs/cli/config/config-file.html#credentials).", Type: "jenkins"}, 182 }, 183 Parameters: []config.StepParameters{ 184 { 185 Name: "command", 186 ResourceRef: []config.ResourceReference{}, 187 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 188 Type: "string", 189 Mandatory: false, 190 Aliases: []config.Alias{}, 191 Default: `plan`, 192 }, 193 { 194 Name: "terraformSecrets", 195 ResourceRef: []config.ResourceReference{ 196 { 197 Name: "terraformFileVaultSecretName", 198 Type: "vaultSecretFile", 199 Default: "terraform", 200 }, 201 }, 202 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 203 Type: "string", 204 Mandatory: false, 205 Aliases: []config.Alias{}, 206 Default: os.Getenv("PIPER_terraformSecrets"), 207 }, 208 { 209 Name: "globalOptions", 210 ResourceRef: []config.ResourceReference{}, 211 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 212 Type: "[]string", 213 Mandatory: false, 214 Aliases: []config.Alias{}, 215 Default: []string{}, 216 }, 217 { 218 Name: "additionalArgs", 219 ResourceRef: []config.ResourceReference{}, 220 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 221 Type: "[]string", 222 Mandatory: false, 223 Aliases: []config.Alias{}, 224 Default: []string{}, 225 }, 226 { 227 Name: "init", 228 ResourceRef: []config.ResourceReference{}, 229 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 230 Type: "bool", 231 Mandatory: false, 232 Aliases: []config.Alias{}, 233 Default: false, 234 }, 235 { 236 Name: "cliConfigFile", 237 ResourceRef: []config.ResourceReference{ 238 { 239 Name: "cliConfigFileCredentialsId", 240 Type: "secret", 241 }, 242 243 { 244 Name: "cliConfigFileVaultSecretName", 245 Type: "vaultSecretFile", 246 Default: "terraform", 247 }, 248 }, 249 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 250 Type: "string", 251 Mandatory: false, 252 Aliases: []config.Alias{}, 253 Default: os.Getenv("PIPER_cliConfigFile"), 254 }, 255 { 256 Name: "workspace", 257 ResourceRef: []config.ResourceReference{}, 258 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 259 Type: "string", 260 Mandatory: false, 261 Aliases: []config.Alias{}, 262 Default: os.Getenv("PIPER_workspace"), 263 }, 264 }, 265 }, 266 Containers: []config.Container{ 267 {Name: "terraform", Image: "hashicorp/terraform:1.0.10", EnvVars: []config.EnvVar{{Name: "TF_IN_AUTOMATION", Value: "piper"}}, Options: []config.Option{{Name: "--entrypoint", Value: ""}}}, 268 }, 269 Outputs: config.StepOutputs{ 270 Resources: []config.StepResources{ 271 { 272 Name: "commonPipelineEnvironment", 273 Type: "piperEnvironment", 274 Parameters: []map[string]interface{}{ 275 {"name": "custom/terraformOutputs", "type": "map[string]interface{}"}, 276 }, 277 }, 278 }, 279 }, 280 }, 281 } 282 return theMetaData 283 }