From 86e28d2848b846eee730f249e2e3e2a530642987 Mon Sep 17 00:00:00 2001 From: Yurii Rochniak Date: Mon, 27 Mar 2023 11:18:44 +0200 Subject: [PATCH] Exit with WARN code if no objects satisfy a policy (#6678) Signed-off-by: Yurii Rochniak Co-authored-by: shuting --- cmd/cli/kubectl-kyverno/apply/apply_command.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/cmd/cli/kubectl-kyverno/apply/apply_command.go b/cmd/cli/kubectl-kyverno/apply/apply_command.go index 1091244de2..b23fc74a55 100644 --- a/cmd/cli/kubectl-kyverno/apply/apply_command.go +++ b/cmd/cli/kubectl-kyverno/apply/apply_command.go @@ -65,6 +65,7 @@ type ApplyCommandConfig struct { PolicyPaths []string GitBranch string warnExitCode int + warnNoPassed bool } var ( @@ -174,7 +175,7 @@ func Command() *cobra.Command { return err } - PrintReportOrViolation(applyCommandConfig.PolicyReport, rc, applyCommandConfig.ResourcePaths, len(resources), skipInvalidPolicies, applyCommandConfig.Stdin, pvInfos, applyCommandConfig.warnExitCode) + PrintReportOrViolation(applyCommandConfig.PolicyReport, rc, applyCommandConfig.ResourcePaths, len(resources), skipInvalidPolicies, applyCommandConfig.Stdin, pvInfos, applyCommandConfig.warnExitCode, applyCommandConfig.warnNoPassed) return nil }, } @@ -194,6 +195,7 @@ func Command() *cobra.Command { cmd.Flags().StringVarP(&applyCommandConfig.GitBranch, "git-branch", "b", "", "test git repository branch") cmd.Flags().BoolVarP(&applyCommandConfig.AuditWarn, "audit-warn", "", false, "If set to true, will flag audit policies as warnings instead of failures") cmd.Flags().IntVar(&applyCommandConfig.warnExitCode, "warn-exit-code", 0, "Set the exit code for warnings; if failures or errors are found, will exit 1") + cmd.Flags().BoolVarP(&applyCommandConfig.warnNoPassed, "warn-no-pass", "", false, "Specify if warning exit code should be raised if no objects satisfied a policy; can be used together with --warn-exit-code flag") return cmd } @@ -465,7 +467,7 @@ func checkMutateLogPath(mutateLogPath string) (mutateLogPathIsDir bool, err erro } // PrintReportOrViolation - printing policy report/violations -func PrintReportOrViolation(policyReport bool, rc *common.ResultCounts, resourcePaths []string, resourcesLen int, skipInvalidPolicies SkippedInvalidPolicies, stdin bool, pvInfos []common.Info, warnExitCode int) { +func PrintReportOrViolation(policyReport bool, rc *common.ResultCounts, resourcePaths []string, resourcesLen int, skipInvalidPolicies SkippedInvalidPolicies, stdin bool, pvInfos []common.Info, warnExitCode int, warnNoPassed bool) { divider := "----------------------------------------------------------------------" if len(skipInvalidPolicies.skipped) > 0 { @@ -509,6 +511,8 @@ func PrintReportOrViolation(policyReport bool, rc *common.ResultCounts, resource osExit(1) } else if rc.Warn > 0 && warnExitCode != 0 { osExit(warnExitCode) + } else if rc.Pass == 0 && warnNoPassed { + osExit(warnExitCode) } }