quick overview on yaml


YAML: YAML Ain’t Markup Language. YAML is a data serialization language which is quite easy to read as compared to XML and JSON. It is very similar to JSON. The main advantage of YAML is human readability.  It’s is widely used to store configuration items (they can store variables, nested elements, lists, dictionaries etc). All major languages have modules/libraries to parse/read YAML files.

example: (sample configuration used in ansible playbooks)

- hosts: host1
  remote_user: ubuntu
  become: yes
  become_user: root
  become_method: sudo
  tasks:
  - name: ping the box
    ping:
  - name: check user
    command: whoami
  - name: install mysql
    environment:
     DEBIAN_FRONTEND: noninteractive
    command: apt-get install mysql-server -y
  - name: start mysql
    command: systemctl start mysql
  - name: add root user to mysql
    command: mysqladmin -u root password xhiendwd
  - name: install apache
    command: "{{ item }}"
    with_items:
    - apt-get install apache2 -y
    - mkdir -p /var/log/apache2
    - chown www-data /var/log/apache2
    - chgrp www-data /var/log/apache2
    - mkdir -p /var/log/mysql
    - chown mysql /var/log/mysql
    - chgrp mysql /var/log/mysql

 

Important:

  • Indentation is very important in YAML for proper structure and it’s based on spaces NOT tabs.
  • Comments begin with #
  • Colon (:) is used to map key -value pair
  • YAML is case sensitive
  • — means start of the document
  • … means end of the document
  • Some popular tools using YAML are anislble, gitlab (CI/CD).

 


YAML Scalars

host: host1
port: 80
path: /etc/apache2

Note: space after a colon is required.

In the above example, we have declared 3 scalars: host, port, and path. You might need to put values in quotes if something needs to be escaped.

 


YAML Lists

--- 
hosts: [host1, host2, host3]

 

=>Each element in a list must start with dash and space with proper indentation

you can also declare lists like :

--- 
hosts: [host1, host2, host3]

 


YAML dictionaries (name: value pairs)

--- 
hosts: 
  h1: host1
  h2: host2
  h3: host3

Note: spaces, – and indentation

you can also declare a dictionary like :

--- 
hosts: {h1: host1, h2: host2, h3: host3}

any string having following characters`[] {} : > |` must be quoted.

example, because the value has a colon we need to quote whole string.

---
x: "this is h1: host1"

 


Python YAML example:

x.yaml
=======
hosts:
    db:
      dbname: sybase
    server1:
      apps: [apache,tomcat]
    server2:
      apps: [iis, apache]


python
==========
#!/usr/bin/python
import yaml
s1=open("x.yaml","r")
data=yaml.load(s1)
print data["hosts"]["db"]
          

output
========
{'dbname': 'sybase'}