Home DevOpsAnsible for Beginners: Inventory, Playbooks, and Roles Explained

Ansible for Beginners: Inventory, Playbooks, and Roles Explained

by Knowledge Base Linux
Ansible for beginners - control node managing many servers illustration

Configuring servers by hand does not scale. The fifth manual setup never quite matches the first four, and nobody remembers which commands were run. Ansible solves this by describing the desired state of your servers in simple YAML files and applying that state automatically over SSH. This guide covers Ansible for beginners in a practical way: installation, inventory files, ad-hoc commands, playbooks, and roles.

Unlike many configuration management tools, Ansible needs no agent on the managed servers. If you can SSH into a machine, Ansible can configure it.

Prerequisites – Ansible for Beginners

  • A control machine running Ubuntu or another Linux distribution (your laptop or a small VPS).
  • One or more target servers reachable over SSH.
  • SSH key-based authentication to the targets. If you need a refresher, follow our guide on how to generate SSH keys on Linux first.

Step 1: Install Ansible on the Control Node – Ansible for Beginners

On Ubuntu, Ansible is available from the default repositories:

sudo apt update
sudo apt install -y ansible
ansible --version

For the newest release you can also install it with pip inside a virtual environment: pip install ansible. Either method works fine for learning Ansible for beginners, because the concepts are identical across versions.

Step 2: Build an Inventory File

The inventory lists the servers Ansible manages, organized into groups. Create a file named inventory.ini in a project directory:

[webservers]
web1 ansible_host=192.168.1.10 ansible_user=ubuntu
web2 ansible_host=192.168.1.11 ansible_user=ubuntu

[databases]
db1 ansible_host=192.168.1.20 ansible_user=ubuntu

[all:vars]
ansible_python_interpreter=/usr/bin/python3

Test the connection to every host with the built-in ping module. This module does not send an ICMP ping; it verifies SSH connectivity and Python availability:

ansible all -i inventory.ini -m ping

A SUCCESS response with "ping": "pong" means your control node can manage the server.

Step 3: Run Ad-Hoc Commands

Ad-hoc commands are one-liners for quick tasks, perfect while learning Ansible for beginners workflows:

# Check disk space on all servers
ansible all -i inventory.ini -a "df -h /"

# Install a package on the webservers group only
ansible webservers -i inventory.ini -b -m apt -a "name=htop state=present"

# Restart a service
ansible webservers -i inventory.ini -b -m service -a "name=nginx state=restarted"

The -b flag means “become”, running the task with sudo on the remote host. The -m flag selects a module, and -a passes its arguments.

Ansible for beginners - playbook roles and modular tasks illustration

Step 4: Write Your First Playbook

Playbooks are YAML files that group tasks into repeatable plays. Create site.yml:

---
- name: Configure web servers
  hosts: webservers
  become: true
  tasks:
    - name: Install Nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true

    - name: Copy the home page
      ansible.builtin.copy:
        content: "<h1>Hello from Ansible</h1>"
        dest: /var/www/html/index.html
        mode: "0644"
      notify: Restart Nginx

    - name: Ensure Nginx is running and enabled
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true

  handlers:
    - name: Restart Nginx
      ansible.builtin.service:
        name: nginx
        state: restarted

Run it with:

ansible-playbook -i inventory.ini site.yml

Run the same command twice. The second run should report changed=0 for every task. This property is called idempotency: Ansible only changes what differs from the desired state, which makes playbooks safe to re-run at any time.

Step 5: Organize Code with Roles

As playbooks grow, roles keep them manageable. A role bundles tasks, handlers, templates, files, and default variables for one responsibility, such as “nginx” or “docker”. Generate the skeleton with:

ansible-galaxy init roles/nginx

This creates a standard directory layout:

roles/nginx/
├── defaults/main.yml    # default variables
├── files/               # static files to copy
├── handlers/main.yml    # handlers
├── tasks/main.yml       # the task list
├── templates/           # Jinja2 templates
└── vars/main.yml        # role variables

Move your Nginx tasks into roles/nginx/tasks/main.yml, then apply the role from a much shorter playbook:

---
- name: Configure web servers
  hosts: webservers
  become: true
  roles:
    - nginx

Roles are also how the community shares automation: Ansible Galaxy hosts thousands of ready-made roles you can download with ansible-galaxy install.

Troubleshooting Common Problems

Host key verification failed

Ansible checks SSH host keys by default. Connect once manually by SSH to accept the key, or set host_key_checking = False in an ansible.cfg file for lab environments only.

Permission denied on modules

Most system tasks need become: true and a sudo-capable user. If sudo asks for a password, add --ask-become-pass when running the playbook.

YAML syntax errors

YAML is strict about indentation and tabs are not allowed. Validate a playbook without running it using ansible-playbook -i inventory.ini site.yml --syntax-check.

Best Practices as Your Ansible Project Grows

A few conventions will save you pain once playbooks multiply. Keep an ansible.cfg in the project root pointing at your inventory and roles path, so nobody runs commands against the wrong fleet. Use group_vars and host_vars directories for variables instead of burying them inside playbooks, and encrypt sensitive values with ansible-vault rather than committing plaintext secrets. Before applying big changes, run with --check for a dry-run preview and --diff to see file changes. Adopt ansible-lint in your editor or CI to enforce style and catch risky patterns early. Finally, pin external roles and collections in a requirements.yml file so a fresh checkout reproduces your exact automation months later. These practices turn a folder of scripts into an engineering asset the whole team can trust and extend.

Conclusion

You have covered the core of Ansible for beginners: installing the control node, defining an inventory, running ad-hoc commands, writing an idempotent playbook with handlers, and packaging logic into reusable roles. The natural next steps are variables and templates for per-environment configuration, and combining Ansible with CI/CD pipelines so configuration changes are tested and applied automatically. Full module references and best practices are available in the Ansible official documentation.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.