Commenting in YAML files
Its human-friendly syntax has fueled the widespread use of YAML in configuration files. In particular, a thorough understanding of handling these files is helpful if you work with Kubernetes since manifests are written using the YAML format. To that end, we will answer frequently asked questions regarding comments in YAML files.
How to add comments to YAML files?
Adding comments in YAML files is simple. In fact, it's very similar to how comments work in bash scripts. You just have to use the hashtag symbol (#) at the beginning of the line you want to comment on. For example:
# Source file (this is a comment) file: - sample.yaml
In the same way, if you want to add multiple lines with comments, you just have to use a # at the beginning of each line. For example:
# Comment 1 # Comment 2 # Comment 3 some: thing
What are the types of comments in YAML files?
Unlike other languages, YAML only supports in-line comments. That said, as shown in the example above, nothing prevents you from using multiple single-line comments to create "block-level" comments.
Can you add comments to the YAML files used with Kubernetes?
The short answer is yes; you can add comments to YAML files used with Kubernetes. That said, the API server won't be able to process such comments (that's the idea of comments), so it's best practice to use annotations instead. According to the documentation,
"You can use Kubernetes annotations to attach arbitrary non-identifying metadata to objects. Clients such as tools and libraries can retrieve this metadata."
Simply put, you can use annotations to include long or short, structured or unstructured comments. The advantage is that these comments can be used as metadata, which can be helpful in use cases where using labels is inconvenient.
Let's see this concept applied in an example included in the official Kubernetes documentation:
apiVersion: v1 kind: Pod metadata: # this is a comment that will be stripped out by the API Server name: annotations-demo annotations: # this comment will be removed, but the below annotation will remain imageregistry: "https://hub.docker.com/" spec: containers: - name: nginx image: nginx:1.14.2 ports: - containerPort: 80
Notice how the Kubernetes annotation uses a key/value pair to assign the value https://hub.docker.com to imageregistry. This would not be possible using comments.
More Kubernetes reading
Using YAML with Kubernetes? Don't make the common mistake of using CPU limits!