YAML essentials for Ansible

Learn the basics of YAML, a simple yet powerful data serialization language, through examples using Ansible.

Understanding YAML is fundamental for creating Ansible content. This lesson will walk you through the basics of YAML syntax with examples relevant to Ansible.

In this lesson, you will:

  • Learn how to create and structure YAML files.

  • Learn about YAML case sensitivity and indentation for Ansible.

Ansible YAML files

In Ansible, YAML files are primarily used for playbooks, task, inventory, and variable files. These files typically end with a .yml extension, which helps other users and Integrated Development Environments (IDEs) such as Visual Studio Code, identify Ansible-specific content.  For example, site.yml could be your playbook filename.

As a best practice, Ansible YAML files start with  --- to indicate the beginning. The playbook code snippets below provide examples.

YAML case-sensitivity

YAML is case-sensitive, and it is essential to maintain consistent casing in your Ansible YAML files. Inconsistent casing can cause Ansible playbooks to fail. 

Here’s an example of inconsistent casing in a variable, which will cause the playbook execution to fail:

---
- name: Debug variable
  hosts: all
  vars:
    Wrong_casing: "myPassword"
  tasks:
    - name: Print database password
      ansible.builtin.debug:
        msg: "{{ wrong_casing }}"

YAML indentation and structure for Ansible

Consistent indentation improves the readability of YAML files. Ansible YAML files use two spaces (not tabs) for indentation. Let’s examine an example playbook called site.yml and highlight some key points.

# site.yml
---
- name: Configure web server
  hosts: all
  become: true

  vars:
    http_port: 80
    max_clients: 200

  tasks:
    - name: Install apache
      ansible.builtin.package:
        name: httpd
        state: present

    - name: Write the apache config template file
      ansible.builtin.template:
        src: httpd.conf.j2
        dest: /etc/httpd.conf
        mode: 0644

Starting the playbook file

The site.yml playbook starts with  ---, indicating the beginning of the Ansible YAML file.

Case-sensitivity

Note the variable names, http_port and max_clients, use consistent casing throughout the playbook.

Indentation

The site.yml playbook's structure uses two spaces for indentation. Ansible tasks are listed under the tasks section, and variables are under the vars section.

Next, we’ll learn more about YAML file components and data types.

Previous resource
Why YAML in Ansible Automation Platform?
Next resource
Basic Ansible YAML syntax and structure