Note. transl.: Operators are utility software for Kubernetes designed to automate the execution of routine actions on cluster objects upon certain events. We have already written about operators in
I decided to write this post with a real life example after my attempts to find documentation on creating an operator for Kubernetes, went through the study of the code.
The example that will be described is this: in our Kubernetes cluster, each Namespace
represents a team's sandbox environment, and we wanted to restrict access to them so that teams can only play in their own sandboxes.
You can achieve what you want by assigning a user to a group that has RoleBinding
to specific Namespace
ΠΈ ClusterRole
with editing rights. The YAML representation will look like this:
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: kubernetes-team-1
namespace: team-1
subjects:
- kind: Group
name: kubernetes-team-1
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: edit
apiGroup: rbac.authorization.k8s.io
(
Create such RoleBinding
you can do it manually, but once you get over a hundred namespaces, it becomes a tedious task. This is where Kubernetes operators come in handy - they allow you to automate the creation of Kubernetes resources based on changes in resources. In our case, we want to create RoleBinding
while creating Namespace
.
First of all, let's define the function main
, which does the required setup to run the statement and then invokes the statement action:
(Note. transl.: hereinafter, the comments in the code are translated into Russian. In addition, the indentation is corrected for spaces instead of [recommended in Go] tabs solely for the purpose of better readability within the framework of Habr's layout. After each listing, there are links to the original on GitHub, where English-language comments and tabs are saved.)
func main() {
// Π£ΡΡΠ°Π½Π°Π²Π»ΠΈΠ²Π°Π΅ΠΌ Π²ΡΠ²ΠΎΠ΄ Π»ΠΎΠ³ΠΎΠ² Π² ΠΊΠΎΠ½ΡΠΎΠ»ΡΠ½ΡΠΉ STDOUT
log.SetOutput(os.Stdout)
sigs := make(chan os.Signal, 1) // Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ ΠΊΠ°Π½Π°Π» Π΄Π»Ρ ΠΏΠΎΠ»ΡΡΠ΅Π½ΠΈΡ ΡΠΈΠ³Π½Π°Π»ΠΎΠ² ΠΠ‘
stop := make(chan struct{}) // Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ ΠΊΠ°Π½Π°Π» Π΄Π»Ρ ΠΏΠΎΠ»ΡΡΠ΅Π½ΠΈΡ ΡΡΠΎΠΏ-ΡΠΈΠ³Π½Π°Π»Π°
// Π Π΅Π³ΠΈΡΡΡΠΈΡΡΠ΅ΠΌ ΠΏΠΎΠ»ΡΡΠ΅Π½ΠΈΠ΅ SIGTERM Π² ΠΊΠ°Π½Π°Π»Π΅ sigs
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
// Goroutines ΠΌΠΎΠ³ΡΡ ΡΠ°ΠΌΠΈ Π΄ΠΎΠ±Π°Π²Π»ΡΡΡ ΡΠ΅Π±Ρ Π² WaitGroup,
// ΡΡΠΎΠ±Ρ Π·Π°Π²Π΅ΡΡΠ΅Π½ΠΈΡ ΠΈΡ
Π²ΡΠΏΠΎΠ»Π½Π΅Π½ΠΈΡ Π΄ΠΎΠΆΠΈΠ΄Π°Π»ΠΈΡΡ
wg := &sync.WaitGroup{}
runOutsideCluster := flag.Bool("run-outside-cluster", false, "Set this flag when running outside of the cluster.")
flag.Parse()
// Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ clientset Π΄Π»Ρ Π²Π·Π°ΠΈΠΌΠΎΠ΄Π΅ΠΉΡΡΠ²ΠΈΡ Ρ ΠΊΠ»Π°ΡΡΠ΅ΡΠΎΠΌ Kubernetes
clientset, err := newClientSet(*runOutsideCluster)
if err != nil {
panic(err.Error())
}
controller.NewNamespaceController(clientset).Run(stop, wg)
<-sigs // ΠΠ΄Π΅ΠΌ ΡΠΈΠ³Π½Π°Π»ΠΎΠ² (Π΄ΠΎ ΠΏΠΎΠ»ΡΡΠ΅Π½ΠΈΡ ΡΠΈΠ³Π½Π°Π»Π° Π±ΠΎΠ»Π΅Π΅ Π½ΠΈΡΠ΅Π³ΠΎ Π½Π΅ ΠΏΡΠΎΠΈΡΡ
ΠΎΠ΄ΠΈΡ)
log.Printf("Shutting down...")
close(stop) // ΠΠΎΠ²ΠΎΡΠΈΠΌ goroutines ΠΎΡΡΠ°Π½ΠΎΠ²ΠΈΡΡΡΡ
wg.Wait() // ΠΠΆΠΈΠ΄Π°Π΅ΠΌ, ΡΡΠΎ Π²ΡΠ΅ ΠΎΡΡΠ°Π½ΠΎΠ²Π»Π΅Π½ΠΎ
}
We do the following:
- We set up a handler for specific operating system signals to cause the operator to gracefully exit.
- Use
WaitGroup
to gracefully stop all goroutines before the application terminates. - We provide access to the cluster by creating
clientset
. - Run
NamespaceController
, in which all our logic will be located.
Now we need a basis for logic, and in our case it is the mentioned NamespaceController
:
// NamespaceController ΡΠ»Π΅Π΄ΠΈΡ ΡΠ΅ΡΠ΅Π· Kubernetes API Π·Π° ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΡΠΌΠΈ
// Π² ΠΏΡΠΎΡΡΡΠ°Π½ΡΡΠ²Π°Ρ
ΠΈΠΌΠ΅Π½ ΠΈ ΡΠΎΠ·Π΄Π°Π΅Ρ RoleBinding Π΄Π»Ρ ΠΊΠΎΠ½ΠΊΡΠ΅ΡΠ½ΠΎΠ³ΠΎ namespace.
type NamespaceController struct {
namespaceInformer cache.SharedIndexInformer
kclient *kubernetes.Clientset
}
// NewNamespaceController ΡΠΎΠ·Π΄Π°Π΅Ρ Π½ΠΎΠ²ΡΠΉ NewNamespaceController
func NewNamespaceController(kclient *kubernetes.Clientset) *NamespaceController {
namespaceWatcher := &NamespaceController{}
// Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ ΠΈΠ½ΡΠΎΡΠΌΠ΅Ρ Π΄Π»Ρ ΡΠ»Π΅ΠΆΠ΅Π½ΠΈΡ Π·Π° Namespaces
namespaceInformer := cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
return kclient.Core().Namespaces().List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return kclient.Core().Namespaces().Watch(options)
},
},
&v1.Namespace{},
3*time.Minute,
cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
)
namespaceInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: namespaceWatcher.createRoleBinding,
})
namespaceWatcher.kclient = kclient
namespaceWatcher.namespaceInformer = namespaceInformer
return namespaceWatcher
}
(
Here we are setting SharedIndexInformer
, which will efficiently (using the cache) wait for namespace changes (read more about informers in the article "EventHandler
to the informer, thanks to which, when adding a namespace (Namespace
) the function is called createRoleBinding
.
The next step is to define this function createRoleBinding
:
func (c *NamespaceController) createRoleBinding(obj interface{}) {
namespaceObj := obj.(*v1.Namespace)
namespaceName := namespaceObj.Name
roleBinding := &v1beta1.RoleBinding{
TypeMeta: metav1.TypeMeta{
Kind: "RoleBinding",
APIVersion: "rbac.authorization.k8s.io/v1beta1",
},
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("ad-kubernetes-%s", namespaceName),
Namespace: namespaceName,
},
Subjects: []v1beta1.Subject{
v1beta1.Subject{
Kind: "Group",
Name: fmt.Sprintf("ad-kubernetes-%s", namespaceName),
},
},
RoleRef: v1beta1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: "edit",
},
}
_, err := c.kclient.Rbac().RoleBindings(namespaceName).Create(roleBinding)
if err != nil {
log.Println(fmt.Sprintf("Failed to create Role Binding: %s", err.Error()))
} else {
log.Println(fmt.Sprintf("Created AD RoleBinding for Namespace: %s", roleBinding.Name))
}
}
(
We get the namespace as obj
and convert it to an object Namespace
. Then we define RoleBinding
, based on the YAML file mentioned at the beginning, using the provided object Namespace
and creating RoleBinding
. Finally, we log whether the creation was successful.
The last function to be defined is β Run
:
// Run Π·Π°ΠΏΡΡΠΊΠ°Π΅Ρ ΠΏΡΠΎΡΠ΅ΡΡ ΠΎΠΆΠΈΠ΄Π°Π½ΠΈΡ ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΠΉ Π² ΠΏΡΠΎΡΡΡΠ°Π½ΡΡΠ²Π°Ρ
ΠΈΠΌΡΠ½
// ΠΈ Π΄Π΅ΠΉΡΡΠ²ΠΈΡ Π² ΡΠΎΠΎΡΠ²Π΅ΡΡΡΠ²ΠΈΠΈ Ρ ΡΡΠΈΠΌΠΈ ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΡΠΌΠΈ.
func (c *NamespaceController) Run(stopCh <-chan struct{}, wg *sync.WaitGroup) {
// ΠΠΎΠ³Π΄Π° ΡΡΠ° ΡΡΠ½ΠΊΡΠΈΡ Π·Π°Π²Π΅ΡΡΠ΅Π½Π°, ΠΏΠΎΠΌΠ΅ΡΠΈΠΌ ΠΊΠ°ΠΊ Π²ΡΠΏΠΎΠ»Π½Π΅Π½Π½ΡΡ
defer wg.Done()
// ΠΠ½ΠΊΡΠ΅ΠΌΠ΅Π½ΡΠΈΡΡΠ΅ΠΌ wait group, Ρ.ΠΊ. ΡΠΎΠ±ΠΈΡΠ°Π΅ΠΌΡΡ Π²ΡΠ·Π²Π°ΡΡ goroutine
wg.Add(1)
// ΠΡΠ·ΡΠ²Π°Π΅ΠΌ goroutine
go c.namespaceInformer.Run(stopCh)
// ΠΠΆΠΈΠ΄Π°Π΅ΠΌ ΠΏΠΎΠ»ΡΡΠ΅Π½ΠΈΡ ΡΡΠΎΠΏ-ΡΠΈΠ³Π½Π°Π»Π°
<-stopCh
}
(
Here we are talking WaitGroup
that we start the goroutine and then call namespaceInformer
which has been previously defined. When a stop signal comes in, it will end the function, inform WaitGroup
, which is no longer executing, and this function will exit.
Information about building and running this statement on a Kubernetes cluster can be found at
On this statement, which creates RoleBinding
upon appearance Namespace
in a Kubernetes cluster, ready.
Source: habr.com