Kubernetes Yaml 文件详解
声明式与命令式是怎么回事
Kubernetes使用的YAML语言有一个非常关键的特性,叫“声明式”(Declarative),对应的有另外一个词:“命令式”(Imperative)。
大多数编程语言也属于命令式,它的特点是交互性强,注重顺序和过程,你必须“告诉”计算机每步该做什么,所有的步骤都列清楚,这样程序才能够一步步走下去,最后完成任务,显得计算机有点“笨”。
“声明式”,在Kubernetes出现之前比较少见,它与“命令式”完全相反,不关心具体的过程,更注重结果。我们不需要“教”计算机该怎么做,只要告诉它一个目标状态,它自己就会想办法去完成任务,相比起来自动化、智能化程度更高。
YAML 基础
YAML语言创建于2001年,比XML晚了三年。XML你应该知道吧,它是一种类似HTML的标签式语言,有很多繁文缛节。而YAML虽然在名字上模仿了XML,但实质上与XML完全不同,更适合人类阅读,计算机解析起来也很容易。
YAML的官网( https://yaml.org/)有对语言规范的完整介绍,所以我就不在这里列举语言的细节了,只讲一些与Kubernetes相关的要点,帮助你快速掌握。
你需要知道, **YAML是JSON的超集**,支持整数、浮点数、布尔、字符串、数组和对象等数据类型。也就是说,任何合法的JSON文档也都是YAML文档,如果你了解JSON,那么学习YAML会容易很多。
YAML语法规则
- 大小写敏感
- 使用缩进表示层级关系。缩进时不允许使用 Tab 键,只能使用空格。用几个空格无所谓,但是同一层级的要对齐。(习惯是2或者4个)
- 可以在一个文件中包含多个文件的内容。
—-表示两个文件分隔。 - 可以使用
#书写注释,从这个字符一直到行尾,都会被解析器忽略,比起JSON是很大的改进。 - 对象(字典)的格式与JSON基本相同,但Key不需要使用双引号。
- 数组(列表)是使用
-开头的清单形式(有点类似MarkDown)。 - 表示对象的
:和表示数组的-后面都必须要有空格。
在 Kubernetes 中,只需要知道两种结构类型即可:
- Lists
- - Maps
:
数据结构与类型
字典(Mapping)
表示以键值对(key: value)形式出现的数据。
- 使用 “冒号 + 空格” 来分开键与值。
# YAML
key: value
apiVersion: v1
kind: Pod
Maps的value既能够对应字符串也能够对应一个Maps。例如:
apiVersion: v1
kind: Pod
metadata:
name: kube100-site
labels:
app: web
注:上述的YAML文件中,metadata这个KEY对应的值为一个Maps,而嵌套的labels这个KEY的值又是一个Map。实际使用中可视情况进行多层嵌套。
YAML处理器根据行缩进来知道内容之间的关联。上述例子中,使用两个空格作为缩进,但空格的数据量并不重要,只是至少要求一个空格并且所有缩进保持一致的空格数 。例如,name和labels是相同缩进级别,因此YAML处理器知道他们属于同一map;它知道app是lables的值因为app的缩进更大。
注意:在YAML文件中绝对不要使用tab键
- 支持多层嵌套(用缩进表示层级关系)
# YAML
key:
child-key1: value1
child-key2: value2
// JSON
"key": {
"child-key1": "value1",
"child-key2": "value2",
}
支持流式风格的语法(用花括号包裹,用逗号加空格分隔,类似 JSON)
# YAML
key: { child-key1: value1, child-key2: value2 }
// JSON
"key": { "child-key1": "value1", "child-key2": "value2" }
使用 ? 声明一个复杂对象,允许使用多个词汇(数组)来组成键
# YAML
?
- keypart1
- keypart2
:
- value1
- value2
数组 List
- 一组以区块格式(即 破折号 + 空格)开头的数据组成一个数组
# YAML
values:
- value1
- value2
- value3
// JSON
{
"values": [ "value1", "value2", "value3" ]
}
- 支持多维数组(用缩进表示层级关系)
# YAML
values:
-
- value1
- value2
-
- value3
- value4
// JSON
"values": [ [ "value1", "value2"], ["value3", "value4"] ]
Lists的子项也可以是Maps,Maps的子项也可以是List,例如:
apiVersion: v1
kind: Pod
metadata:
name: kube100-site
labels:
app: web
spec:
containers:
- name: front-end
image: nginx
ports:
- containerPort: 80
- name: flaskapp-demo
image: jcdemo/flaskapp
ports: 8080
字符串
- 字符串一般不需要使用引号包裹,但是如果字符串中使用了反斜杠
\开头的转义字符就必须使用引号包裹。
# YAML
strings:
- hide in bash # 不用引号包裹
- Hello
world # 拆成多行后会自动在中间添加空格
- 'Hello with single quotes' # 单引号包裹
- "Hello with double quotes" # 双引号包裹
- "I am fine. \u263A" # 使用双引号包裹时支持 Unicode 编码
- "\x0d\x0a is \r\n" # 使用双引号包裹时还支持 Hex 编码
- 'He said: "Hello!"' # 单双引号支持嵌套"
// JSON
"strings":
[ "Hello without quote",
"Hello world",
"Hello with single quotes",
"Hello with double quotes",
"I am fine. ☺",
"\r\n is \r\n",
"He said: 'Hello!'" ]
- 对于所行的文字,YAML 提供了两种特殊的语法支持
保留换行
- 使用竖线
|来表示该语法,每行的缩进和行尾空白都会被去掉,而额外的缩进会被保留。
# YAML
lines: |
我是第一行
我是第二行
我是吴彦祖
我是第四行
我是第五行
// JSON
"lines": "我是第一行\n我是第二行\n 我是吴彦祖\n 我是第四行\n我是第五行"
折叠换行
使用右尖括号 > 来表示该语法,只有空白行才会被识别为换行,原来的换行符都会被转换为空格。
# YAML
lines: >
我是第一行
我也是第一行
我仍是第一行
我依旧是第一行
我是第二行
这么巧我也是第二行
// JSON
"lines": "我是第一行 我也是第一行 我仍是第一行 我依旧是第一行\n我是第二行 这么巧我也是第二行"
布尔值
- “true”、“True”、“TRUE”、“yes”、“Yes”、“YES” 皆为真
- “false”、“False”、“FALSE”、“no”、“No”、“NO” 皆为假
挪威问题
NO 会转化为布尔值,需要用引号包起来
注意数字类型,1.1.0会被转化为数字 1.1,需要用引号包起来
总结:不确定的东西就引起来
多行内容:
key: > # 不保留文字间的换行,保留末尾的换行
Your long
string here.
ket: >- # 不保留文字间的换行,不保留末尾的换行
Your long
string here.
key: | # 保留文字间的换行,保留末尾的换行
### Heading
* Bullet
* Points
key: |- # 保留文字间的换行,不保留末尾的换行
### Heading
* Bullet
* Points
如何编写YAML
最权威的答案无疑是Kubernetes的官方参考文档( https://kubernetes.io/docs/reference/kubernetes-api/),API对象的所有字段都可以在里面找到。不过官方文档内容太多太细,查阅起来有些费劲.
第一个技巧其实前面已经说过了,就是 kubectl api-resources 命令,它会显示出资源对象相应的API版本和类型,比如Pod的版本是“v1”,Ingress的版本是“networking.k8s.io/v1”,照着它写绝对不会错。
第二个技巧,是命令 kubectl explain,它相当于是Kubernetes自带的API文档,会给出对象字段的详细说明,这样我们就不必去网上查找了。比如想要看Pod里的字段该怎么写,就可以这样:
kubectl explain pod
kubectl explain pod.metadata
kubectl explain pod.spec
kubectl explain pod.spec.containers
这第三个技巧就是kubectl的两个特殊参数 --dry-run=client** 和 ****-o yaml**,前者是空运行,后者是生成YAML格式,结合起来使用就会让kubectl不会有实际的创建动作,而只生成YAML文件。
例如,想要生成一个Pod的YAML样板示例,可以在 kubectl run 后面加上这两个参数:
kubectl run nginx --image=nginx:alpine --dry-run=client -o yaml
就会生成一个绝对正确的YAML文件:
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: nginx
name: nginx
spec:
containers:
- image: nginx:alpine
name: nginx
resources: {}
dnsPolicy: ClusterFirst
restartPolicy: Always
status: {}
这个小技巧还可以再进化一下,把这段参数定义成Shell变量(名字任意,比如$do/$go,这里用的是$out),用起来会更省事,比如:
export out="--dry-run=client -o yaml"
kubectl run ngx --image=nginx:alpine $out
Pod 的 yaml
通过 kubectl explain 命令查看 Pod 的 yaml 需要指明的内容
root@master:~# kubectl explain pod
KIND: Pod
VERSION: v1
DESCRIPTION:
Pod is a collection of containers that can run on a host. This resource is
created by clients and scheduled onto hosts.
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/sig-architecture/api-conventions.md#resources
kind <string>
Kind is a string value 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/sig-architecture/api-conventions.md#types-kinds
metadata <Object>
Standard object's metadata. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
spec <Object>
Specification of the desired behavior of the pod. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
status <Object>
Most recently observed status of the pod. This data may not be up to date.
Populated by the system. Read-only. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
root@master:~#
root@master:~# kubectl explain pod.spec
KIND: Pod
VERSION: v1
RESOURCE: spec <Object>
DESCRIPTION:
Specification of the desired behavior of the pod. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
PodSpec is a description of a pod.
FIELDS:
activeDeadlineSeconds <integer>
Optional duration in seconds the pod may be active on the node relative to
StartTime before the system will actively try to mark it failed and kill
associated containers. Value must be a positive integer.
affinity <Object>
If specified, the pod's scheduling constraints
automountServiceAccountToken <boolean>
AutomountServiceAccountToken indicates whether a service account token
should be automatically mounted.
containers <[]Object> -required-
List of containers belonging to the pod. Containers cannot currently be
added or removed. There must be at least one container in a Pod. Cannot be
updated.
dnsConfig <Object>
Specifies the DNS parameters of a pod. Parameters specified here will be
merged to the generated DNS configuration based on DNSPolicy.
dnsPolicy <string>
Set DNS policy for the pod. Defaults to "ClusterFirst". Valid values are
'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. DNS
parameters given in DNSConfig will be merged with the policy selected with
DNSPolicy. To have DNS options set along with hostNetwork, you have to
specify DNS policy explicitly to 'ClusterFirstWithHostNet'.
Possible enum values:
- `"ClusterFirst"` indicates that the pod should use cluster DNS first
unless hostNetwork is true, if it is available, then fall back on the
default (as determined by kubelet) DNS settings.
- `"ClusterFirstWithHostNet"` indicates that the pod should use cluster DNS
first, if it is available, then fall back on the default (as determined by
kubelet) DNS settings.
- `"Default"` indicates that the pod should use the default (as determined
by kubelet) DNS settings.
- `"None"` indicates that the pod should use empty DNS settings. DNS
parameters such as nameservers and search paths should be defined via
DNSConfig.
enableServiceLinks <boolean>
EnableServiceLinks indicates whether information about services should be
injected into pod's environment variables, matching the syntax of Docker
links. Optional: Defaults to true.
ephemeralContainers <[]Object>
List of ephemeral containers run in this pod. Ephemeral containers may be
run in an existing pod to perform user-initiated actions such as debugging.
This list cannot be specified when creating a pod, and it cannot be
modified by updating the pod spec. In order to add an ephemeral container
to an existing pod, use the pod's ephemeralcontainers subresource.
hostAliases <[]Object>
HostAliases is an optional list of hosts and IPs that will be injected into
the pod's hosts file if specified. This is only valid for non-hostNetwork
pods.
hostIPC <boolean>
Use the host's ipc namespace. Optional: Default to false.
hostNetwork <boolean>
Host networking requested for this pod. Use the host's network namespace.
If this option is set, the ports that will be used must be specified.
Default to false.
hostPID <boolean>
Use the host's pid namespace. Optional: Default to false.
hostUsers <boolean>
Use the host's user namespace. Optional: Default to true. If set to true or
not present, the pod will be run in the host user namespace, useful for
when the pod needs a feature only available to the host user namespace,
such as loading a kernel module with CAP_SYS_MODULE. When set to false, a
new userns is created for the pod. Setting false is useful for mitigating
container breakout vulnerabilities even allowing users to run their
containers as root without actually having root privileges on the host.
This field is alpha-level and is only honored by servers that enable the
UserNamespacesSupport feature.
hostname <string>
Specifies the hostname of the Pod If not specified, the pod's hostname will
be set to a system-defined value.
imagePullSecrets <[]Object>
ImagePullSecrets is an optional list of references to secrets in the same
namespace to use for pulling any of the images used by this PodSpec. If
specified, these secrets will be passed to individual puller
implementations for them to use. More info:
https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod
initContainers <[]Object>
List of initialization containers belonging to the pod. Init containers are
executed in order prior to containers being started. If any init container
fails, the pod is considered to have failed and is handled according to its
restartPolicy. The name for an init container or normal container must be
unique among all containers. Init containers may not have Lifecycle
actions, Readiness probes, Liveness probes, or Startup probes. The
resourceRequirements of an init container are taken into account during
scheduling by finding the highest request/limit for each resource type, and
then using the max of of that value or the sum of the normal containers.
Limits are applied to init containers in a similar fashion. Init containers
cannot currently be added or removed. Cannot be updated. More info:
https://kubernetes.io/docs/concepts/workloads/pods/init-containers/
nodeName <string>
NodeName is a request to schedule this pod onto a specific node. If it is
non-empty, the scheduler simply schedules this pod onto that node, assuming
that it fits resource requirements.
nodeSelector <map[string]string>
NodeSelector is a selector which must be true for the pod to fit on a node.
Selector which must match a node's labels for the pod to be scheduled on
that node. More info:
https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
os <Object>
Specifies the OS of the containers in the pod. Some pod and container
fields are restricted if this is set.
If the OS field is set to linux, the following fields must be unset:
-securityContext.windowsOptions
If the OS field is set to windows, following fields must be unset: -
spec.hostPID - spec.hostIPC - spec.hostUsers -
spec.securityContext.seLinuxOptions - spec.securityContext.seccompProfile -
spec.securityContext.fsGroup - spec.securityContext.fsGroupChangePolicy -
spec.securityContext.sysctls - spec.shareProcessNamespace -
spec.securityContext.runAsUser - spec.securityContext.runAsGroup -
spec.securityContext.supplementalGroups -
spec.containers[*].securityContext.seLinuxOptions -
spec.containers[*].securityContext.seccompProfile -
spec.containers[*].securityContext.capabilities -
spec.containers[*].securityContext.readOnlyRootFilesystem -
spec.containers[*].securityContext.privileged -
spec.containers[*].securityContext.allowPrivilegeEscalation -
spec.containers[*].securityContext.procMount -
spec.containers[*].securityContext.runAsUser -
spec.containers[*].securityContext.runAsGroup
overhead <map[string]string>
Overhead represents the resource overhead associated with running a pod for
a given RuntimeClass. This field will be autopopulated at admission time by
the RuntimeClass admission controller. If the RuntimeClass admission
controller is enabled, overhead must not be set in Pod create requests. The
RuntimeClass admission controller will reject Pod create requests which
have the overhead already set. If RuntimeClass is configured and selected
in the PodSpec, Overhead will be set to the value defined in the
corresponding RuntimeClass, otherwise it will remain unset and treated as
zero. More info:
https://git.k8s.io/enhancements/keps/sig-node/688-pod-overhead/README.md
preemptionPolicy <string>
PreemptionPolicy is the Policy for preempting pods with lower priority. One
of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset.
priority <integer>
The priority value. Various system components use this field to find the
priority of the pod. When Priority Admission Controller is enabled, it
prevents users from setting this field. The admission controller populates
this field from PriorityClassName. The higher the value, the higher the
priority.
priorityClassName <string>
If specified, indicates the pod's priority. "system-node-critical" and
"system-cluster-critical" are two special keywords which indicate the
highest priorities with the former being the highest priority. Any other
name must be defined by creating a PriorityClass object with that name. If
not specified, the pod priority will be default or zero if there is no
default.
readinessGates <[]Object>
If specified, all readiness gates will be evaluated for pod readiness. A
pod is ready when all its containers are ready AND all conditions specified
in the readiness gates have status equal to "True" More info:
https://git.k8s.io/enhancements/keps/sig-network/580-pod-readiness-gates
restartPolicy <string>
Restart policy for all containers within the pod. One of Always, OnFailure,
Never. Default to Always. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy
Possible enum values:
- `"Always"`
- `"Never"`
- `"OnFailure"`
runtimeClassName <string>
RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group,
which should be used to run this pod. If no RuntimeClass resource matches
the named class, the pod will not be run. If unset or empty, the "legacy"
RuntimeClass will be used, which is an implicit class with an empty
definition that uses the default runtime handler. More info:
https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class
schedulerName <string>
If specified, the pod will be dispatched by specified scheduler. If not
specified, the pod will be dispatched by default scheduler.
securityContext <Object>
SecurityContext holds pod-level security attributes and common container
settings. Optional: Defaults to empty. See type description for default
values of each field.
serviceAccount <string>
DeprecatedServiceAccount is a depreciated alias for ServiceAccountName.
Deprecated: Use serviceAccountName instead.
serviceAccountName <string>
ServiceAccountName is the name of the ServiceAccount to use to run this
pod. More info:
https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
setHostnameAsFQDN <boolean>
If true the pod's hostname will be configured as the pod's FQDN, rather
than the leaf name (the default). In Linux containers, this means setting
the FQDN in the hostname field of the kernel (the nodename field of struct
utsname). In Windows containers, this means setting the registry value of
hostname for the registry key
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters to
FQDN. If a pod does not have FQDN, this has no effect. Default to false.
shareProcessNamespace <boolean>
Share a single process namespace between all of the containers in a pod.
When this is set containers will be able to view and signal processes from
other containers in the same pod, and the first process in each container
will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both
be set. Optional: Default to false.
subdomain <string>
If specified, the fully qualified Pod hostname will be
"<hostname>.<subdomain>.<pod namespace>.svc.<cluster domain>". If not
specified, the pod will not have a domainname at all.
terminationGracePeriodSeconds <integer>
Optional duration in seconds the pod needs to terminate gracefully. May be
decreased in delete request. Value must be non-negative integer. The value
zero indicates stop immediately via the kill signal (no opportunity to shut
down). If this value is nil, the default grace period will be used instead.
The grace period is the duration in seconds after the processes running in
the pod are sent a termination signal and the time when the processes are
forcibly halted with a kill signal. Set this value longer than the expected
cleanup time for your process. Defaults to 30 seconds.
tolerations <[]Object>
If specified, the pod's tolerations.
topologySpreadConstraints <[]Object>
TopologySpreadConstraints describes how a group of pods ought to spread
across topology domains. Scheduler will schedule pods in a way which abides
by the constraints. All topologySpreadConstraints are ANDed.
volumes <[]Object>
List of volumes that can be mounted by containers belonging to the pod.
More info: https://kubernetes.io/docs/concepts/storage/volumes
root@master:~#