k8s创建服务账号——Service Account

http://docs.kubernetes.org.cn/84.html

https://blog.csdn.net/BigData_Mining/article/details/88529157

https://v1-16.docs.kubernetes.io/zh/docs/tasks/configure-pod-container/configure-service-account/

http://docs.kubernetes.org.cn/84.html

版本k8s1.5.2实操

 

Service Account(服务账号):是指由Kubernetes API 管理的账号,用于为Pod 之中的服务进程在访问Kubernetes API时提供身份标识( identity ) 。Service Account通常要绑定于特定的命名空间,它们由 API Server 创建,或者通过 API 调用于动创建 ,附带着一组存储为Secret的用于访问API Server的凭据。

User Accounts 与 Service Accounts

Kubernetes区分普通帐户(user accounts)和服务帐户(service accounts)的原因:

  • 普通帐户是针对(人)用户的,服务账户针对Pod进程。
  • 普通帐户是全局性。在集群所有namespaces中,名称具有惟一性。
  • 通常,群集的普通帐户可以与企业数据库同步,新的普通帐户创建需要特殊权限。服务账户创建目的是更轻量化,允许集群用户为特定任务创建服务账户。
  • 普通帐户和服务账户的审核注意事项不同。
  • 对于复杂系统的配置包,可以包括对该系统的各种组件的服务账户的定义

Service account automation

三个独立的组件协作,来实现service account的自动化:

  • 一个service account准入控制器(admission controller)
  • 一个 Token controller
  • 一个service account controller

Service Account Admission Controller

通过 Admission Controller插件来实现对pod修改,它是apiserver的一部分。创建或更新pod时会同步进行修改pod。当插件处于激活状态(在大多数发行版中都默认情况)创建或修改pod时,会按以下操作执行:

  1. 如果pod没有设置ServiceAccount,则将ServiceAccount设置为default。
  2. 确保pod引用的ServiceAccount存在,否则将会拒绝请求。
  3. 如果pod不包含任何ImagePullSecrets,则将ServiceAccount的ImagePullSecrets会添加到pod中。
  4. 为包含API访问的Token的pod添加了一个volume。
  5. 把volumeSource添加到安装在pod的每个容器中,挂载在/var/run/secrets/kubernetes.io/serviceaccount

Token controller

TokenController作为controller-manager的一部分运行。异步行为:

  • 观察serviceAccount的创建,并创建一个相应的Secret 来允许API访问。
  • 观察serviceAccount的删除,并删除所有相应的ServiceAccountToken Secret
  • 观察secret 添加,并确保关联的ServiceAccount存在,并在需要时向secret 中添加一个Token。
  • 观察secret 删除,并在需要时对应 ServiceAccount 的关联

需要使用--service-account-private-key-file 参数选项将Service Account 密匙(key)文件传递给controller-manager中的Token controller。key用于 Service Account Token签名。同样,也需要使用--service-account-key-file(k8s1.5没有这个参数)参数选项将相应的(public key)公匙传递给kube-apiserver ,公钥用于在认证期间验证Token。

To create additional API tokens

controller loop能确保每个Service Account都存在一个带有API Token的secret 。如要为Service Account创建额外的API Token,可以使用创建ServiceAccountToken类型的secret,添加与Service Account对应的 annotation 属性,controller会更新令牌:

secret.json:

{
    "kind": "Secret",
    "apiVersion": "v1",
    "metadata": {
        "name": "mysecretname",
        "annotations": {
            "kubernetes.io/service-account.name": "myserviceaccount"
        }
    },
    "type": "kubernetes.io/service-account-token"
}
kubectl create -f ./secret.json
kubectl describe secret mysecretname

要删除/使Service Account token无效

kubectl delete secret mysecretname

Service Account Controller

Service Account Controller在namespaces里管理ServiceAccount,并确保每个有效的namespaces中都存在一个名为“default”的ServiceAccount。

========================================================================================

首先看字面意思

Service 指的是k8s中的svc资源吧

account 翻译成账号

那 service account就是给service用的账号啦

一个Service Account资源往往由用户名及相关的Secret对象组成的

与 ServiceAccount对应的是namespace

每个namespace都有一个默认的service account叫default

当然我们也可以给namespace创建多个 service account

核心内容在data字段中 包含三部分 都做了base64编码

ca.crt :集群api server使用的根CA,基于该CA会签发一系列的服务端证书 客户端证书等

namespace : 解码后就是 kube-system

token : 认证用的令牌

认证用的用户名默认为:

system:serviceaccount:{namespace}:{serviceaccount}

那我们有了这个账号来干啥呢?

特别注意

这个 serviceaccount账号能够让Pod中的容器访问k8s集群而提出的一个概念。简单的说就是内部资源要访问外部资源就要通过serviceaccount实现

k8s创建服务账号——Service Account_第1张图片

实操部分

1.打开kube-apiserver中的KUBE_ADMISSION_CONTROL="--admission-control=NamespaceLifecycle,NamespaceExists,LimitRanger,SecurityContextDeny,ServiceAccount,ResourceQuota"

ServiceAccount配置项目

--service-account-key-file=/etc/pki/k8s/server.key  --service-account-lookup=true 参数

root@localhost:/etc/kubernetes # cat apiserver 
###
# kubernetes system config
#
# The following values are used to configure the kube-apiserver
#

# The address on the local server to listen to.
#KUBE_API_ADDRESS="--insecure-bind-address=0.0.0.0 --bind-address=0.0.0.0 --advertise-address=10.10.3.127"
KUBE_API_ADDRESS="--insecure-bind-address=0.0.0.0 --bind-address=0.0.0.0"

# The port on the local server to listen on.
KUBE_API_PORT="--port=8080 --secure-port=6443"

# Port minions listen on
KUBELET_PORT="--kubelet-port=10250"

# Comma separated list of nodes in the etcd cluster
KUBE_ETCD_SERVERS="--etcd-servers=http://10.10.3.127:2379"

# Address range to use for services
KUBE_SERVICE_ADDRESSES="--service-cluster-ip-range=10.254.0.0/16"

# default admission control policies
KUBE_ADMISSION_CONTROL="--admission-control=NamespaceLifecycle,NamespaceExists,LimitRanger,SecurityContextDeny,ServiceAccount,ResourceQuota"
#KUBE_ADMISSION_CONTROL="--admission-control=NamespaceLifecycle,NamespaceExists,LimitRanger,SecurityContextDeny,ResourceQuota"

# Add your own!
#KUBE_API_ARGS="--service-node-port-range=1-65535 --anonymous-auth=false"
# username+password password,name,uid[123456aA,admin,1]
#KUBE_API_ARGS="--service-node-port-range=1-65535 --anonymous-auth=false --basic-auth-file=/etc/kubernetes/api/staticpassword-auth.csv"
#token-auth [token,admin,1]
#KUBE_API_ARGS="--service-node-port-range=1-65535 --anonymous-auth=false --token-auth-file=/etc/kubernetes/api/statictoken-auth.csv"
#ca
#KUBE_API_ARGS="--service-node-port-range=1-65535 --anonymous-auth=false --client-ca-file=/etc/pki/k8s/ca.crt --tls-private-key-file=/etc/pki/k8s/server.key --tls-cert-file=/etc/pki/k8s/server.crt"
#all
KUBE_API_ARGS="--service-node-port-range=1-65535 --anonymous-auth=false --basic-auth-file=/etc/kubernetes/api/staticpassword-auth.csv --token-auth-file=/etc/kubernetes/api/statictoken-auth.csv --client-ca-file=/etc/pki/k8s/ca.crt --tls-private-key-file=/etc/pki/k8s/server.key --tls-cert-file=/etc/pki/k8s/server.crt --service-account-key-file=/etc/pki/k8s/server.key --service-account-lookup=true"

2.controller-manager 配置

添加:--service-account-private-key-file=/etc/pki/k8s/server.key"  密钥

###
# The following values are used to configure the kubernetes controller-manager

# defaults from config and apiserver should be adequate

# Add your own!
KUBE_CONTROLLER_MANAGER_ARGS="--pv-recycler-pod-template-filepath-nfs=/etc/kubernetes/recycler.yaml --pv-recycler-pod-template-filepath-hostpath=/etc/kubernetes/recycler.yaml --service-account-private-key-file=/etc/pki/k8s/server.key"
systemctl restart  etcd
systemctl restart kube-apiserver.service
systemctl restart  kube-controller-manager.service
systemctl restart  kube-scheduler.service

 

3.使用

3.1默认情况

1.创建namespace
kubectl  create ns wubo

2.创建私有docker镜像仓库的secret 类型为docker-registry 名字为registrysecret。其实最后也是
root@localhost:~/work/k8s/pods/kuber/python-web # cat ~/.docker/config.json                                                                                                                                                       docker login harbor.superred.com 也可以生成但是没有名字给k8s引用,这主方式不但生生成如下信息还有名字引用如下内容,然后名字给k8s使用。
{
	"auths": {
		"10.10.3.104": {
			"auth": "YWRtaW46SGFyYm9yMTIzNDU="
		},
		"harbor.superred.com": {
			"auth": "YWRtaW46SGFyYm9yMTIzNDU="
		}
	}
}#
kubectl create secret docker-registry registrysecret --docker-server=http://harbor.superred.com --docker-username=admin --docker-password=Harbor12345 [email protected] -n wubo


3.root@localhost:~/work/k8s/pods/kuber/python-web # cat mysql-con-svc.yaml 
apiVersion: v1
kind: Service
metadata:
  name: server-mysql
  namespace: wubo
  labels:
    name: server-mysql
spec:
  #type: ClusterIP
  #type: LoadBalancer
  type: NodePort
  #clusterIP: 10.254.111.110
  #externalIPs: 
  #  - 10.10.3.119
  ports:
    - port: 3306
      nodePort: 33306
      targetPort: 3306
  selector:
    name: server-mysql-pod
#spec:
#  #type: ClusterIP
#  #type: LoadBalancer
#  #type: NodePort
#  #clusterIP: 10.254.111.110
#  externalIPs: 
#    - 10.10.3.119
#  ports:
#    - port: 3306
#      #nodePort: 33306
#      #targetPort: 3306
#  selector:
#    name: server-mysql-pod

---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  namespace: wubo
  name: server-mysql-deploy
  labels:
    name: server-mysql-deploy
spec:
  replicas: 1
  selector:
    matchLabels:
      name: server-mysql-pod
  template:
    metadata:
      name: server-mysql-pod
      labels:
        name: server-mysql-pod
    spec:
      containers:
      - name: server-mysql
        image: harbor.superred.com/superredtools/mysql:5.7
        resources:
          requests:
            cpu: 100m
            memory: 100Mi
        ports:
        - containerPort: 3306
        env:
        - name: 'MYSQL_ROOT_PASSWORD'
          value: '123456aA'
        volumeMounts:
        - name: mysql-storage
          mountPath: /var/lib/mysql
        imagePullPolicy: IfNotPresent #IfNotPresent #Always Nerver
      #nodeName: k8s-node-2
      restartPolicy: Always
      volumes:
      - name: mysql-storage
        hostPath:
          path: /mysql/data
      imagePullSecrets:
      - name: registrysecret
      #serviceAccountName: admin

此时会自动在namespace为wubo的下面生成serviceaccount(sa)名字为“default”和secrets默认名字为default-token-xxxxx

secrets就为serviceaccount服务用户的token信息了。

3.1指定方式:

1.创建sa指定在namespace
root@localhost:~/work/k8s/pods/kuber/python-web # kubectl create sa admin -n wubo
serviceaccount "admin" created

此时会自动生成secrets/admin-token-xxxx

2.指定sa:参数->serviceAccountName: admin
root@localhost:~/work/k8s/pods/kuber/python-web # cat mysql-con-svc.yaml 
apiVersion: v1
kind: Service
metadata:
  name: server-mysql
  namespace: wubo
  labels:
    name: server-mysql
spec:
  #type: ClusterIP
  #type: LoadBalancer
  type: NodePort
  #clusterIP: 10.254.111.110
  #externalIPs: 
  #  - 10.10.3.119
  ports:
    - port: 3306
      nodePort: 33306
      targetPort: 3306
  selector:
    name: server-mysql-pod
#spec:
#  #type: ClusterIP
#  #type: LoadBalancer
#  #type: NodePort
#  #clusterIP: 10.254.111.110
#  externalIPs: 
#    - 10.10.3.119
#  ports:
#    - port: 3306
#      #nodePort: 33306
#      #targetPort: 3306
#  selector:
#    name: server-mysql-pod

---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  namespace: wubo
  name: server-mysql-deploy
  labels:
    name: server-mysql-deploy
spec:
  replicas: 1
  selector:
    matchLabels:
      name: server-mysql-pod
  template:
    metadata:
      name: server-mysql-pod
      labels:
        name: server-mysql-pod
    spec:
      containers:
      - name: server-mysql
        image: harbor.superred.com/superredtools/mysql:5.7
        resources:
          requests:
            cpu: 100m
            memory: 100Mi
        ports:
        - containerPort: 3306
        env:
        - name: 'MYSQL_ROOT_PASSWORD'
          value: '123456aA'
        volumeMounts:
        - name: mysql-storage
          mountPath: /var/lib/mysql
        imagePullPolicy: IfNotPresent #IfNotPresent #Always Nerver
      #nodeName: k8s-node-2
      restartPolicy: Always
      volumes:
      - name: mysql-storage
        hostPath:
          path: /mysql/data
      imagePullSecrets:
      - name: registrysecret
      serviceAccountName: admin

4 kubectl create -f mysql-con-svc.yaml

 观看信息:

root@localhost:/etc/pki/k8s # watch kubectl get pod,svc,serviceaccount,secrets -o wide -n wubo

Every 2.0s: kubectl get pod,svc,serviceaccount,secrets -o wide -n wubo                                                                                                                                        Wed Aug 19 22:47:51 2020

NAME                                      READY     STATUS    RESTARTS   AGE       IP          NODE
po/server-mysql-deploy-1677406881-4dmhn   1/1       Running   0          24s       10.0.29.2   10.10.3.183

NAME               CLUSTER-IP	   EXTERNAL-IP   PORT(S)          AGE       SELECTOR
svc/server-mysql   10.254.120.74   	 3306:33306/TCP   24s       name=server-mysql-pod

NAME         SECRETS   AGE
sa/admin     1         2m
sa/default   1         14m

NAME                          TYPE                                  DATA      AGE
secrets/admin-token-cd7gh     kubernetes.io/service-account-token   2         2m
secrets/default-token-ztr3g   kubernetes.io/service-account-token   2         13m
secrets/registrysecret        kubernetes.io/dockercfg               1         16h
root@localhost:~/work/k8s/pods/kuber/python-web # kubectl describe po/server-mysql-deploy-1677406881-4dmhn -n wubo
Name:		server-mysql-deploy-1677406881-4dmhn
Namespace:	wubo
Node:		10.10.3.183/10.10.3.183
Start Time:	Wed, 19 Aug 2020 22:47:27 -0400
Labels:		name=server-mysql-pod
		pod-template-hash=1677406881
Status:		Running
IP:		10.0.29.2
Controllers:	ReplicaSet/server-mysql-deploy-1677406881
Containers:
  server-mysql:
    Container ID:	docker://5bbcb516f1c70b7dad0242a28f3b5c4a34dc01ef9fa84f66bbddcb8665458953
    Image:		harbor.superred.com/superredtools/mysql:5.7
    Image ID:		docker-pullable://harbor.superred.com/superredtools/mysql@sha256:d3418a353847c7b34e3b082d1ea35a9d12fd1244d3d841d8cfe076e72c216b00
    Port:		3306/TCP
    Requests:
      cpu:		100m
      memory:		100Mi
    State:		Running
      Started:		Wed, 19 Aug 2020 22:47:28 -0400
    Ready:		True
    Restart Count:	0
    Volume Mounts:
      /var/lib/mysql from mysql-storage (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from admin-token-cd7gh (ro)
    Environment Variables:
      MYSQL_ROOT_PASSWORD:	123456aA
Conditions:
  Type		Status
  Initialized 	True 
  Ready 	True 
  PodScheduled 	True 
Volumes:
  mysql-storage:
    Type:	HostPath (bare host directory volume)
    Path:	/mysql/data
  admin-token-cd7gh:
    Type:	Secret (a volume populated by a Secret)
    SecretName:	admin-token-cd7gh
QoS Class:	Burstable
Tolerations:	
Events:
  FirstSeen	LastSeen	Count	From			SubObjectPath			Type		Reason		Message
  ---------	--------	-----	----			-------------			--------	------		-------
  3m		3m		1	{default-scheduler }					Normal		Scheduled	Successfully assigned server-mysql-deploy-1677406881-4dmhn to 10.10.3.183
  3m		3m		1	{kubelet 10.10.3.183}	spec.containers{server-mysql}	Normal		Pulled		Container image "harbor.superred.com/superredtools/mysql:5.7" already present on machine
  3m		3m		1	{kubelet 10.10.3.183}	spec.containers{server-mysql}	Normal		Created		Created container with docker id 5bbcb516f1c7; Security:[seccomp=unconfined]
  3m		3m		1	{kubelet 10.10.3.183}	spec.containers{server-mysql}	Normal		Started		Started container with docker id 5bbcb516f1c7
root@localhost:~/work/k8s/pods/kuber/python-web # kubectl describe sa admin -n wubo                       
Name:		admin
Namespace:	wubo
Labels:		

Image pull secrets:	

Mountable secrets: 	admin-token-cd7gh

Tokens:            	admin-token-cd7gh

root@localhost:~/work/k8s/pods/kuber/python-web # kubectl describe  secrets/admin-token-cd7gh  -n wubo            
Name:		admin-token-cd7gh
Namespace:	wubo
Labels:		
Annotations:	kubernetes.io/service-account.name=admin
		kubernetes.io/service-account.uid=337c2408-e28f-11ea-b35a-52540002328d

Type:	kubernetes.io/service-account-token

Data
====
namespace:	4 bytes
token:		eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ3dWJvIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImFkbWluLXRva2VuLWNkN2doIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6ImFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiMzM3YzI0MDgtZTI4Zi0xMWVhLWIzNWEtNTI1NDAwMDIzMjhkIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Ond1Ym86YWRtaW4ifQ.IdaENjEaeRloplpHs_tpIdPs2Prnw9zvQVMkeBr5S7ONLui76L3gnzcNMbAwJUqa11v6mtkmK82_erqKZj0ATQ00vko6T2-o7ZS1lC8B1tuDMwXSWQFeftSHiP7XV_-sZfjnWOtyxu-eBsaakZIVzZUMHkU7k6S8gpFs8ti9dONMvq1Bg-kEFHMxN1uPTH1idE77T40Rup8f-Kim3R10hb44uLL1sedZMx4O3Uxni-Qfww7PGuwMb3zROAan1S6W9Pvn_gneUv7FskTOo6j8RqWrppY9Qa24pippb24CFsaDQtFKUWO-vnE5cyxLuQe_sr5WEnBWmowfrNp4PH1jCA

root@localhost:~/work/k8s/pods/kuber/python-web # kubectl get   secrets/admin-token-cd7gh  -o json -n wubo
{
    "apiVersion": "v1",
    "data": {
        "namespace": "d3Vibw==",
        "token": "ZXlKaGJHY2lPaUpTVXpJMU5pSXNJblI1Y0NJNklrcFhWQ0o5LmV5SnBjM01pT2lKcmRXSmxjbTVsZEdWekwzTmxjblpwWTJWaFkyTnZkVzUwSWl3aWEzVmlaWEp1WlhSbGN5NXBieTl6WlhKMmFXTmxZV05qYjNWdWRDOXVZVzFsYzNCaFkyVWlPaUozZFdKdklpd2lhM1ZpWlhKdVpYUmxjeTVwYnk5elpYSjJhV05sWVdOamIzVnVkQzl6WldOeVpYUXVibUZ0WlNJNkltRmtiV2x1TFhSdmEyVnVMV05rTjJkb0lpd2lhM1ZpWlhKdVpYUmxjeTVwYnk5elpYSjJhV05sWVdOamIzVnVkQzl6WlhKMmFXTmxMV0ZqWTI5MWJuUXVibUZ0WlNJNkltRmtiV2x1SWl3aWEzVmlaWEp1WlhSbGN5NXBieTl6WlhKMmFXTmxZV05qYjNWdWRDOXpaWEoyYVdObExXRmpZMjkxYm5RdWRXbGtJam9pTXpNM1l6STBNRGd0WlRJNFppMHhNV1ZoTFdJek5XRXROVEkxTkRBd01ESXpNamhrSWl3aWMzVmlJam9pYzNsemRHVnRPbk5sY25acFkyVmhZMk52ZFc1ME9uZDFZbTg2WVdSdGFXNGlmUS5JZGFFTmpFYWVSbG9wbHBIc190cElkUHMyUHJudzl6dlFWTWtlQnI1UzdPTkx1aTc2TDNnbnpjTk1iQXdKVXFhMTF2Nm10a21LODJfZXJxS1pqMEFUUTAwdmtvNlQyLW83WlMxbEM4QjF0dURNd1hTV1FGZWZ0U0hpUDdYVl8tc1pmam5XT3R5eHUtZUJzYWFrWklWelpVTUhrVTdrNlM4Z3BGczh0aTlkT05NdnExQmcta0VGSE14TjF1UFRIMWlkRTc3VDQwUnVwOGYtS2ltM1IxMGhiNDR1TEwxc2VkWk14NE8zVXhuaS1RZnd3N1BHdXdNYjN6Uk9BYW4xUzZXOVB2bl9nbmVVdjdGc2tUT282ajhScVdycHBZOVFhMjRwaXBwYjI0Q0ZzYURRdEZLVVdPLXZuRTVjeXhMdVFlX3NyNVdFbkJXbW93ZnJOcDRQSDFqQ0E="
    },
    "kind": "Secret",
    "metadata": {
        "annotations": {
            "kubernetes.io/service-account.name": "admin",
            "kubernetes.io/service-account.uid": "337c2408-e28f-11ea-b35a-52540002328d"
        },
        "creationTimestamp": "2020-08-20T02:45:26Z",
        "name": "admin-token-cd7gh",
        "namespace": "wubo",
        "resourceVersion": "623738",
        "selfLink": "/api/v1/namespaces/wubo/secrets/admin-token-cd7gh",
        "uid": "337e1a21-e28f-11ea-b35a-52540002328d"
    },
    "type": "kubernetes.io/service-account-token"
}

 namespace变成的base64

编码

root@localhost:~/work/k8s/pods/kuber/python-web # echo wubo| base64          
d3Vibwo=

解码 

root@localhost:~/work/k8s/pods/kuber/python-web # echo d3Vibw==| base64 -d                                                                                                                                                      127 ↵
wubo# 

 

你可能感兴趣的:(k8s创建服务账号——Service Account)