This is a demo of a much larger experience.

Basic Ansible Playbook Guide

What is an Ansible Playbook?

An Ansible playbook is a YAML file that defines a series of tasks to be executed on remote hosts. Playbooks are the foundation of Ansible's configuration management and automation capabilities.

Basic Structure

---
- name: My First Playbook
  hosts: all
  become: yes
  tasks:
    - name: Ensure package is installed
      apt:
        name: nginx
        state: present

Key Components

1. Play Definition

2. Tasks

Tasks are the individual actions to perform:

tasks:
  - name: Install Apache
    apt:
      name: apache2
      state: present

  - name: Start Apache service
    service:
      name: apache2
      state: started
      enabled: yes

3. Variables

vars:
  http_port: 80
  max_clients: 200

4. Handlers

Handlers run when notified by tasks:

handlers:
  - name: restart apache
    service:
      name: apache2
      state: restarted

tasks:
  - name: Copy configuration
    copy:
      src: apache.conf
      dest: /etc/apache2/apache2.conf
    notify: restart apache

Complete Example

---
- name: Configure web server
  hosts: webservers
  become: yes

  vars:
    http_port: 80

  tasks:
    - name: Install nginx
      apt:
        name: nginx
        state: present
        update_cache: yes

    - name: Copy custom index page
      copy:
        content: "<h1>Welcome</h1>"
        dest: /var/www/html/index.html

    - name: Ensure nginx is running
      service:
        name: nginx
        state: started
        enabled: yes

Running a Playbook

ansible-playbook playbook.yml
ansible-playbook playbook.yml -i inventory.ini
ansible-playbook playbook.yml --check  # Dry run
ansible-playbook playbook.yml -v       # Verbose output

Best Practices

  1. Use meaningful names for plays and tasks
  2. Keep playbooks simple and modular
  3. Use variables for values that might change
  4. Test with --check mode before running
  5. Use version control for your playbooks
  6. Organize with roles for complex projects