Operations 22 min read

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.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Ansible: From Installation to Advanced Playbooks and Roles

1. Basic Deployment

Install Ansible

# yum -y install epel-release
# yum list all *ansible*
# yum info ansible
# yum -y install ansible

Ansible configuration files

/etc/ansible/ansible.cfg    Main configuration file
/etc/ansible/hosts          Inventory
/usr/bin/ansible-doc        Help files
/usr/bin/ansible-playbook   Playbook runner

Define Inventory

# cd /etc/ansible/
# cp hosts{,.bak}
# > hosts
# cat hosts
[webserver]
127.0.0.1
192.168.10.149

[dbserver]
192.168.10.113

Key‑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 module

Ansible 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 hosts

3. 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 components

4. 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: female

5. 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 setup

5.1.3 Register

Capture a task’s output into a variable for later use:

tasks:
  - shell: /usr/bin/foo
    register: foo_result
    ignore_errors: True

5.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.com

Host‑specific variables can be added directly:

[webserver]
www1.magedu.com http_port=80 maxRequestsPerChild=808
www2.magedu.com http_port=8080 maxRequestsPerChild=909

Group variables are defined in a [group:vars] section:

[webserver:vars]
ntp_server=ntp.magedu.com
nfs_server=nfs.magedu.com

5.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
    - testuser2

6. 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=restarted

7. 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.yml

Include a role in a playbook:

- hosts: webserver
  roles:
    - common
    - webserver

Pass 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 conf
Author: kangvcar – Source: https://my.oschina.net/kangvcar/blog/1830155
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.

Configuration ManagementYAMLPlaybooks
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.