Master Ansible: From Installation to Advanced Playbooks and Roles
This comprehensive guide walks you through installing Ansible, configuring its core files, defining inventories, using key‑based SSH, executing basic commands, exploring common modules, writing playbooks, mastering YAML syntax, handling variables, conditions, loops, handlers, roles, and tags for efficient automation.
1. Basic Deployment
Install Ansible
# yum -y install epel-release
# yum list all *ansible*
# yum info ansible
# yum -y install ansibleAnsible configuration files
/etc/ansible/ansible.cfg Main configuration file
/etc/ansible/hosts Inventory
/usr/bin/ansible-doc Help files
/usr/bin/ansible-playbook Playbook runnerDefine Inventory
# cd /etc/ansible/
# cp hosts{,.bak}
# > hosts
# cat hosts
[webserver]
127.0.0.1
192.168.10.149
[dbserver]
192.168.10.113Key‑based SSH connection
# ssh-keygen -t rsa
# ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
# ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
# ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]Help commands
# ansible-doc -l List all modules
# ansible-doc -s MODULE_NAME Show details of a moduleAnsible command basics
ansible <host-pattern> [-f forks] [-m module_name] [-a args]
# Example:
ansible 192.168.10.113 -m command -a 'date'
ansible webserver -m command -a 'date'
ansible all -m command -a 'date'2. Common Modules
command # Execute a command (default module)
cron # Manage cron jobs
user # Manage user accounts
group # Manage groups
copy # Copy files to remote hosts
file # Manage file attributes
ping # Test connectivity
service # Manage service state
shell # Run complex commands with pipes, variables, etc.
script # Copy and execute a local script
yum # Install/remove packages
setup # Gather facts about remote hosts3. Ansible Playbook Structure
inventory # Target hosts
modules # Modules to invoke
ad hoc commands# Commands to run on hosts
playbooks # Collection of plays
tasks # List of tasks (module calls)
vars # Variables
templates # Jinja2 templates
handlers # Event‑driven actions
roles # Reusable components4. YAML
4.1 Introduction
YAML is a human‑readable data‑serialization format. It emphasizes readability, supports comments, and can represent scalars, lists, and mappings.
4.2 Syntax
name: john smith
age: 41
gender: male
spouse:
name: jane smith
age: 37
gender: female
children:
- name: jimmy smith
age: 17
gender: male
- name: jenny smith
age: 13
gender: female5. Core Ansible Elements
5.1 Variables
Variable names may contain letters, numbers, and underscores, and must start with a letter.
5.1.2 Facts
Facts are automatically gathered system information. Retrieve them with:
# ansible hostname -m setup5.1.3 Register
Capture a task’s output into a variable for later use:
tasks:
- shell: /usr/bin/foo
register: foo_result
ignore_errors: True5.1.4 Pass variables on the command line
# ansible-playbook test.yml --extra-vars "hosts=www user=mageedu"5.1.5 Pass variables via roles
- hosts: webserver
roles:
- common
- { role: foo_app_instance, dir: '/web/htdocs/a.com', port: 8080 }5.2 Inventory
Group hosts in /etc/ansible/hosts using INI‑style sections. Example:
ntp.magedu.com
[webserver]
www1.magedu.com:2222
www2.magedu.com
[dbserver]
db1.magedu.com
db2.magedu.com
db3.magedu.comHost‑specific variables can be added directly:
[webserver]
www1.magedu.com http_port=80 maxRequestsPerChild=808
www2.magedu.com http_port=8080 maxRequestsPerChild=909Group variables are defined in a [group:vars] section:
[webserver:vars]
ntp_server=ntp.magedu.com
nfs_server=nfs.magedu.com5.3 Conditional Tests
Use when to run a task only if a condition is true:
- name: Shutdown Debian systems
command: /sbin/shutdown -h now
when: ansible_os_family == "Debian"5.4 Loops
Repeat a task with with_items (or newer loop syntax):
- name: Add server users
user: name={{ item }} state=present groups=wheel
with_items:
- testuser1
- testuser26. Handlers
Handlers run only when notified by a task that reports a change:
- name: Install configuration file
copy: src=conf/httpd.conf dest=/etc/httpd/conf/httpd.conf
notify:
- restart httpd
handlers:
- name: restart httpd
service: name=httpd state=restarted7. Roles
Roles provide a structured way to reuse playbook components. A typical role layout:
roles/
webserver/
tasks/main.yml
handlers/main.yml
files/…
templates/…
vars/main.yml
meta/main.ymlInclude a role in a playbook:
- hosts: webserver
roles:
- common
- webserverPass parameters to a role:
- hosts: webserver
roles:
- { role: foo_app_instance, dir: '/opt/a', port: 5000 }
- { role: foo_app_instance, dir: '/opt/b', port: 5001 }8. Tags
Tags let you run or skip specific parts of a playbook:
- name: Install configuration file
template: src=conf/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
tags:
- conf
notify:
- restart httpd
# Run only tasks tagged "conf"
ansible-playbook site.yml --tags confAuthor: kangvcar – Source: https://my.oschina.net/kangvcar/blog/1830155
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.
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.
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.
