Ansible Automation

Write Playbooks in YAML

Lesson 5 of 12 · 7 min · Beginner

YAML is a human-readable data serialization language. Combined with Ansible Playbooks, it provides a powerful, declarative way to orchestrate tasks, authorize system arrangements, and manage infrastructure efficiently.

What is YAML?

YAML stands for "Yet Another Markup Language" (or recursively, "YAML Ain't Markup Language"). It is widely supported across programming languages because it represents structured data in a way that is incredibly easy to read and maintain.

Indentation Driven

Structured data is represented purely by indentation. This keeps files clean and eliminates the need for curly braces {} or tags found in JSON or XML.

Lists and Dictionaries

Every item in an Ansible playbook is fundamentally a list of key/value pairs, commonly referred to as a "hash" or a "dictionary".

What is a Playbook?

The Blueprint

A playbook is basically a plan for defining and orchestrating tasks to be executed on managed nodes. It allows you to automate repetitive tasks and manage your entire infrastructure as code.

Playbook Structure

  • --- Every valid YAML file must begin with three dashes.
  • hosts Defines which machines (from your inventory) the tasks should target.
  • tasks A sequential list of actions (using modules) to execute against the target hosts.

A Real Webserver Playbook

web.yml
---
- name: Configure Webserver
  hosts: node2
  become: yes
  tasks:
    - name: install httpd
      yum:
        name: httpd
        state: present

    - name: enable apache
      service:
        name: httpd
        enabled: yes
        state: started

    - name: content
      copy:
        content: "welcome to webserver"
        dest: /var/www/html/index.html
        mode: "0644"

    - name: open firewall port
      firewalld:
        service: httpd
        permanent: yes
        state: enabled

Run Order

  • install Ensures the Apache (httpd) package is downloaded and present on node2.

    yum module

  • enable Starts the web service immediately and ensures it will turn on automatically upon reboot.

    service module

  • seed Injects raw HTML content straight into the index.html file with standard web permissions (0644).

    copy module

  • network Opens the native firewall to allow inbound HTTP traffic permanently.

    firewalld module

Strict YAML Rules