Master Ansible: From Installation to Advanced Playbooks and Roles
This comprehensive guide walks you through installing Ansible, configuring its core files, defining inventories, using common modules, writing YAML syntax, creating variables, applying conditional tests, iterating tasks, building playbooks, organizing roles, and leveraging tags for selective execution.
1. Basic Setup
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 config file
/etc/ansible/hosts Inventory
/usr/bin/ansible-doc Help
/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.113Connect using SSH keys
# 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]Helpful commands
# ansible-doc -l List all modules
# ansible-doc -s MODULE_NAME Show details for a moduleBasic Ansible command syntax
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 # default module, runs a command on remote hosts
cron # schedule jobs (minute, hour, day, month, weekday, state)
user # manage user accounts (name, uid, groups, home, etc.)
group # manage groups (name, gid, state)
copy # copy files to remote hosts (src, dest, owner, mode, content)
file # manage file attributes and symlinks
ping # test connectivity
service # manage service state (enabled, name, state)
shell # run complex commands with pipes, variables
script # copy and execute a local script on remote hosts
yum # install/remove packages
setup # gather facts from remote hosts3. Ansible Playbook Structure
A playbook consists of inventory, modules, ad‑hoc commands, and a list of plays. Each play defines hosts, variables, tasks, handlers, and optional roles.
4. YAML
4.1 Introduction
YAML (YAML Ain't Markup Language) is a human‑readable data‑serialization format used for Ansible playbooks and inventory files.
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.
Facts
Facts are gathered from remote hosts and stored as variables. Retrieve all facts with:
# ansible hostname -m setupRegister
Capture task output into a variable for later use:
tasks:
- shell: /usr/bin/foo
register: foo_result
ignore_errors: TruePassing variables via CLI
# ansible-playbook test.yml --extra-vars "hosts=www user=devopsman"Passing variables through roles
- hosts: webserver
roles:
- common
- {role: foo_app_instance, dir: '/web/htdocs/a.com', port: 8080}5.2 Inventory
Group hosts in INI‑style files. Example:
ntp.devopsman.cn
[webserver]
www1.devopsman.cn:2222
www2.devopsman.cn
[dbserver]
db1.devopsman.cn
db2.devopsman.cn
db3.devopsman.cn
[webserver]
www[01:50].example.com
[databases]
db-[a:f].example.comHost variables
[webserver]
www1.devopsman.cn http_port=80 maxRequestsPerChild=808
www2.devopsman.cn http_port=8080 maxRequestsPerChild=909Group variables
[webserver]
www1.devopsman.cn
www2.devopsman.cn
[webserver:vars]
ntp_server=ntp.devopsman.cn
nfs_server=nfs.devopsman.cnGroup nesting
[apache]
httpd1.devopsman.cn
httpd2.devopsman.cn
[nginx]
ngx1.devopsman.cn
ngx2.devopsman.cn
[webserver:children]
apache
nginx
[webserver:vars]
ntp_server=ntp.devopsman.cnInventory parameters
ansible_ssh_host
ansible_ssh_port
ansible_ssh_user
ansible_ssh_pass
ansible_sudo_pass
ansible_connection
ansible_ssh_private_key_file
ansible_shell_type
ansible_python_interpreter5.3 Conditional Tests
Use when statements with Jinja2 expressions to run tasks conditionally.
tasks:
- name: "shutdown Debian flavored system"
command: /sbin/shutdown -h now
when: ansible_os_family == "Debian"
- command: /bin/false
register: result
ignore_errors: True
- command: /bin/something
when: result|failed
- command: /bin/something_else
when: result|success5.4 Loops
Iterate over items with with_items (or the newer loop syntax).
- name: add server user
user:
name: "{{ item }}"
state: present
groups: wheel
with_items:
- testuser1
- testuser26. Templates
# Example Jinja2 snippet in a template
MaxClients {{ maxClients }}
Listen {{ httpd_port }}7. Ansible Playbooks
A playbook is a list of plays. Each play maps hosts to a set of tasks.
- hosts: webserver
vars:
http_port: 80
max_clients: 256
remote_user: root
tasks:
- name: ensure apache is at the latest version
yum:
name: httpd
state: latest
- name: ensure apache is running
service:
name: httpd
state: started
handlers:
- name: restart apache
service:
name: httpd
state: restarted7.1 Playbook components
Hosts and Users
Define which hosts a play runs on and under which remote user.
Task list and actions
Each task calls a module with parameters; modules are idempotent.
Handlers
Tasks that run only when notified by other tasks.
8. Roles
Roles provide a structured way to organize playbooks, separating files, templates, tasks, handlers, vars, and meta.
# Directory layout example
roles/
common/
tasks/main.yml
handlers/main.yml
files/…
templates/…
vars/main.yml
webserver/
tasks/main.yml
…
# Using roles in a playbook
- hosts: webserver
roles:
- common
- webserver8.1 Creating a role
Create a roles directory.
Create sub‑directories for each role (e.g., webserver).
Inside each role, create tasks, files, templates, handlers, vars, meta (and optionally defaults).
Reference the role in your playbook.
9. Tags
Tags let you run or skip specific parts of a playbook.
- hosts: webserver
tasks:
- name: install httpd package
yum:
name: httpd
state: latest
- name: configure httpd
template:
src: httpd.conf.j2
dest: /etc/httpd/conf/httpd.conf
tags: conf
notify: restart httpd
handlers:
- name: restart httpd
service:
name: httpd
state: restartedRun only tasks with the conf tag: ansible-playbook site.yml --tags conf.
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.
