This is the 6th day of my participation in the August More Text Challenge

First, YAML concept

I encountered YAML a lot in daily operation and maintenance work. For example, I wrote Ansible Playbook and used YAML to define and create various applications and services.

1.1 concept

YAML (pronounced /ˈjæməl/) is a data serialization language similar to XML and JSON. YAML is specially designed to write configuration files. It is very simple and powerful, and is more convenient to use than JSON. It is essentially a universal data serialization format. Its emphasis on data as the center, designed to facilitate human use; And modern programming languages for everyday common tasks. Thus YAML itself is relatively simple to define and claims to be “a user-friendly data format language.”

1.2 the advantages

  • Convenience: You don’t have to add a lot of arguments to the command line to execute a command
  • Maintainability: YAML files can track every operation by controlling the source
  • Flexibility: YAML can create structures that are more complex than the command line
  • Simplicity: Easy to use

1.3 Grammar Rules

  • Case sensitivity
  • Use indentation to indicate hierarchy
  • Indent does not allow Tab, only Spaces
  • The number of indent Spaces does not matter, as long as elements of the same rank are aligned to the left
  • # comment

1.4 Organization Structure

Use “–” (three horizontal lines) at the beginning of each document as a separator between documents. Documents can also use “…” (Three dots) as terminator (optional)

Second, structure type

2.1 Maps type

Map is a dictionary and a pair of key:value pairs, for example

---
apiVersion: v1
kind: Pod
Copy the code

The first line, which is an optional delimiter, can be used in a single file with three consecutive hyphens to distinguish multiple files. Here we can see that we have two keys: kind and apiVersion, with values v1 and Pod, respectively. If you convert the above YAML file to JSON format, you can easily understand this:

{
    "apiVersion": "v1",
    "kind": "pod"
}
Copy the code

In the YAML file above, the metadata KEY is a Map, and the nested labels KEY is a Map. You can nest layers of labels according to your own situation.

We also mentioned the syntax of YAML files. The YAML processor knows the correlation between contents based on line indentation. For example, in our YAML file above, I used two Spaces for indentation. The number of Spaces is not important, but you need to be consistent and require at least one space (what does that mean? Don’t indent two Spaces at a time, four Spaces at a time). We can see that name and labels are indent at the same level, so the YAML processor knows that they belong to the same MAP, and app is the indent of labels because app has a larger indent.

Similarly, we can convert the YAML file above to JSON:

{
    "apiVersion": "v1",
    "kind": "Pod",
    "metadata": {
        "name": "kube100-site",
        "labels": {
            "app": "web"
        }
    }
}
Copy the code

2.2 Lists type

The List as an array

args
  - Cat
  - Dog
  - Fish
Copy the code

You can have any number of items in the list, and the definition of each item begins with a dash (-), with the parent element directly indented by a space. The corresponding JSON format is as follows:

{
    "args": [ 'Cat', 'Dog', 'Fish' ]
}
Copy the code

2.3 Mixed Types

---
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
Copy the code

As shown in the above file, define a containers List object, each of which is composed of name, image, and ports, each of which is composed of a Map with a containerPort KEY, which is converted into a JSON format file:

{
  "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": [{
                "containerPort": "5000"
            }]
        }]
  }
}
Copy the code

Explain the yamL file above:

  • ApiVersion: The value here is v1. This version number needs to change depending on the installed Kubernetes version and resource type
  • Kind: Pod is created here. The resource type can be Deployment, Job, Ingress, Service, etc
  • Metadata: Contains meta information about the Pod we defined, such as name, namespace, lebal, etc.
  • Spec: Includes some containers, storage, volumes, or other parameters that Kubernetes needs to know, as well as properties such as whether to restart the container if it fails. You can find the full Kubernetes Pod properties in the specific Kubernetes API.

Containers settable properties:

name
image
command
args
workingDir
ports
env
resources
volumeMounts
livenessProbe
readinessProbe
livecycle
terminationMessagePath
imagePullPolicy
securityContext
stdin
stdinOnce
tty
Copy the code

Yaml file instance

  • k8s
Kind: Pod # Specifies the role/type to create the resource metadata: # Specifies the resource metadata/attribute name: Web04-pod # name of the resource, must have a unique labels in the same namespace: # set resource tag. For details, please see http://blog.csdn.net/liyingke112/article/details/77482384 k8s - app: apache version: Annotations v1 kubernetes. IO /cluster-service: "true" Annotations: Spec :#specification of the resource Content restartPolicy: Always # indicates that the container is Always running, default k8S policy, after this container exits, an identical container nodeSelector is created immediately: Kubectl label nodes kube-node1 zone=node1 zone: node1 containers: - name: web04-pod ImagePullPolicy: Select Always, Never, IfNotPresent, check and update (from registery) images' policy on each startup. # IfNotPresent not checked every time (whether there is a local one or not) # IfNotPresent not checked if there is a local one, pull command if not: ["$(STR)"] # env = Entrypoint; /etc/run.sh/resources: # resources management, request, please see http://blog.csdn.net/liyingke112/article/details/77452630 requests: # container is running, the minimum resource requirements, that is to say the least need how many containers to normal operation of the CPU resources: 0.1 #CPU resources (number of cores), either floating-point or integer +m, 0.1=100m, minimum 0.001 cores (1m) -containerPort: 80 # Port name: HTTPD # protocol: TCP livenessProbe: # pod container within health check Settings, see http://blog.csdn.net/liyingke112/article/details/77531584 httpGet: Port: 80 #host: 127.0.0.1 # Scheme: HTTP initialDelaySeconds: TimeoutSeconds timeoutSeconds: 5 # Timeout period of detection periodSeconds: 15 # PeriodperiodSeconds can also be used in this manner #exec: TcpSocket: // check the health of the container by tcpSocket: // check the health of the container by tcpSocket: // check the health of the container by tcpSocket # yum lifecycle: # yum lifecycle: # yum lifecycle: # yum lifecycle: # yum lifecycle: # yum lifecycle: # yum lifecycle: # yum lifecycle: # yum lifecycle Command: [' service HTTPD stop] volumeMounts: # please see http://blog.csdn.net/liyingke112/article/details/76577520 - name: Volumes [*]. Name mountPath: /data readOnly: True Volumes: # Define a cluster of mounted volumes - name: Volume # Define the name of a mounted device #meptyDir: {} hostPath: path: /opt # The mounted device type is hostPath and the path is /opt on the hostCopy the code

The corresponding JSON format

{ 'kind': 'Pod', 'spec': { 'restartPolicy': 'Always', 'containers': [ { 'livenessProbe': { 'initialDelaySeconds': 180, 'httpGet': { 'path': '/', 'scheme': 'HTTP', 'port': 80 }, 'timeoutSeconds': 5, 'periodSeconds': 15 }, 'name': 'web04-pod', 'image': 'web:apache', 'args': [ '$(str)' ], 'volumeMounts': [ { 'readOnly': True, 'mountPath': '/data', 'name': 'volume' } ], 'ports': [ { 'protocol': 'TCP', 'containerPort': 80, 'name': 'httpd' } ], 'command': [ 'sh' ], 'env': [ { 'name': 'str', 'value': '/etc/run.sh' } ], 'imagePullPolicy': 'Never', 'lifecycle': { 'preStop': { 'exec': { 'command': [ 'service httpd stop' ] } }, 'postStart': { 'exec': { 'command': [' sh ', 'yum upgrade - y']}}}, 'resources' : {' requests: {' CPU' : 0.1, 'memory' : '32 mi'}, 'limits: {' CPU' : 0.5, 'memory' : '32 mi'}}}], 'volumes: [{' hostPath: {' path:'/opt '}, 'name' : 'volume'}], 'nodeSelector' : { 'zone': 'node1' } }, 'apiVersion': 'v1', 'metadata': { 'labels': { 'k8s-app': 'apache', 'version': 'v1', 'kubernetes.io/cluster-service': 'true' }, 'name': 'web04-pod', 'annotations': [ { 'name': 'String' } ] } }Copy the code
  • ansible
--- - hosts: agent # define host remote_user: root # define user to execute playbook tasks: # task-name: install mysql-server # yum: Name =mysql-server state=present # yum install mysql-server: Name = mysqld state = # started service module start mysql service - name: check the mysql service shell: ps - ef | grep mysqld # shell module to check the mysql processCopy the code

The corresponding JSON format

{
  'tasks': [
    {
      'yum': 'name=mysql-server state=present',
      'name': 'install mysql-server'
    },
    {
      'name': 'start mysql-server',
      'service': 'name=mysqld state=started'
    },
    {
      'shell': 'ps -ef |grep mysqld',
      'name': 'check mysql service'
    }
  ],
  'hosts': 'agent',
  'remote_user': 'root'
}]
Copy the code
  • Convert yamL format to JSON using Python
PIP install Pyyaml # import yaml with open('config.yaml','r') as f: content = yaml.load(f) print(content)Copy the code