Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to YAML Syntax

What is YAML?

YAML (YAML Ain't Markup Language) is a human-readable data serialization standard that can be used in conjunction with all programming languages and is often used to write configuration files. YAML emphasizes human readability and uses a minimalistic syntax which makes it easy to read and write.

Basic Syntax

YAML uses indentation to indicate nesting, and it does not allow the use of tab characters for indentation; spaces must be used. The basic data structures in YAML are:

  • Scalars (strings, numbers, booleans)
  • Sequences (arrays/lists)
  • Mappings (hashes/dictionaries)

Scalars

Scalars are the most basic data type in YAML. They represent a single value and can be strings, numbers, or booleans.

name: John Doe
age: 30
is_student: false

In the example above, name is a string, age is a number, and is_student is a boolean.

Sequences

Sequences in YAML are lists of items. Each item in a sequence is prefixed with a dash and a space.

fruits:
  - Apple
  - Banana
  - Orange

In this example, fruits is a sequence containing three items: "Apple", "Banana", and "Orange".

Mappings

Mappings in YAML are collections of key-value pairs. Each key-value pair is separated by a colon and a space.

person:
  name: John Doe
  age: 30
  occupation: Developer

In this example, person is a mapping containing three key-value pairs: "name", "age", and "occupation".

Nested Structures

YAML allows nesting of sequences and mappings to represent more complex data structures.

employees:
  - name: John Doe
    age: 30
    role: Developer
  - name: Jane Smith
    age: 25
    role: Designer

In this example, employees is a sequence of mappings, each representing an employee with their respective details.

Comments

Comments in YAML are denoted by the # character. Everything on the line after the # character is considered a comment.

name: John Doe # This is a comment
age: 30 # Another comment

Example: Ansible Playbook

Below is an example of an Ansible playbook written in YAML. Ansible uses YAML to define automation tasks in a human-readable format.

- name: Install and start Apache
  hosts: webservers
  become: yes
  tasks:
    - name: Install Apache
      yum:
        name: httpd
        state: present

    - name: Start Apache
      service:
        name: httpd
        state: started

In this example, the playbook installs and starts the Apache HTTP server on all hosts in the "webservers" group.