
准入控制器可以通过多种方式实现,例如使用Webhook或静态配置文件。准入控制器可以根据Pod的元数据、环境变量、容器镜像等属性进行判断。
准入控制器可以实现多种功能,例如资源配额、网络策略、镜像校验等。准入控制器可以帮助维护集群的稳定性和安全性。
You might enjoy: Comcast Spectacor
What is Admission Control
Admission Control is a mechanism used by the Kubernetes API Server to intercept requests. It allows for validation, modification, and validation of resource objects before they are persisted.
Admission Control is different from authn/authz, which is Kubernetes' authentication and authorization mechanism that runs as a filter and can only access HTTP request headers and certificates, but not the request body. This limits authn/authz to client authentication and authorization, but not to modifying or validating the request object.
Admission Control runs in the API Server's create, read, update, and delete handler, allowing it to naturally operate on API resources. It occurs after authorization and before resource persistence, giving it access to user, URL, and other relevant information, as well as the complete API request.
Admission Control is composed of different plugins, each responsible for checking specific object structures. Some examples include PodNodeSelector, PodSecurityPolicy, and ResourceQuota.
Admission Control is divided into two stages:
- Modification (Mutation) stage: modifies the object's main content and rejects API requests before object persistence.
- Validation stage: validates the object and rejects API requests before object persistence.
A single admission plugin can apply in both stages, but all modifications occur before validations.
Creating a Configuration
To create a configuration for k8s golang 准入控制, you'll need to define the admission control rules in a file. This file will specify the conditions under which admission will be granted or denied.
The configuration file should contain the API groups and resources that you want to control. For example, if you want to control the creation of Pods, you'll need to specify the "apps/v1" API group and the "Pods" resource.
You can also define the admission control plugins to use in your configuration. For instance, you might want to use the "MutatingAdmissionWebhook" plugin to modify the Pod object before it's admitted into the cluster.
You might enjoy: Golang Api Gateway
Creating a Configuration
Creating a Configuration is a crucial step in setting up a system.
Start by defining the purpose of the configuration, as this will help you determine the necessary settings and parameters.
For example, if you're creating a configuration for a network device, you'll need to consider the type of traffic that will be flowing through it.
The configuration process typically involves several stages, including planning, design, and implementation.
A good configuration should be flexible and scalable, allowing for easy modifications and upgrades.
In some cases, you may need to consider factors such as security, reliability, and performance when creating a configuration.
A well-designed configuration can greatly reduce the risk of errors and downtime, saving you time and resources in the long run.
For instance, a configuration that includes redundancy and failover capabilities can help ensure that your system remains available even in the event of a failure.
Creating MutatingConfiguration
Creating MutatingConfiguration is a crucial step in Kubernetes configuration. This can be achieved by creating a MutatingWebhookConfiguration.
A MutatingWebhookConfiguration is created with rules that define when a mutating webhook should be called, in this case, when creating core/v1/pods resource objects. The server address and path are specified through clientConfig.
The mutating webhook is used to add init initContainers to a pod. This is referred to as mutating-pods.
Istio uses ValidatingAdmissionWebhooks to validate Istio configuration and MutatingAdmissionWebhooks to automatically inject sidecar proxies into user pods.
Configuration
Creating a configuration involves defining the relationships between different components.
The first step is to identify the key components involved, such as hardware, software, and firmware.
This can be done by creating a bill of materials, which lists all the necessary parts and their quantities.
For example, a server configuration might require a CPU, memory, and storage.
A configuration file is a text file that contains a set of instructions for the configuration process.
It's typically written in a specific format, such as JSON or YAML, and can be edited manually or automatically generated.
In some cases, the configuration file may include sensitive information, such as passwords or API keys.
This information should be stored securely and not committed to version control.
The configuration file is then used to create a configuration profile, which defines the settings for a specific environment or use case.
This profile can be used to deploy the configuration to multiple devices or systems.
For instance, a configuration profile for a web server might include settings for SSL certificates, firewall rules, and authentication.
Readers also liked: Golang Webserver
Writing and Configuration
You can write a webhook to validate and mutate resources in Kubernetes. The webhook consists of two HTTP endpoints: validate and mutate.
The complete code for the webhook can be found on GitHub, specifically in the repository https://github.com/cnych/admission-webhook-example. This repository is a fork of the original project https://github.com/banzaicloud/admission-webhook-example.
The main logic of the webhook is contained in two files: main.go and webhook.go. The main.go file sets up the HTTP service, while the webhook.go file contains the logic for the validate and mutate webhooks.
To create the HTTP service, you can use standard Go packages, as shown in the main.go file. You can also read TLS configuration from command-line flags.
The serve function in main.go handles incoming HTTP requests for mutate and validating functions. It deserializes the AdmissionReview object from the request, performs some basic content validation, and then calls the corresponding mutate and validate functions based on the URL path.
Take a look at this: Golang Test Main
To determine whether to perform validation, you can ignore certain namespaces or configure it through annotations. For example, you can ignore validation for a specific namespace or configure it to be done based on annotations set on the resource.
The mutate function is similar in code, but it creates a patch to add missing labels to the resource and sets the not_available field to the value of the label.
Deployment and Management
Kubernetes has many built-in Admission Controllers that are useful and necessary, so it's good that they've been implemented.
You can enable and disable these Admission Controllers by using parameters, which is a convenient way to manage them.
There are two special Admission Controllers, MutatingAdmissionWebhook and ValidatingAdmissionWebhook, that don't actually execute policies but provide a way to use custom services with kube-apiserver without needing to recompile or restart it.
These Admission Controllers are dynamic and very handy, making it easy to use custom services.
Discover more: Golang Use Cases
Kubernetes provides a list of all the built-in Admission Controllers in its official documentation, which you can refer to for more information.
You can create a webhook server deployment and service to allow the API server to call it, which is an important step in using custom Admission Controllers.
The MutatingAdmissionWebhook and ValidatingAdmissionWebhook Admission Controllers are especially useful because they provide a way to use custom services without modifying the kube-apiserver.
K8s 中的请求处理流程
Kubernetes API 的请求处理流程是由 kube-apiserver 接收请求并最终持久化到 ETCD 的过程。
API Handler 是主要负责提供服务,接收请求的部分。
FullHandlerChain 是由 DefaultBuildHandlerChain 构建出来的 director 对象,负责初始化请求的处理流程。
如果 goRestfulContainer 的 WebServices 的 RootPath 是 /apis,或者请求前缀与 RootPath 匹配,则进入 Restful 处理链路。
请求处理流程主要包含以下几个部分:
- Mutating Admission -- 指执行可用于变更操作的准入控制器,下文中会
Object Schema Validation -- 对资源对象的 schema 校验。
Validating Admission -- 指执行可用于验证操作的准入控制器,下文中会详细介绍。
ETCD -- ETCD 实现资源的持久化存储。
Kubernetes API 处理请求的过程可以分为以下几个步骤:
1. API Handler 接收请求
2. FullHandlerChain 初始化请求的处理流程
3. Restful 处理链路
4. Mutating Admission
5. Object Schema Validation
6. Validating Admission
7. ETCD 持久化存储
Readers also liked: Golang Rest
Authentication and Authorization
Authentication and Authorization are crucial components of k8s golang 准入控制 (Admission Control).
The Webhook Admission Server verifies its connection with API servers using authentication and authorization mechanisms.
There are three types of connections: from kube-apiserver or extension-apiservers to Admission Webhooks running outside the cluster, from kube-apiserver to Admission Webhooks running inside the cluster, and from extension-apiservers to Admission Webhooks running inside the cluster.
To support these connections, the Webhook Admission plugin can read connection information from the kubeconfig file.
For connections with Admission Webhooks running outside the cluster, manual configuration of the kubeconfig file is required.
For connections with Admission Webhooks running inside the cluster, a well-designed Webhook Admission Server and topology can leverage the built-in security defaults of the Admission plugin, providing a secure, portable, and zero-configuration topology that can run from any API server.
Authentication in k8s supports multiple plugins, including token-based authentication and SSL-based authentication.
Token-based authentication uses a shared secret key, where the server creates a password and the client uses it to login. This is an example of symmetric key authentication.
SSL-based authentication verifies the identity of the server and client, using certificates signed by a trusted Certificate Authority (CA). The client and server must mutually authenticate each other, using certificates that are signed by the same CA.
In k8s, there are two types of accounts: ServiceAccount and UserAccount.
The ServiceAccount is used by pods to connect to the API server, and is represented by the serviceAccountName field in the pod specification.
The UserAccount represents a real person, and is used to login to the k8s cluster.
The UserAccount is identified by a username, which determines the user's permissions and access control.
The ServiceAccount, on the other hand, is a resource that allows pods to call the Kubernetes API or other external services, and is used by the dashboard to authenticate users.
Here is a summary of the authentication methods:
控制器插件
AlwaysAdmit插件允许所有请求通过,而AlwaysDeny则禁止所有请求通过,这两个插件常用于测试环境。
AlwaysPullImages插件在启动容器之前总是下载镜像,这样可以确保每当容器启动前都进行一次用于是否有权使用该容器镜像的检查。
DenyEscalatingExec插件拒绝exec和attach命令到有升级特权的Pod的终端用户访问,这对于限制终端用户在这些容器中执行命令的能力非常有用。
控制器插件包括AlwaysAdmit、AlwaysPullImages、AlwaysDeny、DenyEscalatingExec、ImagePolicyWebhook ServiceAccount、SecurityContextDeny、ResourceQuota、LimitRanger和NamespaceLifecycle等。
Summary and Common Implementations
Kubernetes Admission Controller is a crucial component that ensures the integrity and security of your cluster. By default, some Admission Controllers are already compiled into kube-apiserver as plugins.
Many existing tools can help you complete related tasks, making it unnecessary to develop your own services in some cases.
In the Kubernetes ecosystem, there are many ready-to-use tools that can help with Admission Control. These tools can save you time and effort, and provide a more efficient way to manage your cluster.
You can use Mutating and Validating Admission Controllers to enforce policies and validate user requests.
Here are some common implementations of Admission Controllers:
- Dynamic Admission Controllers
- Admission Webhooks
Admission Webhooks are a specific type of Admission Controller that allows you to validate or mutate incoming requests using a webhook.
Frequently Asked Questions
MutatingWebhookConfiguration 是什么?
MutatingWebhookConfiguration 是 Kubernetes 中一种用于配置动态 Webhook 的资源,用于自动修改资源在创建或更新时。它使得 Kubernetes 能够根据需要动态调整资源配置。
Featured Images: pexels.com


