Created
February 28, 2022 10:36
-
-
Save developer-guy/fe7516b124067fbc0f34658eee7da966 to your computer and use it in GitHub Desktop.
A code sample for storing Kyverno policy on OCI registry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
"github.com/google/go-containerregistry/pkg/authn" | |
"github.com/google/go-containerregistry/pkg/name" | |
"github.com/google/go-containerregistry/pkg/v1/empty" | |
"github.com/google/go-containerregistry/pkg/v1/mutate" | |
"github.com/google/go-containerregistry/pkg/v1/remote" | |
"github.com/google/go-containerregistry/pkg/v1/static" | |
"github.com/google/go-containerregistry/pkg/v1/types" | |
"os" | |
"path/filepath" | |
) | |
const ( | |
kyvernoConfigMediaType = "application/vnd.cncf.kyverno.config.v1+json" | |
kyvernoPolicyLayerMediaType = "application/vnd.cncf.kyverno.policy.layer.v1+yaml" | |
) | |
func main() { | |
if len(os.Args) < 1 { | |
panic(errors.New("you should specify policy path as a first argument and an image as a second argument")) | |
} | |
policyRef := os.Args[1] | |
image := os.Args[2] | |
policyBytes, err := os.ReadFile(filepath.Clean(policyRef)) | |
if err != nil { | |
panic(err) | |
} | |
imageRef, err := name.ParseReference(image) | |
if err != nil { | |
panic(err) | |
} | |
var defaultOptions = []remote.Option{ | |
remote.WithAuthFromKeychain(authn.DefaultKeychain), | |
} | |
fmt.Fprintf(os.Stderr, "Uploading Kyverno policy file [%s] to [%s] with mediaType [%s].\n", policyRef, imageRef.Name(), kyvernoConfigMediaType) | |
base := mutate.MediaType(empty.Image, types.OCIManifestSchema1) | |
base = mutate.ConfigMediaType(base, kyvernoConfigMediaType) | |
layer := static.NewLayer(policyBytes, kyvernoPolicyLayerMediaType) | |
img, err := mutate.Append(base, mutate.Addendum{ | |
Layer: layer, | |
}) | |
if err != nil { | |
panic(err) | |
} | |
err = remote.Write(imageRef, img, defaultOptions...) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Fprintf(os.Stderr, "Kyverno policy file [%s] successfully uploaded to [%s]\n", policyRef, imageRef.Name()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To test this run registy on locally and run the code: