What is a YAML file?
A YAML file is used to represent data, in case of Kubernetes it is configuration data. The other formats in which data can be represented are XML and JSON.
In this article I will explain you about the different elements types for the YAML files.
In YAML files, key-value pairs are used to define attributes and settings for various data structures.
There are different types of key-value pairs that can exist in YAML files, depending on the context and the type of data being represented.
Here are the common types of key-value pairs you may encounter:
- Scalar Key-Value Pair:
This is the most basic type of key-value pair, where a single value is associated with a specific key. The value can be a string, number, boolean, or null.
Remember that you need to have a space between the colon and value.
key: value
Example:
name: John Doe
age: 30
is_active: true
- Mapping Key-Value Pair or Dictionary:
A mapping key-value pair is used to associate a key with another nested data structure, such as another key-value pair, a list, or another mapping.
key:
nested_key: nested_value
As you can see in the example below, the name, age and address are the properties of the person. But address is another mapping key with sub properties such as city and country.
Example:
person:
name: John Doe
age: 30
address:
city: New York
country: USA
- List Key-Value Pair:
Lists in YAML represent sequences of values and are denoted by a hyphen followed by a space (“- “). Lists can contain various data types, including strings, numbers, booleans, and other lists.
The “-” represents that it is an elements of an array.
key:
- value1
- value2
- value3
Example:
fruits:
- apple
- orange
- banana
vegetables:
- Carrot
- Ladyfinger
- Potato
Kubernetes YAML file
- A Kubernetes YAML file contains four top-level properties:
apiVersion
,kind
,metadata
, andspec
. apiVersion
specifies the version of the Kubernetes API to use.kind
specifies the type of Kubernetes object being defined.metadata
contains information about the object such as its name.spec
contains the desired state of the object.
Here is an example of a Kubernetes YAML file defining a deployment:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.14.2
ports:
- containerPort: 80
In this example,apiVersion
is set toapps/v1
to use theapps
API group,kind
is set toDeployment
to define a deployment object,metadata
specifies the name of the deployment asnginx-deployment
, andspec
specifies that there should be 3 replicas of the deployment, each running thenginx:1.14.2
container image and exposing port 80.