kopts

package module
v0.0.0-...-3c6fb2b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2023 License: Apache-2.0 Imports: 10 Imported by: 0

README

Kopts

Kopts is a package for easier Kubernetes object creation.

Kopts leverages functional options (Kopts is Kubernetes Options) to build the K8s API objects instead of bare structs, in turn drastically cutting down on the boilerplate needed.

For example, to create a deployment you would normally need:

var replicas = int32(1)
deployment := appsv1.Deployment{
    TypeMeta: metav1.TypeMeta{}
    ObjectMeta: metav1.ObjectMeta{
        Name: "mydeployment",
        Namespace: "mynamespace"
    },
    Spec: appsv1.DeploymentSpec{
        Replicas: &replicas,
        Selector: &metav1.LabelSelector{
                MatchLabels: map[string]string{
                        "app": "myapp",
                    },
        },
        Template: corev1.PodTemplateSpec{
            ObjectMeta: metav1.ObjectMeta{
                Name: "mypod",
                Labels: map[string]string{
                    "app": "myapp",
                },
            },       
            Spec: corev1.PodSpec{
                Colntainers: []corev1.Container{
                    {
                        Name: "myapp",
                        Image: "myapp/myapp",
                        ImagePullPolicy: "IfNotPresent",
                        Env: []corev1.EnvVar{
                            {
                                Name: "SERVER_PORT",
                                Value: fmt.Sprintf("%d, 8080),
                            }
                        }
                    }
                }
            }
        },
    },
}

Whereas with kopts all you need is the following:

c := kopts.NewContainer("myapp",
    kopts.ContainerImage("myapp/myapp"),
    kopts.ContainerEnvVar("SERVER_PORT", "8080"),
    kopts.ContainerImagePullPolicy("IfNotPresent"),
)

p := kopts.NewPodSpec("myapp",
    kopts.PodLabel("foo", "bar"),
    kopts.PodContainer(c),
)

d := kopts.NewDeployment("mydeployment",
    kopts.DeploymentNamespace("mynamespace"),
    kopts.DeploymentSelector("app", "myapp"),
    kopts.DeploymentReplicas(1),
    kopts.DeploymentPodSpec(p),
)

Since kopts uses functional options to build all of the API objects, you can also add fields later on. For instance to satisfy conditionals:

d := kopts.NewDeployment("mydeployment",
    kopts.DeploymentNamespace("mynamespace"),
    kopts.DeploymentSelector("app", "myapp"),
    kopts.DeploymentReplicas(1),
    kopts.DeploymentPodSpec(p),
)

if os.Getenv("ENVIRONMENT") == "PROD" {
    f := kopts.DeploymentReplicas(3)
    f(&d)
}

Kopts uses the sigs.k8s.io YAML marshaler. To print out a YAML string just call the MarshalYaml function:

data, err := kopts.MarshalYaml(i)
if err != nil {
	log.Fatal(err)
}

fmt.Print(data)

The marshaler will automatically include the --- at the top of the string to make printing multiple objects easier.

Demo

Demo putting all the pieces together:

More Examples

For more in depth examples take a look at the example.

We will continue to add features

In case there isn't an option for the property you need, you still have access to the underlying K8s struct. You can just reference that object and modify the property directly.

For example imagine that setting a container pull policy wasn't availble yet, you could simply:

c := kopts.NewContainer("myapp",
    kopts.ContainerImage("myapp/myapp"),
    kopts.ContainerEnvVar("SERVER_PORT", "8080"),
)

c.ImagePullPolicy = "Always"

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNameRequired = fmt.Errorf("name is required")

Functions

func MarshalYaml

func MarshalYaml(i interface{}) (string, error)

MarshalYaml returns the YAML for an API object

Types

type ConfigMap

type ConfigMap struct {
	corev1.ConfigMap
}

func NewConfigMap

func NewConfigMap(name string, opts ...ConfigMapOpt) ConfigMap

Returns a configmap with the given name and options

func (*ConfigMap) AsVolumeSource

func (c *ConfigMap) AsVolumeSource() corev1.VolumeSource

Returns the ConfigMap as a volume source

type ConfigMapOpt

type ConfigMapOpt func(*ConfigMap)

func ConfigMapBinaryData

func ConfigMapBinaryData(key string, value []byte) ConfigMapOpt

Set singular binary kv data

func ConfigMapBinaryDataMap

func ConfigMapBinaryDataMap(data map[string][]byte) ConfigMapOpt

Set multiple binary kv data

func ConfigMapData

func ConfigMapData(key, value string) ConfigMapOpt

Set singular configmap kv pair

func ConfigMapDataMap

func ConfigMapDataMap(data map[string]string) ConfigMapOpt

Set multiple configmap kv pairs

func ConfigMapImmutable

func ConfigMapImmutable(b bool) ConfigMapOpt

Set if configmap is immutable

func ConfigMapNamespace

func ConfigMapNamespace(n string) ConfigMapOpt

Set configmap namespace

type Container

type Container struct {
	corev1.Container
}

Container holds a Kubernetes container

func NewContainer

func NewContainer(name string, opts ...ContainerOpt) Container

NewContainer returns a container with the provided namd and any options

type ContainerOpt

type ContainerOpt func(*Container)

func ContainerArgs

func ContainerArgs(args []string) ContainerOpt

Set Container args

func ContainerCommands

func ContainerCommands(commands []string) ContainerOpt

Set container commands

func ContainerEnvFromConfigMap

func ContainerEnvFromConfigMap(configmap, name, key string) ContainerOpt

Add container environment variable from config map

func ContainerEnvFromSecret

func ContainerEnvFromSecret(secret, name, key string) ContainerOpt

Add container environment variable from secret

func ContainerEnvVar

func ContainerEnvVar(key, value string) ContainerOpt

Add container environment variable

func ContainerImage

func ContainerImage(image string) ContainerOpt

Set container image

func ContainerImagePullPolicy

func ContainerImagePullPolicy(policy corev1.PullPolicy) ContainerOpt

Set container pull policy

func ContainerLivenessProbeHTTP

func ContainerLivenessProbeHTTP(h HTTPProbe) ContainerOpt

Add liveness probe

func ContainerPort

func ContainerPort(name string, port int) ContainerOpt

Add Container port

func ContainerVolume

func ContainerVolume(path string, pv PersistentVolume) ContainerOpt

Add container Volume

func ContainerVolumeSource

func ContainerVolumeSource(name, mountPath string, vs corev1.VolumeSource) ContainerOpt

Mount a volume source in the container

type CronJob

type CronJob struct {
	batchv1.CronJob
}

CronJob is a Kubernetes cron job

func NewCronJob

func NewCronJob(name string, opts ...CronJobOpt) *CronJob

NewCronJob returns a cron job with the given name and options

type CronJobOpt

type CronJobOpt func(*CronJob)

func CronJobActiveDeadlineSeconds

func CronJobActiveDeadlineSeconds(i int) CronJobOpt

CronJobActiveDeadlineSeconds sets the active deadline seconds for the cronjob

func CronJobBackoffLimit

func CronJobBackoffLimit(i int) CronJobOpt

CronJobBackoffLimit sets the backoff limit for the cronjob

func CronJobCompletions

func CronJobCompletions(i int) CronJobOpt

CronJobCompletions sets the completions for the cronjob

func CronJobConcurrency

func CronJobConcurrency(p batchv1.ConcurrencyPolicy) CronJobOpt

CronJobConcurrency sets the concurrency for the cronjob

func CronJobNamespace

func CronJobNamespace(n string) CronJobOpt

CronJobNamespace sets the namespace for the cronjob

func CronJobParallelism

func CronJobParallelism(i int) CronJobOpt

CronJobParallelism sets the parallelism for the cronjob

func CronJobPodSpec

func CronJobPodSpec(p PodSpec) CronJobOpt

CronJobPodSpec sets the pod spec for the cronjob

func CronJobRestartPolicy

func CronJobRestartPolicy(r corev1.RestartPolicy) CronJobOpt

CronJobRestartPolicy sets the restart policy for the cronjob

func CronJobSchedule

func CronJobSchedule(cs CronSchedule) CronJobOpt

CronJobSchedule sets the schedule for the cronjob

type CronSchedule

type CronSchedule string

CronSchedule is a cronjob schedule string

const (
	Daily          CronSchedule = "0 0 * * *"
	Hourly         CronSchedule = "0 * * * *"
	Minute         CronSchedule = "* * * * *"
	Weekly         CronSchedule = "0 0 1 * *"
	Monthly        CronSchedule = "0 0 1 1/1 *"
	Yearly         CronSchedule = "0 0 1 1 *"
	Every15Minutes CronSchedule = "*/15 * * * *"
	Every5Minutes  CronSchedule = "*/5 * * * *"
	Every10Minutes CronSchedule = "*/10 * * *"
	EveryHalfHour  CronSchedule = "*/30 * * *"
)

type Deployment

type Deployment struct {
	appsv1.Deployment
}

Deployment holds a Kubernetes deployment

func NewDeployment

func NewDeployment(name string, depOpts ...DeploymentOpt) *Deployment

NewDeployment returns a deployment with the given name and options

type DeploymentOpt

type DeploymentOpt func(*Deployment)

func DeploymentLabel

func DeploymentLabel(key, value string) DeploymentOpt

Add single deployment label

func DeploymentLabels

func DeploymentLabels(labels map[string]string) DeploymentOpt

Add multiple deployment labels

func DeploymentNamespace

func DeploymentNamespace(n string) DeploymentOpt

Set deployment namespace

func DeploymentPodSpec

func DeploymentPodSpec(p PodSpec) DeploymentOpt

Set deployment pod spec

func DeploymentReplicas

func DeploymentReplicas(r int) DeploymentOpt

Set deployment replicas

func DeploymentSelector

func DeploymentSelector(key, value string) DeploymentOpt

Add deployment selector

type HTTPProbe

type HTTPProbe struct {
	Path          string
	Port          int
	InitialDelay  int
	PeriodSeconds int
}

Liveness probe holds the information for a Kubernetes liveness probe

type Ingress

type Ingress struct {
	networkingv1.Ingress
}

Ingress holds a Kubernetes ingress

func NewIngress

func NewIngress(name string, opts ...IngressOpt) Ingress

NewIngress returns an ingress with the given name and options

type IngressOpt

type IngressOpt func(*Ingress)

func IngressClass

func IngressClass(c string) IngressOpt

Set ingress class

func IngressNamespace

func IngressNamespace(n string) IngressOpt

Set ingress namespace

func IngressRule

func IngressRule(r Rule) IngressOpt

Append a rule to paths

type Namespace

type Namespace struct {
	corev1.Namespace
}

Namespace holds a Kubernetes namespace

func NewNamespace

func NewNamespace(name string, opts ...NamespaceOpt) Namespace

NewNamespace returns a namespace with the given name and options

type NamespaceOpt

type NamespaceOpt func(*Namespace)

func NamespaceAnnotation

func NamespaceAnnotation(key, value string) NamespaceOpt

Set single annotation

func NamespaceAnnotations

func NamespaceAnnotations(annotations map[string]string) NamespaceOpt

Set multiple annotations

type Path

type Path struct {
	Name    string
	Service string
	Port    int
	Type    networkingv1.PathType
}

Path holds an ingress path

type PersistentVolume

type PersistentVolume struct {
	corev1.PersistentVolume
}

PersistentVolume holds a Kubernetes persistent volume

func NewPersistentVolume

func NewPersistentVolume(name string, opts ...PersistentVolumeOpt) PersistentVolume

NewPersistentVolume returns a persistent volume with the given name and options

type PersistentVolumeOpt

type PersistentVolumeOpt func(*PersistentVolume)

func PersistentVolumeHostPath

func PersistentVolumeHostPath(path string, pathType corev1.HostPathType) PersistentVolumeOpt

Set the volume host path

func PersistentVolumeLocal

func PersistentVolumeLocal(path string, fsType string) PersistentVolumeOpt

Set the local volume path

func PersistentvolumeCapacity

func PersistentvolumeCapacity(capacity resource.Quantity) PersistentVolumeOpt

Set volume capacity

type PodOpt

type PodOpt func(*PodSpec)

func PodConfigmapAsVolume

func PodConfigmapAsVolume(name string, c ConfigMap) PodOpt

Add a configmap to the volumes

func PodContainer

func PodContainer(c Container) PodOpt

Add a pod container

func PodInitContainer

func PodInitContainer(c Container) PodOpt

Add a pod init container

func PodLabel

func PodLabel(key, value string) PodOpt

Set signle pod label

type PodSpec

type PodSpec struct {
	Name      string
	Namespace string
	Image     string
	Spec      corev1.PodTemplateSpec
}

Podspec holds information for a Kubernetes pod spec

func NewPodSpec

func NewPodSpec(name string, opts ...PodOpt) PodSpec

Returns a pod spec with the given name and options

type PolicyRule

type PolicyRule struct {
	rbacv1.PolicyRule
}

PolicyRule is a Kubernetes policy rule

func NewPolicyRule

func NewPolicyRule(name string, opts ...PolicyRuleOpt) PolicyRule

NewPolicyRule returns a policy rule with the given name and options

type PolicyRuleOpt

type PolicyRuleOpt func(*PolicyRule)

func PolicyRuleAPIGroup

func PolicyRuleAPIGroup(group string) PolicyRuleOpt

Set policy rule API group

func PolicyRuleAPIGroups

func PolicyRuleAPIGroups(groups []string) PolicyRuleOpt

Set multiple rule API groups

func PolicyRuleNonResourceURL

func PolicyRuleNonResourceURL(nru string) PolicyRuleOpt

Set policy rule resource URL

func PolicyRuleNonResourceURLs

func PolicyRuleNonResourceURLs(nru []string) PolicyRuleOpt

Set multiple policy rule resource URLs

func PolicyRuleResource

func PolicyRuleResource(resource string) PolicyRuleOpt

Set policy rule resource

func PolicyRuleResourceName

func PolicyRuleResourceName(rn string) PolicyRuleOpt

Set policy rule resource name

func PolicyRuleResourceNames

func PolicyRuleResourceNames(rn []string) PolicyRuleOpt

Set multiple policy rule resource names

func PolicyRuleResources

func PolicyRuleResources(resources []string) PolicyRuleOpt

Set multiple policy rule resources

func PolicyRuleVerb

func PolicyRuleVerb(v Verb) PolicyRuleOpt

Set policy rule verb

func PolicyRuleVerbs

func PolicyRuleVerbs(verbs []Verb) PolicyRuleOpt

Set multiple rule verbs

type Role

type Role struct {
	rbacv1.Role
}

Role is a Kubernetes role

func NewRole

func NewRole(name string, opts ...RoleOpt) Role

NewRole returns a role with the given name and options

type RoleBinding

type RoleBinding struct {
	rbacv1.RoleBinding
}

RoleBinding is a Kubernetes role binding

func NewRoleBinding

func NewRoleBinding(name string, opts ...RoleBindingOpt) RoleBinding

NewRoleBinding returns a role binding with the given name and options

type RoleBindingOpt

type RoleBindingOpt func(*RoleBinding)

func RoleBindingNamespace

func RoleBindingNamespace(n string) RoleBindingOpt

Set role binding namespace

func RoleBindingRoleRef

func RoleBindingRoleRef(rf rbacv1.RoleRef) RoleBindingOpt

Set role binding roleref

func RoleBindingSubject

func RoleBindingSubject(s rbacv1.Subject) RoleBindingOpt

Set role binding subject

func RoleBindingSubjects

func RoleBindingSubjects(s []rbacv1.Subject) RoleBindingOpt

Set multiple role binding subjects

type RoleOpt

type RoleOpt func(*Role)

func RoleNamespace

func RoleNamespace(n string) RoleOpt

Set role namespace

func RolePolicyRule

func RolePolicyRule(pr PolicyRule) RoleOpt

Set role policy rule

func RolePolicyRules

func RolePolicyRules(pr []PolicyRule) RoleOpt

Set multiple role policy rules

type Rule

type Rule struct {
	Host        string
	Paths       []Path
	LetsEncrypt bool
	TLS         bool
}

Rule holds an ingress rule

type Secret

type Secret struct {
	corev1.Secret
}

Secret holds a Kubernetes secret

func NewSecret

func NewSecret(name string, opts ...SecretOpt) Secret

NewSecret returns a secret with the given name and options

type SecretOpt

type SecretOpt func(*Secret)

func SecretData

func SecretData(key string, value []byte) SecretOpt

Set secret data

func SecretNamespace

func SecretNamespace(n string) SecretOpt

Set secret namespace

type Service

type Service struct {
	corev1.Service
}

Service holds a kubernetes service

func NewService

func NewService(name string, opts ...ServiceOpt) Service

NewService returns a service with the given name and options

type ServiceAccount

type ServiceAccount struct {
	corev1.ServiceAccount
}

ServiceAccount is a Kubernetes service account

func NewServiceAccount

func NewServiceAccount(name string, opts ...ServiceAccountOpt) ServiceAccount

NewSeviceAccount returns a service account with the provided name and options

type ServiceAccountOpt

type ServiceAccountOpt func(*ServiceAccount)

func ServiceAccountAutoMountToken

func ServiceAccountAutoMountToken(b bool) ServiceAccountOpt

ServiceAccountAutoMountToken sets the automounttoken for the service account

func ServiceAccountImagePullSecret

func ServiceAccountImagePullSecret(s string) ServiceAccountOpt

ServiceAccountImagePullSecret sets an image pull secret for the service account

func ServiceAccountImagePullSecrets

func ServiceAccountImagePullSecrets(s []string) ServiceAccountOpt

ServiceAccountImagePullSecrets sets multiple image pull secrets for the service account

func ServiceAccountNamespace

func ServiceAccountNamespace(n string) ServiceAccountOpt

ServiceAccountNamespace sets the namespace for the service account

type ServiceOpt

type ServiceOpt func(*Service)

func ServiceNamespace

func ServiceNamespace(n string) ServiceOpt

Set service namespace

func ServicePort

func ServicePort(port, targetPort int) ServiceOpt

Add service port

func ServiceSelector

func ServiceSelector(key, value string) ServiceOpt

Set service selector

type Verb

type Verb string
const (
	Create           Verb = "create"
	Delete           Verb = "delete"
	Deletecollection Verb = "deletecollection"
	Get              Verb = "get"
	List             Verb = "list"
	Patch            Verb = "patch"
	Update           Verb = "update"
	Watch            Verb = "watch"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL