YAML Basic Tutorial with Examples

In this article we are going to cover YAML Basic Tutorial with Examples,YAML Indentation and Whitespace,Popular DevOps Tools Using YAML.

What is YAML?

YAML is a file extension often used for YAML (YAML Ain’t Markup Language) files. YAML is indeed a straightforward, human-readable data serialization format that is commonly used for various purposes, including configuration files, data exchange, and structured data representation. Unlike programming languages, YAML does not contain executable code but is primarily focused on efficiently representing data in a way that is easy for both humans and computers to understand.

YAML’s simplicity, readability, and flexibility have made it a popular choice in software development and other fields where data interchange and configuration management are essential. It offers an alternative to more complex and verbose formats like XML while providing similar capabilities. YAML’s human-friendly syntax makes it an excellent choice for configuration files and data interchange between different systems and languages.

In practice, YML and YAML are used interchangeably, and YML is just an abbreviation of YAML. YAML files typically have the “.yaml” or “.yml” file extension, and both extensions are used to indicate that the file contains data in YAML format.

Features and Basic Rules of YAML

It has a simple and clean syntax, which makes it easy to read and write. Here are some of the features and basic rules of YAML:

Features of YAML:

  • Human-Readable: YAML is designed to be easy for humans to read and write. Its syntax is clean and relies on indentation and minimal punctuation.
  • Whitespace Significance: Whitespace and indentation are significant in YAML. They are used to denote the structure and hierarchy of data.
  • Key-Value Pairs: YAML uses key-value pairs to represent data. Keys are followed by a colon and space, followed by the associated value.
  • Lists/Arrays: Lists or arrays are represented using hyphens (-) followed by a space for each item in the list.
  • Dictionaries/Maps: Dictionaries or maps use key-value pairs within a structured container. Key-value pairs are indented under the dictionary key.
  • Comments: Comments in YAML start with the # character and continue to the end of the line. They are for documentation purposes and are ignored by parsers.
  • Data Types: YAML supports various data types, including strings, numbers (integers and floats), booleans, null, lists, dictionaries, multi-line strings, and custom data types.
  • Multi-Line Strings: YAML allows you to represent multi-line strings using either the | character (literal style) or the > character (folded style).
  • Anchors and Aliases: YAML allows you to create references to data within the document using anchors (&) and aliases (*). This can help reduce redundancy and make complex structures more manageable.
  • Inheritance and Merging: YAML enables the merging of multiple mappings into one using the << operator.

Basic Rules of YAML:

  • Indentation: Use spaces (not tabs) for indentation. Common choices are 2 or 4 spaces per level. The number of spaces should be consistent throughout the document.
  • Colon and Space: Key-value pairs are separated by a colon followed by a space (:).
  • Single or Double Quotes: While strings can be written without quotes, you can use single or double quotes to enclose strings if they contain special characters or spaces.
  • Merging: The << operator is used to merge mappings together, allowing you to inherit values from other mappings.
  • Custom Data Types: Custom data types can be defined using tags (!) and are typically used for specific data serialization requirements.

These basic rules and features of YAML make it a versatile format for representing data and configuration information in a readable and concise manner. YAML is widely used in various applications, including configuration files, data interchange, and document markup.

What is Difference between XML vs JSON vs YAML?

XML, JSON, and YAML are three different data serialization formats, each with its own characteristics and use cases. Here’s a comparison of these formats:

XML (Extensible Markup Language):

<person>
    <name>John Doe</name>
    <age>30</age>
</person>

JSON (JavaScript Object Notation):

{
    "person": {
        "name": "John Doe",
        "age": 30
    }
}

YAML (YAML Ain’t Markup Language):

person:
      name: John Doe
      age: 30 

Choosing Between XML, JSON, and YAML:

    XML is well-suited for structured data and when you need to validate data against a schema.

    JSON is a good choice for data interchange, especially in web APIs, and is easy for both humans and machines to work with.

    YAML is ideal when human readability is a priority, such as in configuration files, and it’s also a good choice for data serialization.

Popular Tools Using YAML

YAML is commonly used in various tools and applications for configuration files and data representation. Here are some popular tools and platforms that use YAML:

  1. Docker Compose:
    • Docker Compose is a tool for defining and running multi-container Docker applications. It uses YAML files (docker-compose.yml) to define the services, networks, and volumes required for an application’s containers.
  2. Kubernetes:
    • Kubernetes, an open-source container orchestration platform, often uses YAML files (Kubernetes manifests) to define the configuration of resources like pods, services, deployments, and more.
  3. Ansible:
    • Ansible, an automation and configuration management tool, uses YAML for defining playbooks. Playbooks are used to describe the tasks that should be executed on remote servers.
  4. Jenkins:
    • Jenkins, a popular automation server, allows you to define build and deployment pipelines using Jenkinsfiles. Jenkinsfiles are often written in Groovy but can include YAML sections for configuring aspects of the pipeline.
  5. GitLab CI/CD:
    • GitLab’s Continuous Integration and Continuous Deployment (CI/CD) system uses .gitlab-ci.yml files written in YAML to define build, test, and deployment pipelines.
  6. Travis CI:
    • Travis CI is a cloud-based CI/CD service that uses .travis.yml files written in YAML to define build and test jobs for GitHub repositories.
  7. CircleCI:
    • CircleCI is another CI/CD platform that uses .circleci/config.yml files written in YAML to configure build and deployment pipelines.
  8. Terraform:
    • Terraform, an infrastructure-as-code tool, uses HCL (HashiCorp Configuration Language) for configuration. However, Terraform also supports a JSON-like format and HCL2, which can be used alongside YAML for more advanced use cases.
  9. Jupyter Notebooks:
    • Jupyter Notebook allows you to include YAML metadata at the beginning of a notebook file. This metadata can specify kernel settings, cell formatting, and more.
  10. Serverless Framework:
    • The Serverless Framework, which simplifies the deployment of serverless applications, uses serverless.yml files written in YAML to define AWS Lambda functions, events, and other resources.
  11. Prometheus:
    • Prometheus, a popular open-source monitoring and alerting system, uses YAML-based configuration files to define target endpoints, scrape intervals, and alerting rules.
  12. Helm:
    • Helm is a package manager for Kubernetes that uses YAML files to define charts, which package and deploy Kubernetes applications.
  13. CloudFormation:
    • AWS CloudFormation, Amazon’s infrastructure-as-code service, allows you to define AWS resources and their dependencies using YAML templates (in addition to JSON templates).
  14. GitHub Actions:
    • GitHub Actions uses YAML configuration files (workflow files) to define CI/CD workflows that run in response to events in GitHub repositories.

These are just a few examples of tools and platforms that leverage YAML for configuration and data representation. YAML’s simplicity and human-readability make it a versatile choice for a wide range of applications and use cases in the software development and IT operations domains.

YAML Basic Tutorial with Examples

Below we are covering YAML Basic Tutorial with Examples.

How to Create a YAML File

Creating a YAML (YML) file is a straightforward process. YAML files typically contain structured data in a human-readable format. Here are the steps to create a YAML file:

Step #1.Choose a Text Editor:

Start by choosing a text editor or code editor of your choice. You can use built-in text editors like Notepad (on Windows) or TextEdit (on macOS), or you can use more specialized editors like Visual Studio Code, Sublime Text, or Atom.

Step #2.Open the Text Editor:

Launch the chosen text editor on your computer.

Step #3.Begin Creating the YAML Content:

YAML files consist of structured data represented using indentation and simple key-value pairs. Here’s a basic example to get you started:

# Example YAML file

person:
  name: John Doe
  age: 30
  is_student: false
  hobbies:
    - Reading
    - Hiking
  address:
    street: 123 Main St
    city: Anytown

In this example, we’ve created a YAML document that contains information about a person. It includes a person’s name, age, student status, hobbies (a list), and address (a dictionary).

Step #4.Use Proper Indentation:

YAML relies on proper indentation to represent the structure of data. Use spaces (not tabs) for indentation. Common choices are 2 or 4 spaces per level of indentation.

Ensure that indentation is consistent throughout the document.

Step #5.Add Comments (Optional):

You can add comments to your YAML file by starting a line with the # character. Comments are for documentation purposes and are ignored by parsers.

Step #6.Save the File:

Save the YAML content as a file with the .yml or .yaml file extension. This convention helps identify YAML files.

Step #7.Choose a Location:

Save the YAML file in a directory or folder of your choice on your computer. Ensure that you remember the location for future reference.

Step #8.Test Your YAML File:

You can test your YAML file by using it in the context of its intended use. For example, if it’s a configuration file, you can use it with the associated software or service.

Example YAML file

person:
  name: John Doe
  age: 30
  is_student: false
  hobbies:
    - Reading
    - Hiking
  address:
    street: 123 Main St
    city: Anytown

In this example:

  • We define a dictionary named “person” with nested key-value pairs.
  • We use indentation to represent the hierarchy of data.
  • The “hobbies” key contains a list (array) of items.
  • A comment at the top provides information about the file.

Once you have created your YAML file, you can use it for configuration settings or data storage as needed.

Data types in YAML

YAML (YML) supports various data types for representing information in a human-readable and structured format. Here are the common data types in YAML:

1. Scalars:

  • Strings: Text data. They can be enclosed in single or double quotes but are often written without quotes.

Example

name: John Doe
  • Integers: Whole numbers.

Example

age: 30
  • Floats: Decimal numbers.

Example

price: 19.99
  • Booleans: true or false.

Example

is_active: true
  • Null: A special value indicating the absence of a value.

Example

description: null

2. Collections:

  • Lists/Arrays: Ordered sequences of items, indicated by a hyphen followed by a space (- ).

Example

fruits:
  - apple
  - banana
  - cherry
  • Dictionaries/Maps: Unordered collections of key-value pairs. Key-value pairs are represented using a colon and a space (:).

Example

person:
	name: John
	age: 30
  • Anchors and Aliases: YAML allows you to create references to data within the document using anchors (&) and aliases (*). This can help reduce redundancy and make complex structures more manageable.

Example

first_name: &name John
last_name: *name
  • Multi-Line Strings: You can represent multi-line strings using either the | character (literal style) or the > character (folded style). Literal style preserves newlines and indentation, while folded style folds newlines into spaces.

Example

multiline_literal: |
  This is a
  multi-line
  string in YAML.

OR

multiline_folded: >
  This is a
  multi-line
  string in YAML.
  • Custom Data Types: YAML allows you to define custom data types and tags for specialized data structures or objects. These can be used to extend YAML’s capabilities to handle domain-specific data.

Example

!myapp/custom_type
property1: value1
property2: value2
  • Timestamps: YAML provides a way to represent dates and times using the ISO 8601 format.

Example

timestamp: 2023-09-07T14:30:00Z
  • Binary Data: YAML can represent binary data using base64 encoding.

Example

binary_data: !!binary |
R0lGODlhAQABAIAAAAAAAP///
yH5BAEAAAAALAAAAAABAAEAAAIBRAA7              

These data types, along with the structured and human-readable nature of YAML, make it a versatile choice for configuration files, data serialization, and data exchange in a wide range of applications and programming languages.

YAML Indentation and Whitespace

In YAML (YML), indentation and whitespace are critical for defining the structure and hierarchy of data. Unlike some other data serialization formats, YAML relies on whitespace to represent the relationships between elements and to create a visually appealing and human-readable document. Here are some key points about YAML indentation and whitespace:

1. Indentation:

  • YAML uses spaces (not tabs) for indentation. It is recommended to use either 2 or 4 spaces per level of indentation for consistency and readability. The number of spaces must be the same for all lines within the same block.
  • Indentation indicates the nesting level of data structures. Elements with the same level of indentation are considered to be at the same hierarchical level.

2. Nested Structures:

  • To represent nested structures like dictionaries (maps) and lists (arrays), you increase the level of indentation for the nested elements.
  • For dictionaries, key-value pairs are indented relative to the containing dictionary.
  • For lists, each item in the list is indented relative to the containing list.

Example

person:
  name: John
  age: 30
  address:
    street: 123 Main St
    city: Anytown
fruits:
  - apple
  - banana
  - cherry

3. Whitespace Significance:

  • YAML is sensitive to leading whitespace. Inconsistent or incorrect indentation can result in parsing errors or data misinterpretation.
  • Whitespace is significant within multi-line strings, preserving the formatting and line breaks.

4. Blank Lines:

  • Blank lines are allowed in YAML documents and are typically ignored by parsers. They can be used to enhance readability by separating sections of the document.

Example

person:
  name: John
address:
  street: 123 Main St
  city: Anytown

Proper indentation and whitespace usage are essential in YAML to ensure that the document’s structure is accurately represented and that parsers can correctly interpret the data. YAML’s readability and ease of use are closely tied to its whitespace-based syntax, so it’s important to maintain consistent and well-formatted documents.

Conclusion:

In this article we have covered YAML Basic Tutorial with Examples,YAML Indentation and Whitespace,Popular DevOps Tools Using YAML.

Related Articles:

How to Push Maven Packages to GitLab Package Registry ?

Reference:

YAML official site

About Priti Adkine

I am Priti Adkine working as Software Engineer and having 1+ years of Experience. Likes to share knowledge.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link