当创建 pod 的时候,如果没有指定一个 service account,系统会自动得在与该pod 相同的 namespace 下为其指派一个default service account。如果获取刚创建的 pod 的原始 json 或 yaml 信息(例如使用kubectl get pods podename -o yaml命令),将看到spec.serviceAccountName字段已经被设置为 default。
1 2 3 4 5 6 7 8 9 10
[root@k8s-master ~]# kubectl get pods NAME READY STATUS RESTARTS AGE filebeat-ds-hxgdx 1/1 Running 134d filebeat-ds-s466l 1/1 Running 234d myapp-01/1 Running 03h myapp-11/1 Running 03h myapp-21/1 Running 04h myapp-31/1 Running 04h pod-vol-demo 2/2 Running 02d redis-5b5d6fbbbd-q8ppz 1/1 Running 12d
1 2 3 4 5 6 7 8 9 10 11 12 13
[root@k8s-master~]# kubectl get pods/myapp-0 -o yaml |grep "serviceAccountName" serviceAccountName:default
从上面可以看到每个Pod无论定义与否都会有个存储卷,这个存储卷为default-token-*** token令牌,这就是service account是为Pod中的进程与apiserver联系提供身份认证信息。通过secret进行定义,由于认证信息属于敏感信息,所以需要保存在secret资源当中,并以存储卷的方式挂载到Pod当中。从而让Pod内运行的应用通过对应的secret中的service account来连接apiserver,并完成认证。每个 namespace 中都有一个默认的叫做 default 的 service account资源。可以使用kubectl get secret命令当前名称空间内的secret,也可以看到对应的default-token。可以使用的预制认证信息让当前名称空间中所有的pod连接至apiserver,从而保证pod与apiserver之间的通信。
1 2 3
[root@k8s-master ~]# kubectl get sa NAME SECRETS AGE default150d
1 2 3 4
[root@k8s-master~]# kubectl get sa -n ingress-nginx #前期创建的ingress-nginx名称空间也存在这样的serviceaccount NAME SECRETS AGE default 111d nginx-ingress-serviceaccount 111d
1 2 3 4 5
[root@k8s-master ~]# kubectl get secret NAMETYPE DATA AGE default-token-j5pf5 kubernetes.io/service-account-token 350d mysecret Opaque21d tomcat-ingress-secret kubernetes.io/tls 210d
1 2 3 4
[root@k8s-master ~]# kubectl get secret -n ingress-nginx NAME TYPE DATA AGE default-token-zl49j kubernetes.io/service-account-token 3 11d nginx-ingress-serviceaccount-token-mcsf4 kubernetes.io/service-account-token 3 11d
而默认的service account 仅仅只能获取当前Pod自身的相关属性,无法观察到其他名称空间Pod的相关属性信息。如果想要扩展Pod,假设有一个Pod需要用于管理其他Pod或者是其他资源对象(例如dashboard),是无法通过自身的名称空间的default service account进行获取其他Pod的相关属性信息的,此时就需要进行手动创建一个serviceaccount,并在创建Pod时进行定义。那么serviceaccount该如何进行定义呢???实际上,service accout也属于一个k8s资源,如下查看service account的定义方式:
[root@k8s-master ~]# kubectl explain sa KIND: ServiceAccount VERSION: v1
DESCRIPTION: ServiceAccount binds together: * a name, understood by users, and perhaps by peripheral systems, for an identity * a principal that can be authenticated and authorized * a set of secrets
FIELDS: apiVersion <string> APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
automountServiceAccountToken <boolean> AutomountServiceAccountToken indicates whether pods running as this service account should have an API token automatically mounted. Can be overridden at the pod level.
imagePullSecrets <[]Object> ImagePullSecrets is a list of references to secrets in the same namespace tousefor pulling any images in pods that reference this ServiceAccount. ImagePullSecrets are distinctfrom Secrets because Secrets can be mounted in the pod, but ImagePullSecrets are only accessed by the kubelet. More info: https://kubernetes.io/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod
kind <string> Kind is a stringvalue representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
metadata <Object> Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
secrets <[]Object> Secrets is the list of secrets allowed to be used by pods running using this ServiceAccount. More info: https://kubernetes.io/docs/concepts/configuration/secret
[root@master-1 app]# kubectl apply -f serviceaccount.yaml serviceaccount/admin created
1 2 3 4 5
[root@master-1 app]# kubectl get sa NAME SECRETS AGE admin131s default120d nfs-provisioner 118d
1 2 3 4 5 6
[root@master-1 app]# kubectl get secret NAME TYPE DATA AGE admin-token-j7n8j kubernetes.io/service-account-token 3 27m default-token-zmv4x kubernetes.io/service-account-token 3 20d mysecret Opaque 2 19d nfs-provisioner-token-xjn7p kubernetes.io/service-account-token 3 18d
看到有一个 token 已经被自动创建,只需要在 pod 的spec.serviceAccountName 字段中将name设置为您想要用的 service account 名字即可。在 pod 创建之初 service account 就必须已经存在,否则创建将被拒绝。需要注意的是不能更新已创建的 pod 的 service account。
[root@k8s-masterpki]# kubectl config use-context magedu@kubernetes Switched to context "magedu@kubernetes".
1 2 3
[root@k8s-master pki]# kubectl get pods No resources found. Errorfrom server (Forbidden): pods is forbidden: User "magedu" cannot list pods in the namespace "default"
[root@master-1 pki]# kubectl create --help Create a resource from a file orfrom stdin.
JSON and YAML formats are accepted.
Examples: # Create a pod using the data in pod.json. kubectl create -f ./pod.json
# Create a pod based on the JSON passed into stdin. cat pod.json | kubectl create -f -
# Edit the data in docker-registry.yaml in JSON thencreate the resource using the edited data. kubectl create -f docker-registry.yaml --edit -o json
Available Commands: clusterrole Create a ClusterRole. clusterrolebinding Create a ClusterRoleBinding for a particular ClusterRole configmap Create a configmap from a local file, directory or literal value deployment Create a deployment with the specified name. job Create a job with the specified name. namespaceCreate a namespacewith the specified name poddisruptionbudget Create a pod disruption budget with the specified name. priorityclass Create a priorityclass with the specified name. quota Create a quota with the specified name. roleCreate a rolewith single rule. rolebinding Create a RoleBinding for a particular Roleor ClusterRole secret Create a secret using specified subcommand service Create a service using specified subcommand. serviceaccount Create a service account with the specified name
Options: --allow-missing-template-keys=true: Iftrue, ignoreany errors in templates when a field ormapkeyismissingin the template. Only applies to golang and jsonpath output formats. --dry-run=false: Iftrue, only print the object that would be sent, without sending it. --edit=false: Edit the API resource before creating -f, --filename=[]: Filename, directory, or URL to files tousetocreate the resource -o, --output='': Output format. One of: json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file. --raw='': Raw URI to POST to the server. Uses the transport specified by the kubeconfig file. --record=false: Record current kubectl command in the resource annotation. Ifsettofalse, donot record the command. Ifsettotrue, record the command. Ifnotset, default to updating the existing annotation value only if one already exists. -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. --save-config=false: Iftrue, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this objectin the future. -l, --selector='': Selector (label query) to filter on, supports '=', '==', and'!='.(e.g. -l key1=value1,key2=value2) --template='': Template stringorpathto template file tousewhen -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview]. --validate=true: Iftrue, use a schematovalidate the input before sending it --windows-line-endings=false: Only relevant if --edit=true. Defaults to the line ending native to your platform.
Usage: kubectl create -f FILENAME [options]
Use"kubectl <command> --help"for more information about a given command. Use"kubectl options"for a list of global command-line options (applies toall commands).