Skip to content

Instantly share code, notes, and snippets.

@developer-guy
Created February 28, 2022 10:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save developer-guy/fe7516b124067fbc0f34658eee7da966 to your computer and use it in GitHub Desktop.
Save developer-guy/fe7516b124067fbc0f34658eee7da966 to your computer and use it in GitHub Desktop.
A code sample for storing Kyverno policy on OCI registry
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())
}
@developer-guy
Copy link
Author

To test this run registy on locally and run the code:

https://raw.githubusercontent.com/kyverno/policies/main/pod-security/baseline/disallow-capabilities/disallow-capabilities.yaml

$  docker container run -d -p 5000:5000 --restart=always --name registry registry:2
$ go run ./main.go disallow-capabilities.yaml localhost:5000/disallow-capabilities:latest
Uploading Kyverno policy file [disallow-capabilities.yaml] to [localhost:5000/disallow-capabilities:latest] with mediaType [application/vnd.cncf.kyverno.config.v1+json].
Kyverno policy file [disallow-capabilities.yaml] successfully uploaded to [localhost:5000/disallow-capabilities:latest]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment