Operations 23 min read

Master Ansible: From Basics to Advanced Playbooks and Automation

This comprehensive guide walks you through Ansible fundamentals, architecture, installation, core modules, playbook structure, variables, templates, handlers, roles, conditionals, loops, and practical examples, enabling you to automate configuration management across multiple Linux hosts with confidence and precision.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Ansible: From Basics to Advanced Playbooks and Automation

What is Ansible?

Ansible is an agentless automation tool written in Python, built on core libraries Paramiko, PyYAML, and Jinja2. It offers modularity, simple deployment, custom module support, powerful playbook mechanisms, and idempotence.

Ansible Architecture Diagram

Ansible Features

Modular: invoke specific modules to perform tasks.

Python‑based: uses Paramiko, PyYAML, Jinja2.

Agentless deployment.

Supports custom modules in any language.

Powerful playbook mechanism.

Idempotent operations.

Installation and Environment

Key programs: ansible, ansible‑playbook, ansible‑doc.

Configuration files:

/etc/ansible/ansible.cfg
/etc/ansible/hosts

(inventory) /usr/share/ansible_plugins/ (plugin directory)

Installation steps (illustrated with screenshots): download packages, install dependencies, generate SSH keys, copy public keys to target hosts, verify connectivity.

Ansible Command Usage

Basic syntax: ansible <host‑pattern> [options] Common options:

-m MOD_NAME
-a MOD_ARGS

Configuring Host Inventory

Inventory file /etc/ansible/hosts defines groups and host patterns, e.g.:

[group_id]
HOST_PATTERN1
HOST_PATTERN2

After editing, back up the file and verify the changes.

Ansible Modules

List modules with ansible‑doc -l. Get module help with ansible‑doc -s MOD_NAME. Common modules include:

ping : test host reachability.

command : run commands on remote hosts.

shell : run shell commands with full shell features.

copy : copy files to remote hosts.

file : manage file attributes.

fetch : retrieve files from remote hosts.

cron : manage scheduled tasks.

hostname : manage hostnames.

yum : manage packages via yum.

service : manage services.

group : add or delete groups.

user : manage users.

setup : gather host facts.

template : render Jinja2 templates.

Playbook

A playbook is a YAML file that defines the automation workflow. Core elements:

hosts : target hosts.

remote_user : user to execute tasks.

tasks : list of module actions.

variables : custom variables.

templates : Jinja2 files.

handlers : tasks triggered by notifications.

roles : reusable collections of tasks, vars, templates, etc.

Typical commands:

Syntax check: ansible‑playbook --syntax‑check /path/to/playbook.yml Dry run: ansible‑playbook -C /path/to/playbook.yml List hosts: --list‑hosts List tasks: --list‑tasks Execute:

ansible‑playbook /path/to/playbook.yml

Variables

Variables can be built‑in (facts) or user‑defined. They can be passed via the command line ( -e VAR=VALUE), defined in inventory files, host‑specific sections, group vars, playbooks, roles, or extra files. Use the Jinja2 syntax {{ var_name }} to reference them.

Templates

Templates are text files processed by Jinja2. They support literals, lists, dictionaries, arithmetic, comparisons, and logical operators. Use the template module to render a template onto a remote host:

- name: Deploy config
  template:
    src: my.conf.j2
    dest: /etc/my.conf
    mode: 0644

Handlers

Handlers are tasks that run only when notified. Define them under a handlers: section and notify them from regular tasks using notify: HANDLER_NAME.

Roles

Roles provide a standardized directory structure ( tasks/, handlers/, vars/, templates/, files/, meta/, defaults/) to organize reusable automation code. Include a role in a playbook with:

- hosts: webservers
  roles:
    - nginx
    - { role: mysql, db_name: prod }

Conditional Testing

Use when: statements with Jinja2 expressions to run tasks only on matching hosts, e.g., start nginx on CentOS 6 but not on CentOS 7.

Loops

Iterate over items with with_items (or the newer loop) to repeat tasks for lists, strings, or dictionaries. Example: install multiple packages in one task.

Practical Examples

The guide includes step‑by‑step examples for:

Setting up password‑less SSH.

Creating users and groups.

Deploying and configuring Nginx with Jinja2 templates and role‑based structure.

Managing services (start/stop/restart) across different OS versions.

Using tags to run specific parts of a playbook.

Configuring Memcached memory based on host facts.

Installing MySQL or MariaDB conditionally based on the target OS.

Each example shows the relevant YAML snippets, command‑line checks, and verification steps (e.g., confirming open ports, checking service status, validating file contents).

Performance Note

By default Ansible limits parallel execution to five hosts; increase this value in /etc/ansible/ansible.cfg if you need to manage more hosts, ensuring the control machine has sufficient resources.

Author: ~微风~ Source: http://weiweidefeng.blog.51cto.com/1957995/1895261

Click the image below for more course details

—马哥教育,让你懂更让你行—

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AutomationConfiguration ManagementDevOpsAnsiblePlaybooks
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.