pod 通过 serviceAccount 访问 ApiServer
pod 通过 serviceAccount 访问 k8s Apiserver
·
Service Account(服务账号):是指由Kubernetes API 管理的账号,用于为Pod 之中的服务进程在访问Kubernetes API时提供身份标识( identity ) 。Service Account通常要绑定于特定的命名空间,它们由 API Server 创建,或者通过 API 调用于动创建 ,附带着一组存储为Secret的用于访问API Server的凭据。
以下步骤基于最简单场景:pod 内容器访问apiserver操作pod。
依赖:client-go
步骤:
1、创建serviceaccount
yaml文件 sa.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: example-sa # serviceAccount名
namespace: default # 所属命名空间
kubectl apply -f sa.yaml
2、创建role
role 即一个account能够访问的权限
role.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: example-role
namespace: default
rules:
- apiGroups:
- ''
resources: # 能够访问的资源
- 'pods'
verbs: # 能够执行的动作
- 'create'
- 'delete'
- 'get'
- 'list'
- 'patch'
kubectl apply -f role.yaml
3、创建roleBinding
使用 roleBinding 将 serviceAccount 与 role 进行绑定
roleBinding.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: example-rolebind
namespace: default
subjects:
- kind: ServiceAccount
name: example-kubeconfig
namespace: default
roleRef:
kind: Role
name: example-role
apiGroup: rbac.authorization.k8s.io
kubectl apply -f roleBinding.yaml
4、 pod 内使用创建的 serviceAccount
pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: example
namespace: default
spec:
serviceAccount: example-sa
initContainers: # 省略
kubectl apply -f pod.yaml
5、编写测试程序
// 部分代码
kubeconfig, err := rest.InClusterConfig()
if err != nil {
log.Println(err)
return nil
}
clientset, err := kubernetes.NewForConfig(kubeconfig)
if err != nil {
log.Println(err)
return nil
}
InClusterConfig
方法会获取当前环境下的pod绑定的service account信息,并生成配置。 NewForConfig
根据配置初始化apiserver client。可通过该client去操作pod。
6、将程序放入pod中执行。
End
更多推荐
已为社区贡献2条内容
所有评论(0)