github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/cmd/vaultRotateSecretId_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 vaultRotateSecretIdOptions struct {
    19  	SecretStore                          string `json:"secretStore,omitempty" validate:"possible-values=jenkins ado github"`
    20  	JenkinsURL                           string `json:"jenkinsUrl,omitempty"`
    21  	JenkinsCredentialDomain              string `json:"jenkinsCredentialDomain,omitempty"`
    22  	JenkinsUsername                      string `json:"jenkinsUsername,omitempty"`
    23  	JenkinsToken                         string `json:"jenkinsToken,omitempty"`
    24  	VaultAppRoleSecretTokenCredentialsID string `json:"vaultAppRoleSecretTokenCredentialsId,omitempty"`
    25  	VaultServerURL                       string `json:"vaultServerUrl,omitempty"`
    26  	VaultNamespace                       string `json:"vaultNamespace,omitempty"`
    27  	DaysBeforeExpiry                     int    `json:"daysBeforeExpiry,omitempty"`
    28  	AdoOrganization                      string `json:"adoOrganization,omitempty"`
    29  	AdoPersonalAccessToken               string `json:"adoPersonalAccessToken,omitempty" validate:"required_if=SecretStore ado"`
    30  	AdoProject                           string `json:"adoProject,omitempty"`
    31  	AdoPipelineID                        int    `json:"adoPipelineId,omitempty"`
    32  	GithubToken                          string `json:"githubToken,omitempty" validate:"required_if=SecretStore github"`
    33  	GithubAPIURL                         string `json:"githubApiUrl,omitempty"`
    34  	Owner                                string `json:"owner,omitempty"`
    35  	Repository                           string `json:"repository,omitempty"`
    36  }
    37  
    38  // VaultRotateSecretIdCommand Rotate Vault AppRole Secret ID
    39  func VaultRotateSecretIdCommand() *cobra.Command {
    40  	const STEP_NAME = "vaultRotateSecretId"
    41  
    42  	metadata := vaultRotateSecretIdMetadata()
    43  	var stepConfig vaultRotateSecretIdOptions
    44  	var startTime time.Time
    45  	var logCollector *log.CollectorHook
    46  	var splunkClient *splunk.Splunk
    47  	telemetryClient := &telemetry.Telemetry{}
    48  
    49  	var createVaultRotateSecretIdCmd = &cobra.Command{
    50  		Use:   STEP_NAME,
    51  		Short: "Rotate Vault AppRole Secret ID",
    52  		Long:  `This step takes the given Vault secret ID and checks whether it needs to be renewed and if so it will update the secret ID in the configured secret store.`,
    53  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    54  			startTime = time.Now()
    55  			log.SetStepName(STEP_NAME)
    56  			log.SetVerbose(GeneralConfig.Verbose)
    57  
    58  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    59  
    60  			path, _ := os.Getwd()
    61  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    62  			log.RegisterHook(fatalHook)
    63  
    64  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    65  			if err != nil {
    66  				log.SetErrorCategory(log.ErrorConfiguration)
    67  				return err
    68  			}
    69  			log.RegisterSecret(stepConfig.JenkinsURL)
    70  			log.RegisterSecret(stepConfig.JenkinsUsername)
    71  			log.RegisterSecret(stepConfig.JenkinsToken)
    72  			log.RegisterSecret(stepConfig.AdoPersonalAccessToken)
    73  			log.RegisterSecret(stepConfig.GithubToken)
    74  
    75  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
    76  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
    77  				log.RegisterHook(&sentryHook)
    78  			}
    79  
    80  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
    81  				splunkClient = &splunk.Splunk{}
    82  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
    83  				log.RegisterHook(logCollector)
    84  			}
    85  
    86  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
    87  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
    88  			}
    89  
    90  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
    91  			if err != nil {
    92  				return err
    93  			}
    94  			if err = validation.ValidateStruct(stepConfig); err != nil {
    95  				log.SetErrorCategory(log.ErrorConfiguration)
    96  				return err
    97  			}
    98  
    99  			return nil
   100  		},
   101  		Run: func(_ *cobra.Command, _ []string) {
   102  			stepTelemetryData := telemetry.CustomData{}
   103  			stepTelemetryData.ErrorCode = "1"
   104  			handler := func() {
   105  				config.RemoveVaultSecretFiles()
   106  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   107  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   108  				stepTelemetryData.PiperCommitHash = GitCommit
   109  				telemetryClient.SetData(&stepTelemetryData)
   110  				telemetryClient.Send()
   111  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   112  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   113  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   114  						GeneralConfig.HookConfig.SplunkConfig.Token,
   115  						GeneralConfig.HookConfig.SplunkConfig.Index,
   116  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   117  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   118  				}
   119  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   120  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   121  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   122  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   123  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   124  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   125  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   126  				}
   127  			}
   128  			log.DeferExitHandler(handler)
   129  			defer handler()
   130  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   131  			vaultRotateSecretId(stepConfig, &stepTelemetryData)
   132  			stepTelemetryData.ErrorCode = "0"
   133  			log.Entry().Info("SUCCESS")
   134  		},
   135  	}
   136  
   137  	addVaultRotateSecretIdFlags(createVaultRotateSecretIdCmd, &stepConfig)
   138  	return createVaultRotateSecretIdCmd
   139  }
   140  
   141  func addVaultRotateSecretIdFlags(cmd *cobra.Command, stepConfig *vaultRotateSecretIdOptions) {
   142  	cmd.Flags().StringVar(&stepConfig.SecretStore, "secretStore", `jenkins`, "The store to which the secret should be written back to")
   143  	cmd.Flags().StringVar(&stepConfig.JenkinsURL, "jenkinsUrl", os.Getenv("PIPER_jenkinsUrl"), "The jenkins url")
   144  	cmd.Flags().StringVar(&stepConfig.JenkinsCredentialDomain, "jenkinsCredentialDomain", `_`, "The jenkins credential domain which should be used")
   145  	cmd.Flags().StringVar(&stepConfig.JenkinsUsername, "jenkinsUsername", os.Getenv("PIPER_jenkinsUsername"), "The jenkins username")
   146  	cmd.Flags().StringVar(&stepConfig.JenkinsToken, "jenkinsToken", os.Getenv("PIPER_jenkinsToken"), "The jenkins token")
   147  	cmd.Flags().StringVar(&stepConfig.VaultAppRoleSecretTokenCredentialsID, "vaultAppRoleSecretTokenCredentialsId", os.Getenv("PIPER_vaultAppRoleSecretTokenCredentialsId"), "The Jenkins credential ID, Azure DevOps variable name, or GitHub Actions secret name for the Vault AppRole Secret ID credential")
   148  	cmd.Flags().StringVar(&stepConfig.VaultServerURL, "vaultServerUrl", os.Getenv("PIPER_vaultServerUrl"), "The URL for the Vault server to use")
   149  	cmd.Flags().StringVar(&stepConfig.VaultNamespace, "vaultNamespace", os.Getenv("PIPER_vaultNamespace"), "The Vault namespace that should be used (optional)")
   150  	cmd.Flags().IntVar(&stepConfig.DaysBeforeExpiry, "daysBeforeExpiry", 15, "The amount of days before expiry until the secret ID gets rotated")
   151  	cmd.Flags().StringVar(&stepConfig.AdoOrganization, "adoOrganization", os.Getenv("PIPER_adoOrganization"), "The Azure DevOps organization name")
   152  	cmd.Flags().StringVar(&stepConfig.AdoPersonalAccessToken, "adoPersonalAccessToken", os.Getenv("PIPER_adoPersonalAccessToken"), "The Azure DevOps personal access token")
   153  	cmd.Flags().StringVar(&stepConfig.AdoProject, "adoProject", os.Getenv("PIPER_adoProject"), "The Azure DevOps project ID. Project name also can be used")
   154  	cmd.Flags().IntVar(&stepConfig.AdoPipelineID, "adoPipelineId", 0, "The Azure DevOps pipeline ID. Also called as definition ID")
   155  	cmd.Flags().StringVar(&stepConfig.GithubToken, "githubToken", os.Getenv("PIPER_githubToken"), "GitHub personal access token as per https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line with the scope 'repo'")
   156  	cmd.Flags().StringVar(&stepConfig.GithubAPIURL, "githubApiUrl", `https://api.github.com`, "Set the GitHub API URL that corresponds to the pipeline repository")
   157  	cmd.Flags().StringVar(&stepConfig.Owner, "owner", os.Getenv("PIPER_owner"), "Owner of the pipeline GitHub repository")
   158  	cmd.Flags().StringVar(&stepConfig.Repository, "repository", os.Getenv("PIPER_repository"), "Name of the pipeline GitHub repository")
   159  
   160  	cmd.MarkFlagRequired("vaultAppRoleSecretTokenCredentialsId")
   161  	cmd.MarkFlagRequired("vaultServerUrl")
   162  }
   163  
   164  // retrieve step metadata
   165  func vaultRotateSecretIdMetadata() config.StepData {
   166  	var theMetaData = config.StepData{
   167  		Metadata: config.StepMetadata{
   168  			Name:        "vaultRotateSecretId",
   169  			Aliases:     []config.Alias{},
   170  			Description: "Rotate Vault AppRole Secret ID",
   171  		},
   172  		Spec: config.StepSpec{
   173  			Inputs: config.StepInputs{
   174  				Parameters: []config.StepParameters{
   175  					{
   176  						Name:        "secretStore",
   177  						ResourceRef: []config.ResourceReference{},
   178  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   179  						Type:        "string",
   180  						Mandatory:   false,
   181  						Aliases:     []config.Alias{},
   182  						Default:     `jenkins`,
   183  					},
   184  					{
   185  						Name: "jenkinsUrl",
   186  						ResourceRef: []config.ResourceReference{
   187  							{
   188  								Name:    "jenkinsVaultSecretName",
   189  								Type:    "vaultSecret",
   190  								Default: "jenkins",
   191  							},
   192  						},
   193  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   194  						Type:      "string",
   195  						Mandatory: false,
   196  						Aliases:   []config.Alias{{Name: "url"}},
   197  						Default:   os.Getenv("PIPER_jenkinsUrl"),
   198  					},
   199  					{
   200  						Name:        "jenkinsCredentialDomain",
   201  						ResourceRef: []config.ResourceReference{},
   202  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   203  						Type:        "string",
   204  						Mandatory:   false,
   205  						Aliases:     []config.Alias{},
   206  						Default:     `_`,
   207  					},
   208  					{
   209  						Name: "jenkinsUsername",
   210  						ResourceRef: []config.ResourceReference{
   211  							{
   212  								Name:    "jenkinsVaultSecretName",
   213  								Type:    "vaultSecret",
   214  								Default: "jenkins",
   215  							},
   216  						},
   217  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   218  						Type:      "string",
   219  						Mandatory: false,
   220  						Aliases:   []config.Alias{{Name: "userId"}},
   221  						Default:   os.Getenv("PIPER_jenkinsUsername"),
   222  					},
   223  					{
   224  						Name: "jenkinsToken",
   225  						ResourceRef: []config.ResourceReference{
   226  							{
   227  								Name:    "jenkinsVaultSecretName",
   228  								Type:    "vaultSecret",
   229  								Default: "jenkins",
   230  							},
   231  						},
   232  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   233  						Type:      "string",
   234  						Mandatory: false,
   235  						Aliases:   []config.Alias{{Name: "token"}},
   236  						Default:   os.Getenv("PIPER_jenkinsToken"),
   237  					},
   238  					{
   239  						Name:        "vaultAppRoleSecretTokenCredentialsId",
   240  						ResourceRef: []config.ResourceReference{},
   241  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   242  						Type:        "string",
   243  						Mandatory:   true,
   244  						Aliases:     []config.Alias{},
   245  						Default:     os.Getenv("PIPER_vaultAppRoleSecretTokenCredentialsId"),
   246  					},
   247  					{
   248  						Name:        "vaultServerUrl",
   249  						ResourceRef: []config.ResourceReference{},
   250  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   251  						Type:        "string",
   252  						Mandatory:   true,
   253  						Aliases:     []config.Alias{},
   254  						Default:     os.Getenv("PIPER_vaultServerUrl"),
   255  					},
   256  					{
   257  						Name:        "vaultNamespace",
   258  						ResourceRef: []config.ResourceReference{},
   259  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   260  						Type:        "string",
   261  						Mandatory:   false,
   262  						Aliases:     []config.Alias{},
   263  						Default:     os.Getenv("PIPER_vaultNamespace"),
   264  					},
   265  					{
   266  						Name:        "daysBeforeExpiry",
   267  						ResourceRef: []config.ResourceReference{},
   268  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   269  						Type:        "int",
   270  						Mandatory:   false,
   271  						Aliases:     []config.Alias{},
   272  						Default:     15,
   273  					},
   274  					{
   275  						Name:        "adoOrganization",
   276  						ResourceRef: []config.ResourceReference{},
   277  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   278  						Type:        "string",
   279  						Mandatory:   false,
   280  						Aliases:     []config.Alias{},
   281  						Default:     os.Getenv("PIPER_adoOrganization"),
   282  					},
   283  					{
   284  						Name: "adoPersonalAccessToken",
   285  						ResourceRef: []config.ResourceReference{
   286  							{
   287  								Name:    "azureDevOpsVaultSecretName",
   288  								Type:    "vaultSecret",
   289  								Default: "azure-dev-ops",
   290  							},
   291  						},
   292  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   293  						Type:      "string",
   294  						Mandatory: false,
   295  						Aliases:   []config.Alias{{Name: "token"}},
   296  						Default:   os.Getenv("PIPER_adoPersonalAccessToken"),
   297  					},
   298  					{
   299  						Name:        "adoProject",
   300  						ResourceRef: []config.ResourceReference{},
   301  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   302  						Type:        "string",
   303  						Mandatory:   false,
   304  						Aliases:     []config.Alias{},
   305  						Default:     os.Getenv("PIPER_adoProject"),
   306  					},
   307  					{
   308  						Name:        "adoPipelineId",
   309  						ResourceRef: []config.ResourceReference{},
   310  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   311  						Type:        "int",
   312  						Mandatory:   false,
   313  						Aliases:     []config.Alias{},
   314  						Default:     0,
   315  					},
   316  					{
   317  						Name: "githubToken",
   318  						ResourceRef: []config.ResourceReference{
   319  							{
   320  								Name:    "githubVaultSecretName",
   321  								Type:    "vaultSecret",
   322  								Default: "github",
   323  							},
   324  						},
   325  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   326  						Type:      "string",
   327  						Mandatory: false,
   328  						Aliases:   []config.Alias{{Name: "access_token"}, {Name: "token"}},
   329  						Default:   os.Getenv("PIPER_githubToken"),
   330  					},
   331  					{
   332  						Name:        "githubApiUrl",
   333  						ResourceRef: []config.ResourceReference{},
   334  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   335  						Type:        "string",
   336  						Mandatory:   false,
   337  						Aliases:     []config.Alias{},
   338  						Default:     `https://api.github.com`,
   339  					},
   340  					{
   341  						Name: "owner",
   342  						ResourceRef: []config.ResourceReference{
   343  							{
   344  								Name:  "commonPipelineEnvironment",
   345  								Param: "github/owner",
   346  							},
   347  						},
   348  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   349  						Type:      "string",
   350  						Mandatory: false,
   351  						Aliases:   []config.Alias{},
   352  						Default:   os.Getenv("PIPER_owner"),
   353  					},
   354  					{
   355  						Name: "repository",
   356  						ResourceRef: []config.ResourceReference{
   357  							{
   358  								Name:  "commonPipelineEnvironment",
   359  								Param: "github/repository",
   360  							},
   361  						},
   362  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   363  						Type:      "string",
   364  						Mandatory: false,
   365  						Aliases:   []config.Alias{},
   366  						Default:   os.Getenv("PIPER_repository"),
   367  					},
   368  				},
   369  			},
   370  		},
   371  	}
   372  	return theMetaData
   373  }