2022-01-17 在pod内部操作k8s
目录摘要:使用模块:例子:说明:pod的接口:摘要:因为某些业务需要在pod内部直接操作k8s, 本文记录如何处理.使用模块:client-go标准接口:https://github.com/kubernetes/client-go例子:在pod内访问k8s:https://github.com/kubernetes/client-go/tree/master/examples/in-cluste
·
目录
摘要:
因为某些业务需要在pod内部直接操作k8s, 本文记录如何处理.
使用模块:
client-go标准接口:
https://github.com/kubernetes/client-go
例子:
在pod内访问k8s:
https://github.com/kubernetes/client-go/tree/master/examples/in-cluster-client-configuration
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Note: the example only works with the code within the same release/branch.
package main
import (
"context"
"fmt"
"time"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
//
// Uncomment to load all auth plugins
// _ "k8s.io/client-go/plugin/pkg/client/auth"
//
// Or uncomment to load specific auth plugins
// _ "k8s.io/client-go/plugin/pkg/client/auth/azure"
// _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
// _ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
// _ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
)
func main() {
// creates the in-cluster config
config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
for {
// get pods in all the namespaces by omitting namespace
// Or specify namespace to get pods in particular namespace
pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
// Examples for error handling:
// - Use helper functions e.g. errors.IsNotFound()
// - And/or cast to StatusError and use its properties like e.g. ErrStatus.Message
_, err = clientset.CoreV1().Pods("default").Get(context.TODO(), "example-xxxxx", metav1.GetOptions{})
if errors.IsNotFound(err) {
fmt.Printf("Pod example-xxxxx not found in default namespace\n")
} else if statusError, isStatus := err.(*errors.StatusError); isStatus {
fmt.Printf("Error getting pod %v\n", statusError.ErrStatus.Message)
} else if err != nil {
panic(err.Error())
} else {
fmt.Printf("Found example-xxxxx pod in default namespace\n")
}
time.Sleep(10 * time.Second)
}
}
说明:
# Authenticating inside the cluster
This example shows you how to configure a client with client-go to authenticate
to the Kubernetes API from an application running inside the Kubernetes cluster.
client-go uses the [Service Account token][sa] mounted inside the Pod at the
`/var/run/secrets/kubernetes.io/serviceaccount` path when the
`rest.InClusterConfig()` is used.
## Running this example
First compile the application for Linux:
cd in-cluster-client-configuration
GOOS=linux go build -o ./app .
Then package it to a docker image using the provided Dockerfile to run it on
Kubernetes.
If you are running a [Minikube][mk] cluster, you can build this image directly
on the Docker engine of the Minikube node without pushing it to a registry. To
build the image on Minikube:
eval $(minikube docker-env)
docker build -t in-cluster .
If you are not using Minikube, you should build this image and push it to a registry
that your Kubernetes cluster can pull from.
If you have RBAC enabled on your cluster, use the following
snippet to create role binding which will grant the default service account view
permissions.
```
kubectl create clusterrolebinding default-view --clusterrole=view --serviceaccount=default:default
```
Then, run the image in a Pod with a single instance Deployment:
kubectl run --rm -i demo --image=in-cluster
There are 4 pods in the cluster
There are 4 pods in the cluster
There are 4 pods in the cluster
...
The example now runs on Kubernetes API and successfully queries the number of
pods in the cluster every 10 seconds.
### Clean up
To stop this example and clean up the pod, press <kbd>Ctrl</kbd>+<kbd>C</kbd> on
the `kubectl run` command and then run:
kubectl delete deployment demo
[sa]: https://kubernetes.io/docs/admin/authentication/#service-account-tokens
[mk]: https://kubernetes.io/docs/getting-started-guides/minikube/
pod的接口:
// PodInterface has methods to work with Pod resources.
type PodInterface interface {
Create(ctx context.Context, pod *v1.Pod, opts metav1.CreateOptions) (*v1.Pod, error)
Update(ctx context.Context, pod *v1.Pod, opts metav1.UpdateOptions) (*v1.Pod, error)
UpdateStatus(ctx context.Context, pod *v1.Pod, opts metav1.UpdateOptions) (*v1.Pod, error)
Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error
DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error
Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.Pod, error)
List(ctx context.Context, opts metav1.ListOptions) (*v1.PodList, error)
Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)
Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Pod, err error)
Apply(ctx context.Context, pod *corev1.PodApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Pod, err error)
ApplyStatus(ctx context.Context, pod *corev1.PodApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Pod, err error)
UpdateEphemeralContainers(ctx context.Context, podName string, pod *v1.Pod, opts metav1.UpdateOptions) (*v1.Pod, error)
PodExpansion
}
测试删除pod:
原理: 熟悉又陌生的 k8s 字段:finalizers - 伪架构师的个人空间 - OSCHINA - 中文开源技术交流社区
kubectl -n ns-init-redis delete pvc init-redis-cluster-data-init-redis-cluster-0
kubectl -n ns-init-redis delete pvc init-redis-cluster-data-init-redis-cluster-0 --force
kubectl -n ns-init-redis patch pvc init-redis-cluster-data-init-redis-cluster-0 -p '{"metadata":{"finalizers":null}}'
kubectl delete pv init-redis-cluster-data-ns-init-redis-init-redis-cluster-pv-0 --force
kubectl delete pv init-redis-cluster-data-paas-init-redis-cluster-pv-0 --force
kubectl -n ns-init-redis patch pv init-redis-cluster-data-paas-init-redis-cluster-pv-0 -p '{"metadata":{"finalizers":null}}'
更多推荐
已为社区贡献9条内容
所有评论(0)