高效编写 kubernetes-YAML文件

1. YAML语法格式

2. kubernetes YAML 字段

3. 得力助手:help,dry-run,explain

4. vscode 工具生成和编写

5. YAML语法检查系统

YAML文件主要是编写 k8s 的一些资源的,对象(资源里面包含对象),字段等,哪些字段,字段对应的值,资源含义搞清楚。

一.YAML的语法格式

YAML(YAML Ain 't Markup Language)是一种人类可读的数据序列化,常用于配置文件和数据交换。与JSON类似,YAML以键值对的方式表示数据,但是更强调可读性和易用性,使得它在配置文件,持续集成,编排工具(如ansible,kubernetes)等领域广泛使用。

YAML他不是一种编程语言,他是一种文本的格式。编程语言分为有结尾符,语句的结尾符,有一些编程语言是没有的,比如if,有的有结尾,比如fi,python 有些他是不需要结尾的,比如file

springboot,ansible,kubernetes他们的YAML内容是不一样的,他们只是采用了YAML这种文本格式,里面的字段都是有他们自己预定义的。定义了什么字段,他就会去引用什么。所以说 kubernetes 他有自己的字段,ansible 也有他自己的字段,kubernetes的字段高达七十几种,常用的大约十几种吧!

YAML格式如下:

1)缩进表示层级关系
2)不支持制表符 "tab" 缩进,使用空格缩进
3)通常开头缩进2个空格
4)字符后缩进1个空格,如冒号,逗号等
5)"---"表示YAML格式,一个文件的开始
6)"#" 注释

calico 网络配置文件 vim /root/calico-3.27.3/manifests/calico.yaml

root@k8s-master-10:~/calico-3.27.3/manifests# cat calico.yaml
---
# Source: calico/templates/calico-kube-controllers.yaml
# This manifest creates a Pod Disruption Budget for Controller to allow K8s Cluster Autoscaler to evict

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: calico-kube-controllers
  namespace: kube-system
  labels:
    k8s-app: calico-kube-controllers
spec:
  maxUnavailable: 1
  selector:
    matchLabels:
      k8s-app: calico-kube-controllers
---
# Source: calico/templates/calico-kube-controllers.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: calico-kube-controllers
  namespace: kube-system
---
# Source: calico/templates/calico-node.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: calico-node
  namespace: kube-system
---
# Source: calico/templates/calico-node.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: calico-cni-plugin
  namespace: kube-system
---

Kubernetes YAML字段类型

POD资源配置选项
apiVersion: v1
kind: Pod
metadata:
  labels: 
    key: value
  name: ""
  namespace: ""
spec:
  containers:
  - image: ""
    imagePullPolicy: "Always|ifNotPresent|Never"
    name: ""
    args: []
    command: []
    ports: []
    env: []
    resources: {}
    livenessProbe: {}
    readinessProbe: {}
    startupProbe: {}
    volumeMounts: {}
    securityContext: {}
    lifecycle: {}
  volumes: []



# springboot,ansible,kubernetes他们的YAML内容是一样的,他们只是采用了YAML这种文本格式
以上YAML语法解释:
apiVersion: v1
kind: Pod
metadata:
  labels: 
    key: value
  name: ""
  namespace: ""
spec:	# 资源对象的核心配置
  containers:
  - image: ""	# 指定镜像的名称
    imagePullPolicy: "Always|ifNotPresent|Never" 	# 指定镜像下载策略
    name: ""
    args: []		# 指定参数
    command: []		# 执行的命令
    ports: []		# 声明的端口
    env: []			# 变量
    resources: {}	# 资源配额
    livenessProbe: {}	# 健康检查
    readinessProbe: {}
    startupProbe: {}	# 指定启动检查
    volumeMounts: {}	# 数据卷
    securityContext: {}	# 安全上下文
    lifecycle: {}		# 回收,生命周期的句子,回调
  volumes: []		# 配置管理卷的来源

编排 yaml文件,pod资源配置是修改最多的地方,已作预定义,最终都会转化为 JSON 格式提交过去。

kubernetes对属性也好,字段也好,做了预定义,已经定义了它是什么类型了,因为这些 yaml 最终都会按提交到 k8s 的 apiserver 那里,所以他最终都会转换成 JSON 提交

我们如何确定 yaml 的这些字段是[] ,还是""呢?还是他是一个什么样的意思,当你明白了这一点,这个字段你就会去写了。

字段值类型:

1.<string> : 表示一个字符串 比如 name: "k8s" 表示一个固定的值

2. <map[string]string> : 表示一个键值对的映射,其中键和值都是字符串类型。比如 标签就是这个类型 比如

labels:

key1 : value1

key2 : value2

3)<[]string> : 表示一个字符串列表,使用[]表示该字段可以包含多个字符串值,并且每个值都是独立的。比如 command: ["a","b"]

4)<Object> : 表示一个单独的对象 {}

5)<[]Object> : 表示一个对象列表。使用[]表示该字段可以包含多个对象,并且每个对象可以包含多个字符串。

因为这些 yaml 最终都会按提交到 k8s 的 apiserver 那里,所以他最终都会转换成 JSON 提交过去。

k8s对"",{},[]等已作预定义了,具体含义如下:

"" 表示的就是字符串

{} 表示一个对象

[] 表示的是字符串列表,使用[]表示该字段可以包含多个字符串值,且都是独立的。

'-' 一个横杠代表一个 Object, 比如 Containers:

表示一个单独的对象,他的父级是一个对象列表

containers:	# 可以有多个容器对象,可以表示有多个容器,每个容器对象表示一个横杠
        - name: calico-kube-controllers
          image: docker.io/calico/kube-controllers:v3.27.3
          imagePullPolicy: IfNotPresent
          env:
            # Choose which controllers to run. 
            '#'一下以'-'开头的表示一个单独的对象,而它的赋值就是对象列表
            - name: ENABLED_CONTROLLERS
              value: node
            - name: DATASTORE_TYPE
              value: kubernetes
          livenessProbe:
            exec:
              command:
              - /usr/bin/check-status
              - -l
            periodSeconds: 10
            initialDelaySeconds: 10
            failureThreshold: 6
            timeoutSeconds: 10
          readinessProbe:
            exec:
              command:
              - /usr/bin/check-status
              - -r
            periodSeconds: 10


spec:
  # The controllers can only have a single active instance.
  replicas: 1
  selector:
    matchLabels:
      k8s-app: calico-kube-controllers
  strategy:
    type: Recreate
  template:
    metadata:
      name: calico-kube-controllers
      namespace: kube-system
      labels:
        k8s-app: calico-kube-controllers
    spec:
      nodeSelector:
        kubernetes.io/os: linux
      tolerations:
        # Mark the pod as a critical add-on for rescheduling.
        - key: CriticalAddonsOnly
          operator: Exists
        - key: node-role.kubernetes.io/master
          effect: NoSchedule
        - key: node-role.kubernetes.io/control-plane
          effect: NoSchedule
      serviceAccountName: calico-kube-controllers
      priorityClassName: system-cluster-critical

如何去确定这些字段的类型?

  • help: 有时候,我们可能忘记具体的命令用法或参数选项。在这种情况下,"help"命令将成为你的得力助手,为你提供清晰的指导。

  • dry-run: 通过使用 "dry-run" 选项,可以预先验证命令的效果。这种模拟执行命令不会对集群产生实际影响,再搭配上 -o 选项以将结果输出为 YAML 格式,能够快速地获得所需的 YAML 文件。

  • explain: 在编写 YAML 文件时,了解资源类型的结构和属性至关重要。通过 "explain" 命令,你可以轻松掌握资源的所有字段,默认值以及示例的详细信息,帮助你更好地编写 YAML 文件。

    打印字段选项信息--explain

  •  
    # 打印字段选项信息
    kubectl explain --help 
    
    root@k8s-master-10:~# 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      <ObjectMeta>
        Standard object's metadata. More info:
        https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
    
      spec  <PodSpec>
        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        <PodStatus>
        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
    
    -----------------------------------------------------------------------------------
    kubectl explain pod.spec.containers
    
    root@k8s-master-10:~# kubectl explain pod.spec.containers
    KIND:       Pod
    VERSION:    v1
    
    FIELD: containers <[]Container>   容器字段表示是对象列表 如下的形式
    
    [
    	{},
    	{},
    	{}
    ]
    # 列表嵌套对象,对象里面再嵌套列表
    containers:
    - name: 第一个容器
    - name: 第二个容器
    DESCRIPTION:
        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.
        A single application container that you want to run within a pod.
    
    FIELDS:
      args  <[]string>	# 列表字符串,有如下两种形式显示
      
      [1,2,3]
      -1
      -2
      -3
      
        Arguments to the entrypoint. The container image's CMD is used if this is
        not provided. Variable references $(VAR_NAME) are expanded using the
        container's environment. If a variable cannot be resolved, the reference in
        the input string will be unchanged. Double $$ are reduced to a single $,
        which allows for escaping the $(VAR_NAME) syntax: i.e. "$$(VAR_NAME)" will
        produce the string literal "$(VAR_NAME)". Escaped references will never be
        expanded, regardless of whether the variable exists or not. Cannot be
        updated. More info:
        https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell
    
      command       <[]string>  列表字符串 ["a","b","c"]
      
        Entrypoint array. Not executed within a shell. The container image's
        ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME)
        are expanded using the container's environment. If a variable cannot be
        resolved, the reference in the input string will be unchanged. Double $$ are
        reduced to a single $, which allows for escaping the $(VAR_NAME) syntax:
        i.e. "$$(VAR_NAME)" will produce the string literal "$(VAR_NAME)". Escaped
        references will never be expanded, regardless of whether the variable exists
        or not. Cannot be updated. More info:
        https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell
    
      env   <[]EnvVar>  列表变量 如下表示
      		env: 
      		- name: abc
      		  value: 123
      		- name: sde
      		  value: 456
      
        List of environment variables to set in the container. Cannot be updated.
    
      envFrom       <[]EnvFromSource>
        List of sources to populate environment variables in the container. The keys
        defined within a source must be a C_IDENTIFIER. All invalid keys will be
        reported as an event when the container is starting. When a key exists in
        multiple sources, the value associated with the last source will take
        precedence. Values defined by an Env with a duplicate key will take
        precedence. Cannot be updated.
    
      image <string>
        Container image name. More info:
        https://kubernetes.io/docs/concepts/containers/images This field is optional
        to allow higher level config management to default or override container
        images in workload controllers like Deployments and StatefulSets.
    
      imagePullPolicy       <string>
        Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if
        :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More
        info: https://kubernetes.io/docs/concepts/containers/images#updating-images
    
        Possible enum values:
         - `"Always"` means that kubelet always attempts to pull the latest image.
        Container will fail If the pull fails.
         - `"IfNotPresent"` means that kubelet pulls if the image isn't present on
        disk. Container will fail if the image isn't present and the pull fails.
         - `"Never"` means that kubelet never pulls an image, but only uses a local
        image. Container will fail if the image isn't present
    
      lifecycle     <Lifecycle>
        Actions that the management system should take in response to container
        lifecycle events. Cannot be updated.
    
      livenessProbe <Probe>
        Periodic probe of container liveness. Container will be restarted if the
        probe fails. Cannot be updated. More info:
        https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
    
      name  <string> -required-
        Name of the container specified as a DNS_LABEL. Each container in a pod must
        have a unique name (DNS_LABEL). Cannot be updated.
    
      ports <[]ContainerPort>
        List of ports to expose from the container. Not specifying a port here DOES
        NOT prevent that port from being exposed. Any port which is listening on the
        default "0.0.0.0" address inside a container will be accessible from the
        network. Modifying this array with strategic merge patch may corrupt the
        data. For more information See
        https://github.com/kubernetes/kubernetes/issues/108255. Cannot be updated.
    
      readinessProbe        <Probe> 就是一个纯对象
      			readinessProbe:
      			  exec:
      			    command: 
      			    - /bin/calico-node
      			    - -felix-ready
      			    - -bird-ready
      
        Periodic probe of container service readiness. Container will be removed
        from service endpoints if the probe fails. Cannot be updated. More info:
        https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
    
      resizePolicy  <[]ContainerResizePolicy>
        Resources resize policy for the container.
    
      resources     <ResourceRequirements>
        Compute Resources required by this container. Cannot be updated. More info:
        https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/
    
      restartPolicy <string>
        RestartPolicy defines the restart behavior of individual containers in a
        pod. This field may only be set for init containers, and the only allowed
        value is "Always". For non-init containers or when this field is not
        specified, the restart behavior is defined by the Pod's restart policy and
        the container type. Setting the RestartPolicy as "Always" for the init
        container will have the following effect: this init container will be
        continually restarted on exit until all regular containers have terminated.
        Once all regular containers have completed, all init containers with
        restartPolicy "Always" will be shut down. This lifecycle differs from normal
        init containers and is often referred to as a "sidecar" container. Although
        this init container still starts in the init container sequence, it does not
        wait for the container to complete before proceeding to the next init
        container. Instead, the next init container starts immediately after this
        init container is started, or after any startupProbe has successfully
        completed.
    
      securityContext       <SecurityContext>
        SecurityContext defines the security options the container should be run
        with. If set, the fields of SecurityContext override the equivalent fields
        of PodSecurityContext. More info:
        https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
    
      startupProbe  <Probe>
        StartupProbe indicates that the Pod has successfully initialized. If
        specified, no other probes are executed until this completes successfully.
        If this probe fails, the Pod will be restarted, just as if the livenessProbe
        failed. This can be used to provide different probe parameters at the
        beginning of a Pod's lifecycle, when it might take a long time to load data
        or warm a cache, than during steady-state operation. This cannot be updated.
        More info:
        https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
    
      stdin <boolean>
        Whether this container should allocate a buffer for stdin in the container
        runtime. If this is not set, reads from stdin in the container will always
        result in EOF. Default is false.
    
      stdinOnce     <boolean>
        Whether the container runtime should close the stdin channel after it has
        been opened by a single attach. When stdin is true the stdin stream will
        remain open across multiple attach sessions. If stdinOnce is set to true,
        stdin is opened on container start, is empty until the first client attaches
        to stdin, and then remains open and accepts data until the client
        disconnects, at which time stdin is closed and remains closed until the
        container is restarted. If this flag is false, a container processes that
        reads from stdin will never receive an EOF. Default is false
    
      terminationMessagePath        <string>
        Optional: Path at which the file to which the container's termination
        message will be written is mounted into the container's filesystem. Message
        written is intended to be brief final status, such as an assertion failure
        message. Will be truncated by the node if greater than 4096 bytes. The total
        message length across all containers will be limited to 12kb. Defaults to
        /dev/termination-log. Cannot be updated.
    
      terminationMessagePolicy      <string>
        Indicate how the termination message should be populated. File will use the
        contents of terminationMessagePath to populate the container status message
        on both success and failure. FallbackToLogsOnError will use the last chunk
        of container log output if the termination message file is empty and the
        container exited with an error. The log output is limited to 2048 bytes or
        80 lines, whichever is smaller. Defaults to File. Cannot be updated.
    
        Possible enum values:
         - `"FallbackToLogsOnError"` will read the most recent contents of the
        container logs for the container status message when the container exits
        with an error and the terminationMessagePath has no contents.
         - `"File"` is the default behavior and will set the container status
        message to the contents of the container's terminationMessagePath when the
        container exits.
    
      tty   <boolean>
        Whether this container should allocate a TTY for itself, also requires
        'stdin' to be true. Default is false.
    
      volumeDevices <[]VolumeDevice>
        volumeDevices is the list of block devices to be used by the container.
    
      volumeMounts  <[]VolumeMount>
        Pod volumes to mount into the container's filesystem. Cannot be updated.
    
      workingDir    <string>
        Container's working directory. If not specified, the container runtime's
        default will be used, which might be configured in the container image.
        Cannot be updated.
    
    
    root@k8s-master-10:~#
    -------------------------------------------------------------------------------------
    root@k8s-master-10:~# kubectl explain pod.spec.containers.ports
    KIND:       Pod
    VERSION:    v1
    
    FIELD: ports <[]ContainerPort>
    
    DESCRIPTION:
        List of ports to expose from the container. Not specifying a port here DOES
        NOT prevent that port from being exposed. Any port which is listening on the
        default "0.0.0.0" address inside a container will be accessible from the
        network. Modifying this array with strategic merge patch may corrupt the
        data. For more information See
        https://github.com/kubernetes/kubernetes/issues/108255. Cannot be updated.
        ContainerPort represents a network port in a single container.
    
    FIELDS:
      containerPort <integer> -required-
        Number of port to expose on the pod's IP address. This must be a valid port
        number, 0 < x < 65536.
    
      hostIP        <string>
        What host IP to bind the external port to.
    
      hostPort      <integer>
        Number of port to expose on the host. If specified, this must be a valid
        port number, 0 < x < 65536. If HostNetwork is specified, this must match
        ContainerPort. Most containers do not need this.
    
      name  <string>
        If specified, this must be an IANA_SVC_NAME and unique within the pod. Each
        named port in a pod must have a unique name. Name for the port that can be
        referred to by services.
    
      protocol      <string>
        Protocol for port. Must be UDP, TCP, or SCTP. Defaults to "TCP".
    
        Possible enum values:
         - `"SCTP"` is the SCTP protocol.
         - `"TCP"` is the TCP protocol.
         - `"UDP"` is the UDP protocol.
    
    
    root@k8s-master-10:~#
    
    root@k8s-master-10:~# kubectl explain --help
    
    Describe fields and structure of various resources.
    
     This command describes the fields associated with each supported API resource. Fields are identified via a simple
    JSONPath identifier:
    
            <type>.<fieldName>[.<fieldName>]
    
     Information about each field is retrieved from the server in OpenAPI format.
    
    Use "kubectl api-resources" for a complete list of supported resources.
    
    Examples:
      # Get the documentation of the resource and its fields
      kubectl explain pods
    
      # Get all the fields in the resource
      kubectl explain pods --recursive
    
      # Get the explanation for deployment in supported api versions
      kubectl explain deployments --api-version=apps/v1
    
      # Get the documentation of a specific field of a resource
      kubectl explain pods.spec.containers
    
      # Get the documentation of resources in different format
      kubectl explain deployment --output=plaintext-openapiv2
    
    Options:
        --api-version='':
            Use given api-version (group/version) of the resource.
    
        --output='plaintext':
            Format in which to render the schema. Valid values are: (plaintext, plaintext-openapiv2).
    
        --recursive=false:
            When true, print the name of all the fields recursively. Otherwise, print the available fields with their
            description.
    
    Usage:
      kubectl explain TYPE [--recursive=FALSE|TRUE] [--api-version=api-version-group]
    [--output=plaintext|plaintext-openapiv2] [options]
    
    Use "kubectl options" for a list of global command-line options (applies to all commands).
    root@k8s-master-10:~/calico-3.27.3/manifests#
    
    kubectl explain deployment.spec
    # 关于 deployment 资源配置参数
    root@k8s-master-10:~# kubectl explain deployment.spec
    GROUP:      apps
    KIND:       Deployment
    VERSION:    v1
    
    FIELD: spec <DeploymentSpec>
    
    DESCRIPTION:
        Specification of the desired behavior of the Deployment.
        DeploymentSpec is the specification of the desired behavior of the
        Deployment.
    
    FIELDS:
      minReadySeconds       <integer>
        Minimum number of seconds for which a newly created pod should be ready
        without any of its container crashing, for it to be considered available.
        Defaults to 0 (pod will be considered available as soon as it is ready)
    
      paused        <boolean>
        Indicates that the deployment is paused.
    
      progressDeadlineSeconds       <integer>
        The maximum time in seconds for a deployment to make progress before it is
        considered to be failed. The deployment controller will continue to process
        failed deployments and a condition with a ProgressDeadlineExceeded reason
        will be surfaced in the deployment status. Note that progress will not be
        estimated during the time a deployment is paused. Defaults to 600s.
    
      replicas      <integer>   # 定义 deployment 有几个副本
        Number of desired pods. This is a pointer to distinguish between explicit
        zero and not specified. Defaults to 1.
    
      revisionHistoryLimit  <integer>
        The number of old ReplicaSets to retain to allow rollback. This is a pointer
        to distinguish between explicit zero and not specified. Defaults to 10.
    
      selector      <LabelSelector> -required-	# 定义 deployment 的标签选择器
        Label selector for pods. Existing ReplicaSets whose pods are selected by
        this will be the ones affected by this deployment. It must match the pod
        template's labels.
    
      strategy      <DeploymentStrategy>
        The deployment strategy to use to replace existing pods with new ones.
    
      template      <PodTemplateSpec> -required- 
      # 定义 deployment 的 template,就是定义 pod 相关的
        Template describes the pods that will be created. The only allowed
        template.spec.restartPolicy value is "Always".
    
    
    root@k8s-master-10:~#
    
    root@k8s-master-10:~# kubectl explain deployment.spec.template
    GROUP:      apps
    KIND:       Deployment
    VERSION:    v1
    
    FIELD: template <PodTemplateSpec>	
    # 就是定义 pod 资源配置选项 
    # 因为 deployment 是管理 pod 的 就不用单独去定义 pod 直接生成
    ----------------------------------------------
    apiVersion: v1
    kind: Pod
    metadata:
      labels: 
        key: value
      name: ""
      namespace: ""
    spec:
      containers:
      - image: ""
        imagePullPolicy: "Always|ifNotPresent|Never"
        name: ""
        args: []
        command: []
        ports: []
        env: []
        resources: {}
        livenessProbe: {}
        readinessProbe: {}
        startupProbe: {}
        volumeMounts: {}
        securityContext: {}
        lifecycle: {}
      volumes: []
    ----------------------------------------------
    
    DESCRIPTION:
        Template describes the pods that will be created. The only allowed
        template.spec.restartPolicy value is "Always".
        PodTemplateSpec describes the data a pod should have when created from a
        template
    
    FIELDS:
      metadata      <ObjectMeta>
        Standard object's metadata. More info:
        https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
    
      spec  <PodSpec>
        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
        
        
        kubectl explain deployment.spec.template.spec
     root@k8s-master-10:~# kubectl explain deployment.spec.template.spec
    GROUP:      apps
    KIND:       Deployment
    VERSION:    v1
    
    FIELD: spec <PodSpec>
    
     # 此时就与容器的spec 对等了
     ------------------------------
     apiVersion: v1
    kind: Pod
    metadata:
      labels: 
        key: value
      name: ""
      namespace: ""
    spec:
      containers:
      - image: ""
        imagePullPolicy: "Always|ifNotPresent|Never"
        name: ""
        args: []
        command: []
        ports: []
        env: []
        resources: {}
        livenessProbe: {}
        readinessProbe: {}
        startupProbe: {}
        volumeMounts: {}
        securityContext: {}
        lifecycle: {}
      volumes: []
     ------------------------------
     
    # 因为 deployment 管理 pod ,所以deployment与pod的 containers 字段是一模一样的
    root@k8s-master-10:~# kubectl explain deployment.spec.template.spec.containers
    
    root@k8s-master-10:~# kubectl explain deployment.spec.template.spec.containers
    GROUP:      apps
    KIND:       Deployment
    VERSION:    v1
    
    FIELD: containers <[]Container>
    
    DESCRIPTION:
        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.
        A single application container that you want to run within a pod.
    
    FIELDS:
      args  <[]string>
        Arguments to the entrypoint. The container image's CMD is used if this is
        not provided. Variable references $(VAR_NAME) are expanded using the
        container's environment. If a variable cannot be resolved, the reference in
        the input string will be unchanged. Double $$ are reduced to a single $,
        which allows for escaping the $(VAR_NAME) syntax: i.e. "$$(VAR_NAME)" will
        produce the string literal "$(VAR_NAME)". Escaped references will never be
        expanded, regardless of whether the variable exists or not. Cannot be
        updated. More info:
        https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell
    
      command       <[]string>
        Entrypoint array. Not executed within a shell. The container image's
        ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME)
        are expanded using the container's environment. If a variable cannot be
        resolved, the reference in the input string will be unchanged. Double $$ are
        reduced to a single $, which allows for escaping the $(VAR_NAME) syntax:
        i.e. "$$(VAR_NAME)" will produce the string literal "$(VAR_NAME)". Escaped
        references will never be expanded, regardless of whether the variable exists
        or not. Cannot be updated. More info:
        https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell
    
      env   <[]EnvVar>
        List of environment variables to set in the container. Cannot be updated.
    
      envFrom       <[]EnvFromSource>
        List of sources to populate environment variables in the container. The keys
        defined within a source must be a C_IDENTIFIER. All invalid keys will be
        reported as an event when the container is starting. When a key exists in
        multiple sources, the value associated with the last source will take
        precedence. Values defined by an Env with a duplicate key will take
        precedence. Cannot be updated.
    
      image <string>
        Container image name. More info:
        https://kubernetes.io/docs/concepts/containers/images This field is optional
        to allow higher level config management to default or override container
        images in workload controllers like Deployments and StatefulSets.
    
      imagePullPolicy       <string>
        Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if
        :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More
        info: https://kubernetes.io/docs/concepts/containers/images#updating-images
    
        Possible enum values:
         - `"Always"` means that kubelet always attempts to pull the latest image.
        Container will fail If the pull fails.
         - `"IfNotPresent"` means that kubelet pulls if the image isn't present on
        disk. Container will fail if the image isn't present and the pull fails.
         - `"Never"` means that kubelet never pulls an image, but only uses a local
        image. Container will fail if the image isn't present
    
      lifecycle     <Lifecycle>
        Actions that the management system should take in response to container
        lifecycle events. Cannot be updated.
    
      livenessProbe <Probe>
        Periodic probe of container liveness. Container will be restarted if the
        probe fails. Cannot be updated. More info:
        https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
    
      name  <string> -required-
        Name of the container specified as a DNS_LABEL. Each container in a pod must
        have a unique name (DNS_LABEL). Cannot be updated.
    
      ports <[]ContainerPort>
        List of ports to expose from the container. Not specifying a port here DOES
        NOT prevent that port from being exposed. Any port which is listening on the
        default "0.0.0.0" address inside a container will be accessible from the
        network. Modifying this array with strategic merge patch may corrupt the
        data. For more information See
        https://github.com/kubernetes/kubernetes/issues/108255. Cannot be updated.
    
      readinessProbe        <Probe>
        Periodic probe of container service readiness. Container will be removed
        from service endpoints if the probe fails. Cannot be updated. More info:
        https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
    
      resizePolicy  <[]ContainerResizePolicy>
        Resources resize policy for the container.
    
      resources     <ResourceRequirements>
        Compute Resources required by this container. Cannot be updated. More info:
        https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/
    
      restartPolicy <string>
        RestartPolicy defines the restart behavior of individual containers in a
        pod. This field may only be set for init containers, and the only allowed
        value is "Always". For non-init containers or when this field is not
        specified, the restart behavior is defined by the Pod's restart policy and
        the container type. Setting the RestartPolicy as "Always" for the init
        container will have the following effect: this init container will be
        continually restarted on exit until all regular containers have terminated.
        Once all regular containers have completed, all init containers with
        restartPolicy "Always" will be shut down. This lifecycle differs from normal
        init containers and is often referred to as a "sidecar" container. Although
        this init container still starts in the init container sequence, it does not
        wait for the container to complete before proceeding to the next init
        container. Instead, the next init container starts immediately after this
        init container is started, or after any startupProbe has successfully
        completed.
    
      securityContext       <SecurityContext>
        SecurityContext defines the security options the container should be run
        with. If set, the fields of SecurityContext override the equivalent fields
        of PodSecurityContext. More info:
        https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
    
      startupProbe  <Probe>
        StartupProbe indicates that the Pod has successfully initialized. If
        specified, no other probes are executed until this completes successfully.
        If this probe fails, the Pod will be restarted, just as if the livenessProbe
        failed. This can be used to provide different probe parameters at the
        beginning of a Pod's lifecycle, when it might take a long time to load data
        or warm a cache, than during steady-state operation. This cannot be updated.
        More info:
        https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
    
      stdin <boolean>
        Whether this container should allocate a buffer for stdin in the container
        runtime. If this is not set, reads from stdin in the container will always
        result in EOF. Default is false.
    
      stdinOnce     <boolean>
        Whether the container runtime should close the stdin channel after it has
        been opened by a single attach. When stdin is true the stdin stream will
        remain open across multiple attach sessions. If stdinOnce is set to true,
        stdin is opened on container start, is empty until the first client attaches
        to stdin, and then remains open and accepts data until the client
        disconnects, at which time stdin is closed and remains closed until the
        container is restarted. If this flag is false, a container processes that
        reads from stdin will never receive an EOF. Default is false
    
      terminationMessagePath        <string>
        Optional: Path at which the file to which the container's termination
        message will be written is mounted into the container's filesystem. Message
        written is intended to be brief final status, such as an assertion failure
        message. Will be truncated by the node if greater than 4096 bytes. The total
        message length across all containers will be limited to 12kb. Defaults to
        /dev/termination-log. Cannot be updated.
    
      terminationMessagePolicy      <string>
        Indicate how the termination message should be populated. File will use the
        contents of terminationMessagePath to populate the container status message
        on both success and failure. FallbackToLogsOnError will use the last chunk
        of container log output if the termination message file is empty and the
        container exited with an error. The log output is limited to 2048 bytes or
        80 lines, whichever is smaller. Defaults to File. Cannot be updated.
    
        Possible enum values:
         - `"FallbackToLogsOnError"` will read the most recent contents of the
        container logs for the container status message when the container exits
        with an error and the terminationMessagePath has no contents.
         - `"File"` is the default behavior and will set the container status
        message to the contents of the container's terminationMessagePath when the
        container exits.
    
      tty   <boolean>
        Whether this container should allocate a TTY for itself, also requires
        'stdin' to be true. Default is false.
    
      volumeDevices <[]VolumeDevice>
        volumeDevices is the list of block devices to be used by the container.
    
      volumeMounts  <[]VolumeMount>
        Pod volumes to mount into the container's filesystem. Cannot be updated.
    
      workingDir    <string>
        Container's working directory. If not specified, the container runtime's
        default will be used, which might be configured in the container image.
        Cannot be updated.
    
    
    root@k8s-master-10:~#
    

    如何查看参数?如何使用 help?

  • kubectl create deployment --help
    
    root@k8s-master-10:~# kubectl create deployment --help
    Create a deployment with the specified name.
    
    Aliases:
    deployment, deploy
    
    Examples:
      # Create a deployment named my-dep that runs the busybox image
      kubectl create deployment my-dep --image=busybox
    
      # Create a deployment with a command
      kubectl create deployment my-dep --image=busybox -- date
    
      # Create a deployment named my-dep that runs the nginx image with 3 replicas
      kubectl create deployment my-dep --image=nginx --replicas=3
    
      # Create a deployment named my-dep that runs the busybox image and expose port 5701
      kubectl create deployment my-dep --image=busybox --port=5701
    
    Options:
        --allow-missing-template-keys=true:
            If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to
            golang and jsonpath output formats.
    
        --dry-run='none':
            Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without
            sending it. If server strategy, submit server-side request without persisting the resource.
    
        --field-manager='kubectl-create':
            Name of the manager used to track field ownership.
    
        --image=[]:
            Image names to run.
    
        -o, --output='':
            Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath,
            jsonpath-as-json, jsonpath-file).
    
        --port=-1:
            The port that this container exposes.
    
        -r, --replicas=1:
            Number of replicas to create. Default is 1.
    
        --save-config=false:
            If true, 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 object in the future.
    
        --show-managed-fields=false:
            If true, keep the managedFields when printing objects in JSON or YAML format.
    
        --template='':
            Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format
            is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
    
        --validate='strict':
            Must be one of: strict (or true), warn, ignore (or false).              "true" or "strict" will use a schema to validate
            the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation
            is enabled on the api-server, but will fall back to less reliable client-side validation if not.                "warn" will
            warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled
            on the API server, and behave as "ignore" otherwise.            "false" or "ignore" will not perform any schema
            validation, silently dropping any unknown or duplicate fields.
    
    Usage:
      kubectl create deployment NAME --image=image -- [COMMAND] [args...] [options]
    
    Use "kubectl options" for a list of global command-line options (applies to all commands).
    root@k8s-master-10:~#
    

    如何快速获取所需的 YAML 文件

    dry-run 可以快速获取所需的 YAML 文件

  • kubectl create deployment web666 --image=nginx --replicas=3 -n test --dry-run=client/server   通常我们使用 client
    
    
    通常我们会用这个命令帮我们导出一个 YAML 文件,通过 yaml 文件部署我们复杂的应用
    
    'web666' : 生成一个'deployment'应用名称 web666
    '--image=nginx' : 指定镜像名称
    '--replicas=3' : 指定副本数
    '-n': 指定命名空间
    '-o' :可以输出指定的yaml格式,能够快速获取所需的 YAML 文件
    '--dry-run' 有两个参数 一个是 client(--dry-run=client) 一个是 server(--dry-run=server) 他是尝试运行,并不实际运行,可以作测试,你是在 client 去验证这个命令还是在 server 层面去验证这个命令,dry-run 内置效验这种能力。通常情况下使用 client 
    
    # 执行这条命令是不会输出任何东西的
    kubectl create deployment web666 --image=nginx --replicas=3 -n test --dry-run=client
    
    # 增加一个'-o'参数,就可以输出 YAML 文件
    kubectl create deployment web666 --image=nginx --replicas=3 -n test --dry-run=client -o yaml
    
    # '> deployment.yaml' 该参数是将生成的 yaml 文件 导出到 'deployment.yaml'中
    
    3. root@k8s-master-10:~# kubectl create deployment web666 --image=nginx --replicas=3 -n test --dry-run=client -o yaml > deployment.yaml
    root@k8s-master-10:~#
    
    
    1. root@k8s-master-10:~# kubectl create deployment web666 --image=nginx --replicas=3 -n test --dry-run=client
    deployment.apps/web666 created (dry run)
    
    2. root@k8s-master-10:~# kubectl create deployment web666 --image=nginx --replicas=3 -n test --dry-run=client -o yaml
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      creationTimestamp: null
      labels:
        app: web666
      name: web666
      namespace: test
    spec:
      replicas: 3
      selector:
        matchLabels:
          app: web666
      strategy: {}
      template:
        metadata:
          creationTimestamp: null
          labels:
            app: web666
        spec:
          containers:
          - image: nginx
            name: nginx
            resources: {}
    status: {}
    root@k8s-master-10:~#
    
    

    VSCode工具生成和编写

    VSCode安装扩展:

  • Kubernetes-Templates: 帮助你轻松地编辑和管理 Kubernetes YAML文件

  • YAML: 提供 YAML 的语法高亮,格式化和验证。

    如图所示已经安装好 kubernetes-Templates 和 YAML 插件

我们在 vscode 中新创建一个空白的 yaml 文件,在 编辑器 里面的 yaml 文件区域输入 k8s 会出现如下图所示

我们可以选择我们需要生成的 yaml 文件 比如我们选择'k8sjob' 回车,得到如下 yaml 文件

然后我们在修改相应的名称,标签,一些数据等,改成我们需要的参数就可以,这样 yaml 文件编写就非常轻松了。其实本质就是代码补全命令。

YAML语法检查系统

YAML 语法检查网址:YAML Validator Online to validate YAML data

输入自己写的 yaml 文件,工具自动检查出哪里有错误,如下图粉红色提示的内容有错误

  • 10
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值