Ejemplo de un k8s custom controller para un CRD nuevo

Clonado de kubernetes/sample-controller

Para pruebas de un CRD nuevo

This repository implements a simple controller for watching Foo resources as defined with a CustomResourceDefinition (CRD).

Note: go-get or vendor this package as k8s.io/sample-controller.

This particular example demonstrates how to perform basic operations such as:

  • How to register a new custom resource (custom resource type) of type Foo using a CustomResourceDefinition.
  • How to create/get/list instances of your new resource type Foo.
  • How to setup a controller on resource handling create/update/delete events.

It makes use of the generators in k8s.io/code-generator to generate a typed client, informers, listers and deep-copy functions. You can do this yourself using the ./hack/update-codegen.sh script.

The update-codegen script will automatically generate the following files & directories:

  • pkg/apis/samplecontroller/v1alpha1/zz_generated.deepcopy.go
  • pkg/generated/

Changes should not be made to these files manually, and when creating your own controller based off of this implementation you should not copy these files and instead run the update-codegen script to generate your own.

Details

The sample controller uses client-go library extensively. The details of interaction points of the sample controller with various mechanisms from this library are explained here.

Fetch sample-controller and its dependencies

Like the rest of Kubernetes, sample-controller has used godep and $GOPATH for years and is now adopting go 1.11 modules. There are thus two alternative ways to go about fetching this demo and its dependencies.

Fetch with godep

When NOT using go 1.11 modules, you can use the following commands.

go get -d k8s.io/sample-controller
cd $GOPATH/src/k8s.io/sample-controller
godep restore

When using go 1.11 modules

When using go 1.11 modules (GO111MODULE=on), issue the following commands --- starting in whatever working directory you like.

git clone https://github.com/kubernetes/sample-controller.git
cd sample-controller

Note, however, that if you intend to generate code then you will also need the code-generator repo to exist in an old-style location. One easy way to do this is to use the command go mod vendor to create and populate the vendor directory.

A Note on kubernetes/kubernetes

If you are developing Kubernetes according to https://github.com/kubernetes/community/blob/master/contributors/guide/github-workflow.md then you already have a copy of this demo in kubernetes/staging/src/k8s.io/sample-controller and its dependencies --- including the code generator --- are in usable locations (valid for all Go versions).

Purpose

This is an example of how to build a kube-like controller with a single type.

Running

Prerequisite: Since the sample-controller uses apps/v1 deployments, the Kubernetes cluster version should be greater than 1.9.

# assumes you have a working kubeconfig, not required if operating in-cluster
go build -o sample-controller .
./sample-controller -kubeconfig=$HOME/.kube/config

# create a CustomResourceDefinition
kubectl create -f artifacts/examples/crd.yaml

# create a custom resource of type Foo
kubectl create -f artifacts/examples/example-foo.yaml

# check deployments created through the custom resource
kubectl get deployments

Use Cases

CustomResourceDefinitions can be used to implement custom resource types for your Kubernetes cluster. These act like most other Resources in Kubernetes, and may be kubectl apply'd, etc.

Some example use cases:

  • Provisioning/Management of external datastores/databases (eg. CloudSQL/RDS instances)
  • Higher level abstractions around Kubernetes primitives (eg. a single Resource to define an etcd cluster, backed by a Service and a ReplicationController)

Defining types

Each instance of your custom resource has an attached Spec, which should be defined via a struct{} to provide data format validation. In practice, this Spec is arbitrary key-value data that specifies the configuration/behavior of your Resource.

For example, if you were implementing a custom resource for a Database, you might provide a DatabaseSpec like the following:

type DatabaseSpec struct {
	Databases []string `json:"databases"`
	Users     []User   `json:"users"`
	Version   string   `json:"version"`
}

type User struct {
	Name     string `json:"name"`
	Password string `json:"password"`
}

Validation

To validate custom resources, use the CustomResourceValidation feature. Validation in the form of a structured schema is mandatory to be provided for apiextensions.k8s.io/v1.

Example

The schema in crd.yaml applies the following validation on the custom resource: spec.replicas must be an integer and must have a minimum value of 1 and a maximum value of 10.

Subresources

Custom Resources support /status and /scale subresources. The CustomResourceSubresources feature is in GA from v1.16.

Example

The CRD in crd-status-subresource.yaml enables the /status subresource for custom resources. This means that UpdateStatus can be used by the controller to update only the status part of the custom resource.

To understand why only the status part of the custom resource should be updated, please refer to the Kubernetes API conventions.

In the above steps, use crd-status-subresource.yaml to create the CRD:

# create a CustomResourceDefinition supporting the status subresource
kubectl create -f artifacts/examples/crd-status-subresource.yaml

A Note on the API version

The group version of the custom resource in crd.yaml is v1alpha, this can be evolved to a stable API version, v1, using CRD Versioning.

Cleanup

You can clean up the created CustomResourceDefinition with:

kubectl delete crd foos.samplecontroller.k8s.io

Compatibility

HEAD of this repository will match HEAD of k8s.io/apimachinery and k8s.io/client-go.

Where does it come from?

sample-controller is synced from https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/sample-controller. Code changes are made in that location, merged into k8s.io/kubernetes and later synced here.

Similar Resources

Controller-check - Run checks against K8s controllers to verify if they meets certain conventions

controller-check Run checks against K8s controllers to verify if they meets cert

Jan 4, 2022

K8s-delete-protection - Kubernetes admission controller to avoid deleteing master nodes

k8s-delete-protection Admission Controller If you want to make your Kubernetes c

Nov 2, 2022

K8s-cinder-csi-plugin - K8s Pod Use Openstack Cinder Volume

k8s-cinder-csi-plugin K8s Pod Use Openstack Cinder Volume openstack volume list

Jul 18, 2022

K8s-ingress-health-bot - A K8s Ingress Health Bot is a lightweight application to check the health of the ingress endpoints for a given kubernetes namespace.

k8s-ingress-health-bot A K8s Ingress Health Bot is a lightweight application to check the health of qualified ingress endpoints for a given kubernetes

Jan 2, 2022

K8s-go-structs - All k8s API Go structs

k8s-api go types Why? Its nice to have it all in a single package. . |-- pkg |

Jul 17, 2022

Repositório para a aula sobre integração do containerd com Golang

Repositório para a aula sobre integração do containerd com Golang

Integrando containers nativamente usando Golang Este é o código finalizado da aplicação Já pensou em uma alternativa ao Docker? Que tal manipular cont

May 4, 2021

repo de teste para executar á pipeline do rancher

pipeline-example-go This is a sample golang project to demonstrate the integration with rancher pipeline. Building go build -o ./bin/hello-server Runn

Dec 19, 2021

Repositório destinado para acompanhar meu aprendizado na linguagem Go, desde o básico "Hello, World!" até a elaboração de um projeto ainda não definido. 🙂

go-basics Repositório destinado para acompanhar meu aprendizado na linguagem Go, desde o básico "Hello, World!" até a elaboração de um projeto ainda n

Jan 7, 2022

Pacote de integração para utilizar dynamo com lambda

Dynamo for lambda Pacote criado para utilizar o dynamo db com lambda functions Para rodar o projeto Certifique-se de ter instalado Docker e docker-com

Jan 11, 2022
A Controller written in kubernetes sample-controller style which watches a custom resource named Bookstore

bookstore-sample-controller A Controller written in kubernetes sample-controller style which watches a custom resource named Bookstore. A resource cre

Jan 20, 2022
Write controller-runtime based k8s controllers that read/write to git, not k8s

Git Backed Controller The basic idea is to write a k8s controller that runs against git and not k8s apiserver. So the controller is reading and writin

Dec 10, 2021
Helm Operator is designed to managed the full lifecycle of Helm charts with Kubernetes CRD resource.

Helm Operator Helm Operator is designed to install and manage Helm charts with Kubernetes CRD resource. Helm Operator does not create the Helm release

Aug 25, 2022
Lightweight, CRD based envoy control plane for kubernetes

Lighweight, CRD based Envoy control plane for Kubernetes: Implemented as a Kubernetes Operator Deploy and manage an Envoy xDS server using the Discove

Nov 3, 2022
VaultOperator provides a CRD to interact securely and indirectly with secrets stored in Hashicorp Vault.

vault-operator The vault-operator provides several CRDs to interact securely and indirectly with secrets. Details Currently only stage 1 is implemente

Mar 12, 2022
Image clone controller is a kubernetes controller to safe guard against the risk of container images disappearing

Image clone controller image clone controller is a kubernetes controller to safe guard against the risk of container images disappearing from public r

Oct 10, 2021
A controller to create K8s Ingresses for Openshift routes.

route-to-ingress-operator A controller to create corresponding ingress.networking.k8s.io/v1 resources for route.openshift.io/v1 TODO int port string p

Jan 7, 2022
The k8s-generic-webhook is a library to simplify the implementation of webhooks for arbitrary customer resources (CR) in the operator-sdk or controller-runtime.

k8s-generic-webhook The k8s-generic-webhook is a library to simplify the implementation of webhooks for arbitrary customer resources (CR) in the opera

Nov 24, 2022
K8s controller implementing Multi-Cluster Services API based on AWS Cloud Map.

AWS Cloud Map MCS Controller for K8s Introduction AWS Cloud Map multi-cluster service discovery for Kubernetes (K8s) is a controller that implements e

Dec 17, 2022
K8S ConfigMap Merging Controller

ConfigMap Merging Controller (cmmc) cmmc is a k8s operator that allows for the merging of ConfigMap resources with data validation. Why? The impetus f

Oct 2, 2022