高效编写 kubernetes-YAML文件

news2024/11/18 14:34:25

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 文件,工具自动检查出哪里有错误,如下图粉红色提示的内容有错误

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1573486.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

出门一笑, “栈” 落江横 (Java篇)

本篇会加入个人的所谓‘鱼式疯言’ ❤️❤️❤️鱼式疯言:❤️❤️❤️此疯言非彼疯言 而是理解过并总结出来通俗易懂的大白话, 小编会尽可能的在每个概念后插入鱼式疯言,帮助大家理解的. &#x1f92d;&#x1f92d;&#x1f92d;可能说的不是那么严谨.但小编初心是能让更多人…

设计模式——组合模式08

组合模式&#xff1a;把类似对象或方法组合成结构为树状的设计思路。 例如部门之间的关系。 设计模式&#xff0c;一定要敲代码理解 抽象组件 /*** author ggbond* date 2024年04月06日 08:54* 部门有&#xff1a;二级部门&#xff08;下面管三级部门&#xff09; 三级部门 &a…

12.自定义的多帧缓存架构

1.简介 在数字图像处理中&#xff0c;经常需要用到的一个架构就是多帧缓存。视频流中需要用到多帧缓存来防止帧撕裂现象&#xff0c;图像处理中也需要帧差法来做移动目标检测。因此一个多帧缓存架构在图像系统的设计中是十分重要的。 2.多帧缓存 在视频流中&#xff0c;通常不…

感染了后缀为.jayy勒索病毒如何应对?数据能够恢复吗?

导言&#xff1a; 在当今数字化的世界中&#xff0c;网络安全已经成为了每个人都需要关注的重要议题。而勒索病毒作为网络安全领域中的一大威胁&#xff0c;不断地演变和升级&#xff0c;给个人和组织带来了严重的损失和困扰。近期&#xff0c;一种名为.jayy的勒索病毒引起了广…

java数据结构与算法刷题-----LeetCode415. 字符串相加

java数据结构与算法刷题目录&#xff08;剑指Offer、LeetCode、ACM&#xff09;-----主目录-----持续更新(进不去说明我没写完)&#xff1a;https://blog.csdn.net/grd_java/article/details/123063846 文章目录 模拟小学加法运算 模拟小学加法运算 解题思路&#xff1a;时间复…

【Java设计模式】创建型——工厂方法模式

目录 背景/问题解决方案思路方案 图解简单工厂模式/静态工厂模式工厂方法模式 代码示例&#xff1a;图形工厂意图主要解决何时使用如何解决关键代码 工厂模式的优点工厂模式的缺点使用场景注意事项 背景/问题 在软件设计中&#xff0c;我们经常遇到需要创建不同类型对象的情况…

如何理解模板?

文章目录 1. 泛型编程2.函数模板2.1函数模板概念2.1函数模板格式2.3函数模板的原理2.4函数模板的实例化2.5模板参数的匹配原则 3.类模板3.1类模板的定义格式3.2类模板的实例化 1. 泛型编程 如何实现一个通用的交换函数呢&#xff1f; void Swap(int& left, int& right)…

Vue中如何使用Tailwind CSS样式?多次引用不成功?具体步骤怎么做?

一、安装Tailwind CSS和依赖 在你的Vue项目中安装Tailwind CSS及其依赖。你可以使用npm或yarn来安装。 npm install tailwindcsslatest postcsslatest autoprefixerlatest # 或者yarn add tailwindcsslatest postcsslatest autoprefixerlatest 二、初始化Tailwind CSS np…

【事务注解✈️✈️】@Transactional注解在不同参数配置下的功能实现

目录 前言 使用场景 1.单个方法层面 2.类级别使用 3.指定异常回滚 4.跨方法调用事务管理 5.只读事务 ​ 6.设置超时时间&#xff0c;超时则自动回滚 7.隔离级别设置 章末 前言 小伙伴们大家好&#xff0c;ACID&#xff08;原子性&#xff0c;一致性&#xff0c;隔离…

【WEEK6】 【DAY1】DQL查询数据-第一部分【中文版】

2024.4.1 Monday 目录 4.DQL查询数据&#xff08;重点&#xff01;&#xff09;4.1.Data Query Language查询数据语言4.2.SELECT4.2.1.语法4.2.2.实践4.2.2.1.查询字段 SELECT 字段/* FROM 表查询全部的某某查询指定字段 4.2.2.2.给查询结果或者查询的这个表起别名&#xff08…

2024免费Mac苹果解压压缩包软件BetterZip5

在2024年&#xff0c;对于Mac电脑用户来说&#xff0c;如果你想要无需解压就能快速查看压缩文档的内容&#xff0c;BetterZip是一个极佳的选择。这款软件不仅支持多种格式的压缩和解压&#xff0c;如zip、rar、7z、tar等&#xff0c;还具备丰富的功能和设置&#xff0c;包括预览…

【异常解决】Non-terminating decimal expansion; no exact representable decimal result.

Non-terminating decimal expansion; no exact representable decimal result. 一、背景描述二、异常原因三、解决方案四、RoundingMode&#xff08;舍入模式&#xff09;4.1、ROUND_UP4.2、ROUND_DOWN4.3、ROUND_CEILING4.4、ROUND_FLOOR4.5、ROUND_HALF_UP&#xff08;四舍五…

SQL语句的编写

##创建用户-建表建库 #创建一个用户名为 feng&#xff0c;允许从任何主机 % 连接&#xff0c;并使用密码 sc123456 进行身份验证的用户。 rootTENNIS 16:33 scmysql>create user feng% identified by sc123456; Query OK, 0 rows affected (0.04 sec) #创建一个名为fen…

软考113-上午题-【计算机网络】-IPv6、无线网络、Windows命令

一、IPv6 IPv6 具有长达 128 位的地址空间&#xff0c;可以彻底解决 IPv4 地址不足的问题。由于 IPv4 地址是32 位二进制&#xff0c;所能表示的IP 地址个数为 2^32 4 294 967 29640 亿&#xff0c;因而在因特网上约有 40亿个P 地址。 由 32 位的IPv4 升级至 128 位的IPv6&am…

ChromeOS 中自启动 Fcitx5 和托盘 stalonetray

ChromeOS 更新的飞快&#xff0c;旧文章的方法也老是不好用&#xff0c;找遍了也没找到很好的可以开机自启动 Linux VM 和输入法、托盘的方法。 研究了一下&#xff08;不&#xff0c;是很久&#xff09;&#xff0c;终于找到个丑陋的实现。 方法基于 ChromeOS 123.0.6312.94…

域名应该如何实名?域名应该如何备案?域名如何解析到服务器

大家好欢迎来到易极赞&#xff0c;今天我们来跟大家聊一下“域名应该如何实名以及备案”这个话题。 域名实名认证是验证域名所有者身份的过程&#xff0c;以确保域名的合法性&#xff0c;通常需要登录到域名服务商后台&#xff0c;进行域名的注册&#xff0c;注册后创建域名模…

MYSQL 锁机制 与 MVCC多版本并发

MYSQL锁机制与优化以及MVCC底层原理 锁分类 乐观锁&#xff0c;悲观锁 从性能上分为乐观锁&#xff08;版本对比,版本一致就更新&#xff0c;不一致就不更新或CAS机制&#xff09;和悲观锁&#xff08;锁住资源等待&#xff09;&#xff0c;乐观锁适合读比较多的场景&#x…

Unity和Android的交互

Unity和Android的交互 一、前言二、Android导出jar/aar包到Unity2.1 版本说明2.2 拷贝Unity的classes.jar给Android工程2.2.1 classes.jar的位置2.2.2 Android Studio创建module2.2.3 拷贝classes.jar 到 Android工程并启用 2.3 编写Android工程代码2.3.1 创建 MainActivity2.…

springboot之mybatisPlus多表查询及分页查询

文章目录 一、多表查询二、mybatis-plus条件查询三、分页查询 一、多表查询 可能会用到的注解 这里的场景是&#xff0c;查询每个用户及其所有的订单。就是查询你的id号的同时&#xff0c;把你所有的历史订单信息都拉出来。 表结构这样 CREATE TABLE User ( id INT PRIMARY…

Pytorch数据结构:GPU加速

文章目录 一、GPU加速1. 检查GPU可用性&#xff1a;2. GPU不可用需要具体查看问题3. 指定设备4.将张量和模型转移到GPU5.执行计算&#xff1a;6.将结果转移回CPU 二、转移原理1. 数据和模型的存储2. 数据传输3. 计算执行4. 设备管理5.小结 三、to方法的参数类型 一、GPU加速 .…