Master Ansible: From Installation to Advanced Playbooks and Automation
This guide introduces Ansible’s core concepts, installation, inventory configuration, command‑line usage, built‑in modules, playbook syntax, handlers, and role structures, providing step‑by‑step examples that enable engineers to automate Linux system administration efficiently and reliably.
Overview of Ansible
Ansible is an open‑source automation engine that simplifies configuration management, application deployment, and task orchestration across large numbers of servers. It relies on SSH for communication, requires no client agents on managed nodes, and ships with thousands of built‑in modules.
Key Features
Python‑based, easy to extend.
Rich module library covering most sysadmin tasks.
Agent‑less operation via SSH.
Scales to thousands of hosts with a single command.
Supported by major cloud providers (AWS, GCP, Azure) and vendors.
Roles and Interaction Models
Users can interact with Ansible through four main approaches:
CMDB integration – trigger Ansible runs directly from a configuration database.
Public/Private APIs – invoke Ansible via language bindings (Python, PHP, Perl, etc.).
Ad‑hoc commands – run one‑off tasks from the command line.
Playbooks – execute pre‑written YAML files that describe ordered tasks.
Installation
Ansible runs on a Linux control node (e.g., CentOS, RedHat, Debian). The only dependencies are Python and SSH.
YUM Installation Example
# Create a local YUM repo (optional)
cd /mnt/ansiblerepo/ansiblerepo/repodata/
vim /etc/yum.repos.d/local.repo
[local]
name=centos
baseurl=file:///mnt/ansiblerepo/ansiblerepo
enabled=1
gpgcheck=0
# Install Ansible
yum -y install ansible
# Verify installation
ansible --versionSSH Key‑Based Authentication
# Generate RSA key pair
ssh-keygen -t rsa
# Copy public key to managed hosts
ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]Inventory Configuration
The inventory file (default /etc/ansible/hosts) lists managed hosts and groups. Hosts can be addressed by name, IP, or pattern, and groups are defined in square brackets.
# Example inventory
[web]
192.168.100.20
192.168.100.30
[test]
www.example.com:222 # non‑default SSH port
[mail]
yj1.kgc.cn
yj[2:5].kgc.cn # expands to yj2…yj5Use -i /etc/ansible/hosts or --inventory-file to specify a custom inventory.
Common Ansible Commands
ansible all -m ping– verify connectivity. ansible web -m command -a "df -hT" – run a shell command on the web group. ansible web -m shell -a "echo hello world" – demonstrates the shell module (supports pipelines, redirection, etc.). ansible-playbook playbook.yml – execute a YAML playbook.
Command‑Line Options (selected)
-v / --verbose– detailed output. -i PATH / --inventory=PATH – inventory file. -f NUM / --forks=NUM – parallelism (default 5). --private-key=FILE – specify SSH key. -m MODULE / --module-name=MODULE – choose module. -a ARGS / --args=ARGS – module arguments. -u USER / --user=USER – remote user. -l SUBSET / --limit=SUBSET – limit hosts.
Built‑In Modules Overview
command – run a command without a shell.
shell – run a command through the remote shell (supports pipes, redirects).
copy – transfer files to remote hosts.
hostname – manage remote hostnames.
yum – manage packages on RPM‑based systems.
service – control system services.
user – manage user accounts.
Example: Using the copy Module
# Copy local /etc/hosts to all hosts in the web group
ansible web -m copy -a "src=/etc/hosts dest=/root/a1.hosts mode=777 owner=root group=root"Playbooks
Playbooks are YAML files that describe a series of tasks. They replace repetitive ad‑hoc commands with reusable, version‑controlled code.
# Minimal playbook (a.yml)
---
- hosts: web1
remote_user: root
tasks:
- name: add a system user
user:
name: user1
state: present
- name: copy /etc/passwd
copy:
src: /etc/passwd
dest: /homeKey sections:
hosts – target hosts or groups.
remote_user – user for remote execution.
tasks – list of module calls.
handlers – tasks that run only when notified (e.g., service restart).
roles – reusable collections of tasks, handlers, files, templates, and variables.
Running a Playbook
# Syntax check
ansible-playbook --syntax-check /etc/ansible/a.yml
# Dry run (check mode)
ansible-playbook -C /etc/ansible/a.yml
# Execute
ansible-playbook /etc/ansible/a.ymlHandlers Example
# httpd.yml snippet
---
- hosts: web1
tasks:
- name: change Apache port
command: sed -i 's/Listen 80/Listen 8080/g' /etc/httpd/conf/httpd.conf
notify: restart httpd
handlers:
- name: restart httpd
service:
name: httpd
state: restartedRoles Structure
Roles live under /etc/ansible/roles/ and follow a fixed directory layout (files, templates, tasks, handlers, vars, defaults, meta). Example role mariadb contains: tasks/main.yml – primary tasks. handlers/main.yml – restart/reload actions. templates/ – Jinja2 configuration templates. files/ – static files for the copy module. vars/main.yml and defaults/main.yml – role variables.
Playbooks can invoke roles with a simple list:
- hosts: web
remote_user: root
roles:
- mysql
- httpdPractical Example: Deploying MariaDB
Goal: install MariaDB on managed hosts, push a prepared configuration file, restart the service, create a database testdb, and grant all privileges to user test.
The playbook would combine the yum, copy, service, and mysql_user modules (the latter provided by community collections) and use handlers to restart MariaDB only when the configuration changes.
By structuring automation with playbooks and roles, teams achieve repeatable, version‑controlled deployments and reduce manual error.
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.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
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.
