1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-03-09 09:26:54 +00:00
kyverno/cmd/cli/kubectl-kyverno/processor/policy_processor.go
Ammar Yasser 739e6a21c4
Mutate existing CLI support (#11453)
* feat: Add flags for target resources and add fake client initialization

Signed-off-by: aerosouund <aerosound161@gmail.com>

* feat: Add fake discovery client and cluster bool in the policy processor

Signed-off-by: aerosouund <aerosound161@gmail.com>

* refactor: Use the full mutation engine policy response in the engine response

Signed-off-by: aerosouund <aerosound161@gmail.com>

* feat: Extract mutated targets from the policy responses and print them out

Signed-off-by: aerosouund <aerosound161@gmail.com>

* feat: Add TargetResources field in the cli test schema

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: Generate CLI crds

Signed-off-by: aerosouund <aerosound161@gmail.com>

* refactor: modify checkResult to take an arbitrary actual resource and resource name

Signed-off-by: aerosouund <aerosound161@gmail.com>

* refactor: change getAndCompareResource to take a resource name and cascade it to GetResourceFromPath

Signed-off-by: aerosouund <aerosound161@gmail.com>

* test: Create a simple test to test mutate existing in the CLI

Signed-off-by: aerosouund <aerosound161@gmail.com>

* refactor: Allow GetResourceFromPath to select a resource with a name from a multi resource yaml

Signed-off-by: aerosouund <aerosound161@gmail.com>

* refactor: Modify the runTest command to return the TestResponse type

- Create a fake client, load the target resources in it and use it in the PolicyProcessor.
- Create the TestResponse which contains Trigger and Target fields, each is a map of gvk/name to the responses corresponding to that resource.

Signed-off-by: aerosouund <aerosound161@gmail.com>

* refactor: Rewrite output.go to use the TestResponse type

- Check for both target and trigger
- Create logic for appending the resource array in case no resources are passed
- Move row creation logic into a separate method to avoid code duplication
- Extract the proper target resource based on rule type
- Create a function to extract mutated target from the engine response

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: Move tests to the correct folder

Signed-off-by: aerosouund <aerosound161@gmail.com>

* refactor: Use apiVersion/Kind/Name as the key in the test responses

Signed-off-by: aerosouund <aerosound161@gmail.com>

* refactor: Use the apiVersion/Kind/name key schema in checking results and fix invalid resource name checking for generate policies

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Use better variable names for rows

Signed-off-by: aerosouund <aerosound161@gmail.com>

* refactor: Account for Generate resources being an array

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Use generated resource name in checking the results and printing output

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: Uncomment checks printing

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Remove bug in engine response creation

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Move the generate logic into an else block

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Fix namespace fetching bug in cel validator

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Use pointer to int in the test counter

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: Remove redundant method

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Skip resources not being found in the manifests

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Create another field in the engine to denote if this is a cluster engine or an offline engine

Simply checking for the client being nil is no longer enough because for cli operations the client will be a fake client
A pointer to bool is chosen because callers who don't necessarily know what to pass should be able to pass nil

Signed-off-by: ammar <ammar.yasser@vodafone.com>

* fix: Add extra argument in fake client initiation

Signed-off-by: ammar <ammar.yasser@vodafone.com>

* fix: add extra argument in fuzz test

Signed-off-by: ammar <ammar.yasser@vodafone.com>

* fix: Add extra arg

Signed-off-by: ammar <ammar.yasser@vodafone.com>

* fix: Handle resources specified as ns/name as this schema will be deprecated in favor of apiVersion/Kind/Name

Signed-off-by: ammar <ammar.yasser@vodafone.com>

* fix: Fix linter complaints

Signed-off-by: ammar <ammar.yasser@vodafone.com>

* fix: Use comma separation as array separators as kubernetes names don't support commas

To avoid undefined array length on splitting on /
using commas will result in a fixed length since all resources will have an apiVersion, kind, namespace and name

Signed-off-by: aerosouund <aerosound161@gmail.com>

* refactor: Change resource array type to an array of any instead of array of string

To support the use of a string or a TestResourceSpec

Signed-off-by: aerosouund <aerosound161@gmail.com>

* refactor: Expect the resource array to be an array of string or array of TestResourceSpec

Assert that an array element is either of these types and match the resources in both cases according to the element type
Expect that the key in responses is now separated by commas instead of slashes

Signed-off-by: aerosouund <aerosound161@gmail.com>

* refactor: Expect that the resource array is now of type array of any and modify tests that use it

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Skip response check if the policy name isnt whats in the result

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Match the name if its specified as ns/name

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Fix linter complaint

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: Run codegen

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: Create CLI CRDs

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: Run codegen

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Fix linter complaints

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Cleanup invalid code used in FixTest to adapt it to the schema changes

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Check if resource is nil before extracting

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: use the loadResources method to open targets in a directory

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Account for target resources with the same name but different namespaces

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Add CLI test for mutate existing with the same name

Signed-off-by: aerosouund <aerosound161@gmail.com>

* refactor: Infer resource name and namespace from the actual resource and account for resources with the same name and namespace but different kinds

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: remove extra line

Signed-off-by: aerosouund <aerosound161@gmail.com>

* feat: Add printing mutate existing resources to the output or to a file

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: Minor fixes

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: fix linter complaint

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: codegen

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Revert result back to error

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Use io discard to not print resources in the test command

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: Update vague comments and remove outdated ones

Signed-off-by: aerosouund <aerosound161@gmail.com>

* refactor: Integrate mutate existing changes with diff generation

Signed-off-by: aerosouund <aerosound161@gmail.com>

* refactor: Move resource key generation into a function

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: Add a mutate existing test that fails

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: fix linter complaint

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: Remove redundant comment

Signed-off-by: aerosouund <aerosound161@gmail.com>

* refactor: Fix array of any assignment in cli test

Signed-off-by: aerosouund <aerosound161@gmail.com>

* fix: Dont check duplicate strings for field that is an array of any

Signed-off-by: aerosouund <aerosound161@gmail.com>

* bug: Fix appending to the wrong array

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: run fix tests

Signed-off-by: aerosouund <aerosound161@gmail.com>

* chore: Run fix tests

Signed-off-by: aerosouund <aerosound161@gmail.com>

---------

Signed-off-by: aerosouund <aerosound161@gmail.com>
Signed-off-by: ammar <ammar.yasser@vodafone.com>
Signed-off-by: Ammar Yasser <aerosound161@gmail.com>
Co-authored-by: ammar <ammar.yasser@vodafone.com>
Co-authored-by: shuting <shuting@nirmata.com>
2024-12-19 07:42:54 +00:00

448 lines
15 KiB
Go

package processor
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
json_patch "github.com/evanphx/json-patch/v5"
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
kyvernov2 "github.com/kyverno/kyverno/api/kyverno/v2"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/apis/v1alpha1"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/log"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/store"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/common"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/variables"
"github.com/kyverno/kyverno/pkg/clients/dclient"
"github.com/kyverno/kyverno/pkg/config"
"github.com/kyverno/kyverno/pkg/engine"
"github.com/kyverno/kyverno/pkg/engine/adapters"
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
"github.com/kyverno/kyverno/pkg/engine/factories"
"github.com/kyverno/kyverno/pkg/engine/jmespath"
"github.com/kyverno/kyverno/pkg/engine/mutate/patch"
"github.com/kyverno/kyverno/pkg/engine/policycontext"
"github.com/kyverno/kyverno/pkg/exceptions"
"github.com/kyverno/kyverno/pkg/imageverifycache"
"github.com/kyverno/kyverno/pkg/registryclient"
jsonutils "github.com/kyverno/kyverno/pkg/utils/json"
"gomodules.xyz/jsonpatch/v2"
yamlv2 "gopkg.in/yaml.v2"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
)
type PolicyProcessor struct {
Store *store.Store
Policies []kyvernov1.PolicyInterface
Resource unstructured.Unstructured
PolicyExceptions []*kyvernov2.PolicyException
MutateLogPath string
MutateLogPathIsDir bool
Variables *variables.Variables
Cluster bool
UserInfo *kyvernov2.RequestInfo
PolicyReport bool
NamespaceSelectorMap map[string]map[string]string
Stdin bool
Rc *ResultCounts
PrintPatchResource bool
RuleToCloneSourceResource map[string]string
Client dclient.Interface
AuditWarn bool
Subresources []v1alpha1.Subresource
Out io.Writer
}
func (p *PolicyProcessor) ApplyPoliciesOnResource() ([]engineapi.EngineResponse, error) {
cfg := config.NewDefaultConfiguration(false)
jp := jmespath.New(cfg)
resource := p.Resource
namespaceLabels := p.NamespaceSelectorMap[p.Resource.GetNamespace()]
policyExceptionLister := &policyExceptionLister{
exceptions: p.PolicyExceptions,
}
var client engineapi.Client
if p.Client != nil {
client = adapters.Client(p.Client)
}
rclient := p.Store.GetRegistryClient()
if rclient == nil {
rclient = registryclient.NewOrDie()
}
isCluster := false
eng := engine.NewEngine(
cfg,
config.NewDefaultMetricsConfiguration(),
jmespath.New(cfg),
client,
factories.DefaultRegistryClientFactory(adapters.RegistryClient(rclient), nil),
imageverifycache.DisabledImageVerifyCache(),
store.ContextLoaderFactory(p.Store, nil),
exceptions.New(policyExceptionLister),
&isCluster,
)
gvk, subresource := resource.GroupVersionKind(), ""
resourceKind := resource.GetKind()
resourceName := resource.GetName()
resourceNamespace := resource.GetNamespace()
// If --cluster flag is not set, then we need to find the top level resource GVK and subresource
if !p.Cluster {
for _, s := range p.Subresources {
subgvk := schema.GroupVersionKind{
Group: s.Subresource.Group,
Version: s.Subresource.Version,
Kind: s.Subresource.Kind,
}
if gvk == subgvk {
gvk = schema.GroupVersionKind{
Group: s.ParentResource.Group,
Version: s.ParentResource.Version,
Kind: s.ParentResource.Kind,
}
parts := strings.Split(s.Subresource.Name, "/")
subresource = parts[1]
}
}
} else {
if len(namespaceLabels) == 0 && resourceKind != "Namespace" && resourceNamespace != "" {
ns, err := p.Client.GetResource(context.TODO(), "v1", "Namespace", "", resourceNamespace)
if err != nil {
log.Log.Error(err, "failed to get the resource's namespace")
return nil, fmt.Errorf("failed to get the resource's namespace (%w)", err)
}
namespaceLabels = ns.GetLabels()
}
}
resPath := fmt.Sprintf("%s/%s/%s", resourceNamespace, resourceKind, resourceName)
responses := make([]engineapi.EngineResponse, 0, len(p.Policies))
// mutate
for _, policy := range p.Policies {
if !policy.GetSpec().HasMutate() {
continue
}
policyContext, err := p.makePolicyContext(jp, cfg, resource, policy, namespaceLabels, gvk, subresource)
if err != nil {
return responses, err
}
mutateResponse := eng.Mutate(context.Background(), policyContext)
err = p.processMutateEngineResponse(mutateResponse, resPath)
if err != nil {
return responses, fmt.Errorf("failed to print mutated result (%w)", err)
}
responses = append(responses, mutateResponse)
resource = mutateResponse.PatchedResource
}
// verify images
for _, policy := range p.Policies {
if !policy.GetSpec().HasVerifyImages() {
continue
}
policyContext, err := p.makePolicyContext(jp, cfg, resource, policy, namespaceLabels, gvk, subresource)
if err != nil {
return responses, err
}
verifyImageResponse, verifiedImageData := eng.VerifyAndPatchImages(context.TODO(), policyContext)
// update annotation to reflect verified images
var patches []jsonpatch.JsonPatchOperation
if !verifiedImageData.IsEmpty() {
annotationPatches, err := verifiedImageData.Patches(len(verifyImageResponse.PatchedResource.GetAnnotations()) != 0, log.Log)
if err != nil {
return responses, err
}
// add annotation patches first
patches = append(annotationPatches, patches...)
}
if len(patches) != 0 {
patch := jsonutils.JoinPatches(patch.ConvertPatches(patches...)...)
decoded, err := json_patch.DecodePatch(patch)
if err != nil {
return responses, err
}
options := &json_patch.ApplyOptions{SupportNegativeIndices: true, AllowMissingPathOnRemove: true, EnsurePathExistsOnAdd: true}
resourceBytes, err := verifyImageResponse.PatchedResource.MarshalJSON()
if err != nil {
return responses, err
}
patchedResourceBytes, err := decoded.ApplyWithOptions(resourceBytes, options)
if err != nil {
return responses, err
}
if err := verifyImageResponse.PatchedResource.UnmarshalJSON(patchedResourceBytes); err != nil {
return responses, err
}
}
responses = append(responses, verifyImageResponse)
resource = verifyImageResponse.PatchedResource
}
// validate
for _, policy := range p.Policies {
if !policyHasValidateOrVerifyImageChecks(policy) {
continue
}
policyContext, err := p.makePolicyContext(jp, cfg, resource, policy, namespaceLabels, gvk, subresource)
if err != nil {
return responses, err
}
validateResponse := eng.Validate(context.TODO(), policyContext)
responses = append(responses, validateResponse)
resource = validateResponse.PatchedResource
}
// generate
for _, policy := range p.Policies {
if policy.GetSpec().HasGenerate() {
policyContext, err := p.makePolicyContext(jp, cfg, resource, policy, namespaceLabels, gvk, subresource)
if err != nil {
return responses, err
}
generateResponse := eng.ApplyBackgroundChecks(context.TODO(), policyContext)
if !generateResponse.IsEmpty() {
newRuleResponse, err := handleGeneratePolicy(p.Out, p.Store, &generateResponse, *policyContext, p.RuleToCloneSourceResource)
if err != nil {
log.Log.Error(err, "failed to apply generate policy")
} else {
generateResponse.PolicyResponse.Rules = newRuleResponse
}
if err := p.processGenerateResponse(generateResponse, resPath); err != nil {
return responses, err
}
responses = append(responses, generateResponse)
}
p.Rc.addGenerateResponse(generateResponse)
}
}
p.Rc.addEngineResponses(p.AuditWarn, responses...)
return responses, nil
}
func (p *PolicyProcessor) makePolicyContext(
jp jmespath.Interface,
cfg config.Configuration,
resource unstructured.Unstructured,
policy kyvernov1.PolicyInterface,
namespaceLabels map[string]string,
gvk schema.GroupVersionKind,
subresource string,
) (*policycontext.PolicyContext, error) {
operation := kyvernov1.Create
var resourceValues map[string]interface{}
if p.Variables != nil {
kindOnwhichPolicyIsApplied := common.GetKindsFromPolicy(p.Out, policy, p.Variables.Subresources(), p.Client)
vals, err := p.Variables.ComputeVariables(p.Store, policy.GetName(), resource.GetName(), resource.GetKind(), kindOnwhichPolicyIsApplied /*matches...*/)
if err != nil {
return nil, fmt.Errorf("policy `%s` have variables. pass the values for the variables for resource `%s` using set/values_file flag (%w)",
policy.GetName(),
resource.GetName(),
err,
)
}
resourceValues = vals
}
// TODO: this is kind of buggy, we should read that from the json context
switch resourceValues["request.operation"] {
case "DELETE":
operation = kyvernov1.Delete
case "UPDATE":
operation = kyvernov1.Update
}
policyContext, err := engine.NewPolicyContext(
jp,
resource,
operation,
p.UserInfo,
cfg,
)
if err != nil {
log.Log.Error(err, "failed to create policy context")
return nil, fmt.Errorf("failed to create policy context (%w)", err)
}
if operation == kyvernov1.Update {
resource := resource.DeepCopy()
policyContext = policyContext.WithOldResource(*resource)
if err := policyContext.JSONContext().AddOldResource(resource.Object); err != nil {
return nil, fmt.Errorf("failed to update old resource in json context (%w)", err)
}
}
if operation == kyvernov1.Delete {
policyContext = policyContext.WithOldResource(resource)
if err := policyContext.JSONContext().AddOldResource(resource.Object); err != nil {
return nil, fmt.Errorf("failed to update old resource in json context (%w)", err)
}
}
policyContext = policyContext.
WithPolicy(policy).
WithNamespaceLabels(namespaceLabels).
WithResourceKind(gvk, subresource)
for key, value := range resourceValues {
err = policyContext.JSONContext().AddVariable(key, value)
if err != nil {
log.Log.Error(err, "failed to add variable to context", "key", key, "value", value)
return nil, fmt.Errorf("failed to add variable to context %s (%w)", key, err)
}
}
// we need to get the resources back from the context to account for injected variables
switch operation {
case kyvernov1.Create:
ret, err := policyContext.JSONContext().Query("request.object")
if err != nil {
return nil, err
}
if ret == nil {
policyContext = policyContext.WithNewResource(unstructured.Unstructured{})
} else {
object, ok := ret.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("the object retrieved from the json context is not valid")
}
policyContext = policyContext.WithNewResource(unstructured.Unstructured{Object: object})
}
case kyvernov1.Update:
{
ret, err := policyContext.JSONContext().Query("request.object")
if err != nil {
return nil, err
}
if ret == nil {
policyContext = policyContext.WithNewResource(unstructured.Unstructured{})
} else {
object, ok := ret.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("the object retrieved from the json context is not valid")
}
policyContext = policyContext.WithNewResource(unstructured.Unstructured{Object: object})
}
}
{
ret, err := policyContext.JSONContext().Query("request.oldObject")
if err != nil {
return nil, err
}
if ret == nil {
policyContext = policyContext.WithOldResource(unstructured.Unstructured{})
} else {
object, ok := ret.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("the object retrieved from the json context is not valid")
}
policyContext = policyContext.WithOldResource(unstructured.Unstructured{Object: object})
}
}
case kyvernov1.Delete:
ret, err := policyContext.JSONContext().Query("request.oldObject")
if err != nil {
return nil, err
}
if ret == nil {
policyContext = policyContext.WithOldResource(unstructured.Unstructured{})
} else {
object, ok := ret.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("the object retrieved from the json context is not valid")
}
policyContext = policyContext.WithOldResource(unstructured.Unstructured{Object: object})
}
}
return policyContext, nil
}
func (p *PolicyProcessor) processGenerateResponse(response engineapi.EngineResponse, resourcePath string) error {
generatedResources := []*unstructured.Unstructured{}
for _, rule := range response.PolicyResponse.Rules {
gen := rule.GeneratedResources()
generatedResources = append(generatedResources, gen...)
}
for _, r := range generatedResources {
err := p.printOutput(r.Object, response, resourcePath, true)
if err != nil {
return fmt.Errorf("failed to print generate result (%w)", err)
}
fmt.Fprintf(p.Out, "\n\nGenerate:\nGeneration completed successfully.")
}
return nil
}
func (p *PolicyProcessor) processMutateEngineResponse(response engineapi.EngineResponse, resourcePath string) error {
p.Rc.addMutateResponse(response)
err := p.printOutput(response.PatchedResource.Object, response, resourcePath, false)
if err != nil {
return fmt.Errorf("failed to print mutated result (%w)", err)
}
fmt.Fprintf(p.Out, "\n\nMutation:\nMutation has been applied successfully.")
return nil
}
func (p *PolicyProcessor) printOutput(resource interface{}, response engineapi.EngineResponse, resourcePath string, isGenerate bool) error {
yamlEncodedResource, err := yamlv2.Marshal(resource)
if err != nil {
return fmt.Errorf("failed to marshal (%w)", err)
}
var yamlEncodedTargetResources [][]byte
for _, ruleResponese := range response.PolicyResponse.Rules {
patchedTarget, _, _ := ruleResponese.PatchedTarget()
if patchedTarget != nil {
yamlEncodedResource, err := yamlv2.Marshal(patchedTarget.Object)
if err != nil {
return fmt.Errorf("failed to marshal (%w)", err)
}
yamlEncodedResource = append(yamlEncodedResource, []byte("\n---\n")...)
yamlEncodedTargetResources = append(yamlEncodedTargetResources, yamlEncodedResource)
}
}
if p.MutateLogPath == "" {
resource := string(yamlEncodedResource) + string("\n---")
if len(strings.TrimSpace(resource)) > 0 {
if !p.Stdin {
fmt.Fprintf(p.Out, "\npolicy %s applied to %s:", response.Policy().GetName(), resourcePath)
}
fmt.Fprintf(p.Out, "\n"+resource+"\n") //nolint:govet
if len(yamlEncodedTargetResources) > 0 {
fmt.Fprintf(p.Out, "patched targets: \n")
for _, patchedTarget := range yamlEncodedTargetResources {
fmt.Fprintf(p.Out, "\n"+string(patchedTarget)+"\n")
}
}
}
return nil
}
var file *os.File
mutateLogPath := filepath.Clean(p.MutateLogPath)
filename := p.Resource.GetName() + "-mutated"
if isGenerate {
filename = response.Policy().GetName() + "-generated"
}
file, err = os.OpenFile(filepath.Join(mutateLogPath, filename+".yaml"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) // #nosec G304
if err != nil {
return err
}
if !p.MutateLogPathIsDir {
// truncation for the case when mutateLogPath is a file (not a directory) is handled under pkg/kyverno/apply/test_command.go
f, err := os.OpenFile(mutateLogPath, os.O_APPEND|os.O_WRONLY, 0o600) // #nosec G304
if err != nil {
return err
}
file = f
}
if _, err := file.Write([]byte(string(yamlEncodedResource) + "\n---\n\n")); err != nil {
return err
}
for _, patchedTarget := range yamlEncodedTargetResources {
if _, err := file.Write(patchedTarget); err != nil {
return err
}
}
if err := file.Close(); err != nil {
return err
}
return nil
}