Master Ansible: A Complete Guide to Playbooks, Modules, and Automation
This comprehensive tutorial walks you through Ansible fundamentals, architecture, key features, installation, inventory setup, and detailed usage of modules, playbooks, variables, templates, handlers, tags, loops, roles, and conditionals, providing step‑by‑step examples and practical tips for automating server configuration and management.
What is Ansible?
Ansible Architecture Diagram
Ansible Features
Modular: call specific modules to perform specific tasks.
Based on Python, built with Paramiko, PyYAML, and Jinja2.
Agentless deployment.
Supports custom modules written in any language.
Powerful playbook mechanism.
Idempotent.
Installation and Environment
Program: ansible
ansible‑playbook
ansible‑doc
Configuration file: /etc/ansible/ansible.cfg
Host inventory: /etc/ansible/hosts
Plugin directory: /usr/share/ansible_plugins/
Install Ansible:
Install dependencies:
Using Ansible Commands
Usage: ansible <host-pattern> [options] Common options:
-m MOD_NAME -a MOD_ARGSConfigure Host Inventory
File:
/etc/ansible/hosts [group_id]
HOST_PATTERN1
HOST_PATTERN2Backup the original file before editing.
SSH Key‑Based Authentication
Generate a key pair: ssh-keygen -t rsa -P '' Copy the public key to authorized_keys on the remote hosts.
Testing Connectivity
Ping all hosts:
ansible all -m pingCommon Ansible Modules
ping : check if a host is reachable.
command : run a command on a remote host (default module).
shell : run a command through the shell, supporting pipelines.
copy : copy files to remote hosts.
file : manage file attributes (create, delete, link).
cron : manage cron jobs.
hostname : manage hostnames.
yum : manage packages with yum.
service : manage services (start, stop, restart, enable).
group : manage groups.
user : manage users.
setup : gather host facts.
fetch : retrieve files from remote hosts.
YAML Basics
YAML is a human‑readable data‑serialization format.
Data structures:
Key‑value pairs: key: value Lists: - item1 Dictionaries:
{name: jerry, age: 21}Playbook Structure
Hosts : target hosts.
remote_user : user to execute tasks.
tasks : list of tasks.
handlers : tasks triggered by notifications.
vars : variables.
templates : Jinja2 templates.
roles : reusable sets of tasks, files, templates, etc.
Typical command to run a playbook: ansible-playbook /path/to/playbook.yaml Common options: --syntax-check: check syntax. -C or --check: dry run. --list-hosts: list target hosts. --list-tasks: list tasks. --list-tags: list tags. -t TAGS or --tags=TAG: run only tasks with given tags. --skip-tags=TAG: skip tasks with given tags. --start-at-task=TASK: start from a specific task.
Using Tags
Assign a tag to a task:
- name: Install package
yum:
name: httpd
state: present
tags: httpd_installRun only tasks with the tag:
ansible-playbook playbook.yaml --tags=httpd_installVariables
Variables can be defined in several ways:
Built‑in facts (gathered by the setup module).
Command‑line: -e VAR=value.
Inventory file: per‑host or per‑group variables.
Playbook: vars: section.
Role defaults and vars.
Reference a variable in a template or task with {{ var_name }}.
Templates (Jinja2)
Templates are text files that contain Jinja2 expressions.
Typical usage:
- name: Deploy configuration file
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
mode: '0644'
owner: root
group: rootJinja2 supports literals, lists, dictionaries, arithmetic, comparisons, and logical operators.
Handlers
Handlers are tasks that run only when notified.
- name: Restart nginx
service:
name: nginx
state: restarted
listen: restart_nginxNotify a handler from a task:
- name: Update configuration
copy:
src: nginx.conf
dest: /etc/nginx/nginx.conf
notify: restart_nginxLoops
Iterate over a list, dictionary, or string using with_items (or the newer loop syntax).
- name: Install multiple packages
yum:
name: "{{ item }}"
state: present
loop:
- httpd
- php
- mariadb-serverRoles
Roles provide a standardized directory layout:
tasks/main.yml handlers/main.yml vars/main.yml defaults/main.yml files/ templates/ meta/main.ymlUse a role in a playbook:
- hosts: webservers
roles:
- nginx
- { role: mysql, vars: { mysql_root_password: secret } }Conditional Execution
Use when to run a task only if a condition is true.
- name: Start httpd on CentOS 6
service:
name: httpd
state: started
when: ansible_distribution_major_version == "6"Example: Deploy Nginx with a Role
Directory layout:
roles/
nginx/
tasks/main.yml
handlers/main.yml
templates/nginx.conf.j2
files/nginx‑package.rpmPlaybook nginx.yml:
- hosts: webservers
become: true
roles:
- nginxThe role installs the package, copies the configuration, renders the template, and restarts the service via a handler.
Example: Manage Users with a Loop
- name: Create users
user:
name: "{{ item.name }}"
state: present
groups: "{{ item.groups | default(omit) }}"
loop:
- { name: alice, groups: "wheel" }
- { name: bob }Example: Conditional Package Installation
- name: Install httpd on CentOS 7
yum:
name: httpd
state: present
when: ansible_distribution_major_version == "7"Best Practices
Keep YAML indentation consistent; a missing space can break the playbook.
Use --syntax-check or --check to validate before execution.
Test changes on a small set of hosts before applying to the whole inventory.
Leverage roles and variables to make playbooks reusable and maintainable.
Source: https://blog.51cto.com/weiweidefeng/1895261
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
