资源注解
除了标签之外,Pod与其他各种资源还能使用资源注解(annotation)。与标签类似,注解也是”键值”类型的数据,不过它不能用于标签及挑选K8S对象,仅可用于为资源提供元数据信息。另外,注解中的元数据不受字符数量的限制,它可大可小,可以为结构或非结构化形式,也支持在标签中禁止使用的其他字符 资源注解可由用户手动添加,它也可由工具程序自动附加并使用它们。在K8S的新版中(alpha或beta阶段)为某资源引入新字段时,常以注解的方式提供,以避免其增删等变动对用户带来困扰,一旦确定支持使用它们,这些新增字段就将再引入到资源中并淘汰相关的注解。另外,为资源添加注解也可以让其他用户快速了解资源的相关信息,例如其创建者的身份,以下是常用的场景案例
- 由声明式配置层管理的字段:将这些字段定义为注解有助于识别由服务器或客户端设定的默认值、系统自动生成的字段以及由自动伸缩系统生成的字段
- 构建、发现或镜像相关的信息,例如,时间戳、发型ID、Git分支、PR号码、镜像哈希及仓库地址等
- 指向日志、监控、分析或审计仓库的指针
- 由客户端库或工具程序生成的用于调试目的的信息:如名称、版本、构建信息等
- 用户或工具程序的来源地址信息,例如,来自其它生态系统组件的相关对象的URL
- 轻量化滚动升级工具的元数据,如config及checkpoints
- 相关人员的电话号码等联系信息,或者指向类似信息的可寻址的目录条目,如网站站点
查看资源注解
kubectl get -o yaml
和kubectl describe
命令均能显示资源的注解信息,例如下面的命令显示的test-nodeselector的注解信息
[root@k8s-master01 nginx]# kubectl get pods
NAME READY STATUS RESTARTS AGE
client 0/1 Completed 0 5d23h
my-nginx-854bbd7557-xnbn9 1/1 Running 0 5d3h
test 1/1 Running 0 47h
test-nodeselector 1/1 Running 0 24m
[root@k8s-master01 nginx]# kubectl describe pods test-nodeselector
Name: test-nodeselector
Namespace: default
Priority: 0
Node: 172.18.15.113/172.18.15.113
Start Time: Wed, 10 Jun 2020 17:09:35 +0800
Labels: env=pre
Annotations: kubectl.kubernetes.io/last-applied-configuration:
{"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{},"labels":{"env":"pre"},"name":"test-nodeselector","namespace":"default"},"spe...
Status: Running
IP: 10.244.59.3
IPs:
IP: 10.244.59.3
...
...
...
[root@k8s-master01 nginx]#
test-nodeselector是此前由声明式配置命令apply创建,因此它在注解中保存了如上的相关信息以便在下次资源变动时进行版本对比
管理资源注解
annotations可在资源创建时使用
metadata.annotations
字段指定,也可以随时按需在活动的资源上使用kubectl annotate
命令进行附加,例如,为test-nodeselector重新进行注解
[root@k8s-master01 nginx]# kubectl annotate pods test-nodeselector created-by="cluster admin"
pod/test-nodeselector annotated
[root@k8s-master01 nginx]# kubectl describe pods test-nodeselector |grep "Annotation"
Annotations: created-by: cluster admin
[root@k8s-master01 nginx]#
如果在资源清单中指定,可以使用如下的方式,在metadata字段嵌套annotation
[root@k8s-master01 nginx]# cat nodeSelector.yaml
apiVersion: v1
kind: Pod
metadata:
annotations:
created-by: cluster admin
date: 2020.06.10
name: test-nodeselector
labels:
env: pre
spec:
containers:
- name: busybox
image: registry.cn-hangzhou.aliyuncs.com/jiangyida/busybox:0.1
ports:
- name: http
containerPort: 80
protocol: TCP
nodeSelector:
disktype: ssd
[root@k8s-master01 nginx]#
[root@k8s-master01 nginx]# kubectl apply -f nodeSelector.yaml
pod/test-nodeselector configured
[root@k8s-master01 nginx]#
查看资源注解
[root@k8s-master01 nginx]# kubectl describe pods test-nodeselector |grep "Annotations" -A 2
Annotations: created-by: cluster admin
date: 2020.06.10
kubectl.kubernetes.io/last-applied-configuration:
[root@k8s-master01 nginx]#