Operations 21 min read

Turn Scattered Playbooks into Reusable Ansible Roles – A Complete Practical Guide

This article walks through converting monolithic Ansible playbooks into modular roles, securing secrets with Vault, boosting concurrency for hundreds of servers, and delivering ready‑to‑run LNMP, LVS + Keepalived, system‑info, NTP, and bare‑metal initialization playbooks, complete with code examples and performance tips.

AI Agent Super App
AI Agent Super App
AI Agent Super App
Turn Scattered Playbooks into Reusable Ansible Roles – A Complete Practical Guide

Why Split Playbooks into Roles?

Roles provide modularity: each service (Nginx, MySQL, PHP, etc.) gets its own directory with tasks, handlers, templates, defaults, and vars, making the main playbook clean and reusable.

Project Structure Before and After

Before: a flat list of install_*.yml files and a single vars.yml mixing all variables.

After: a structured layout with site.yml, ansible.cfg, inventory/, and a roles/ directory containing sub‑roles such as nginx, mysql, php, and common. Sensitive data lives in vault/secrets.yml.enc.

Creating a Role

Run ansible-galaxy role init nginx to generate the skeleton, then fill in the appropriate files.

Ansible Vault – Encrypting Secrets

Encrypt entire files: ansible-vault create vault/secrets.yml Encrypt a single variable string:

ansible-vault encrypt_string "MyS3cretP@ss" --name "db_password"

Run encrypted playbooks with --ask-vault-pass, a password file, or an environment variable. Encrypted files start with $ANSIBLE_VAULT;1.1;AES256, protecting secrets even if the repository is leaked.

High‑Concurrency Tuning for 200 Servers in 15 Minutes

Default forks=5 is too low. Increase it in ansible.cfg:

[defaults]
inventory=./inventory/hosts
forks=50
timeout=30
host_key_checking=False

[ssh_connection]
pipelining=True
ssh_args=-C -o ControlMaster=auto -o ControlPersist=60s

Key tweaks:

forks : raise to 50‑100 depending on controller resources.

pipelining=True : reduces SSH round‑trips, 2‑3× speedup.

ControlPersist : reuses SSH connections.

disable gather_facts when not needed.

fact caching with JSON files to avoid repeated collection.

strategy=free runs tasks on each host independently.

serial (e.g., serial: "30%") rolls out updates in batches.

Practical Playbook 1 – LNMP One‑Click Installation

Main playbook ( site.yml) calls the common, nginx, mysql, and php roles.

Nginx role installs the package, deploys nginx.conf.j2, and restarts the service via a handler.

MySQL role installs MySQL, creates a database, and sets the root password (the password should be read from the encrypted vault, not hard‑coded).

PHP role installs PHP and extensions, deploys www.conf.j2, and ensures the service runs.

Practical Playbook 2 – LVS + Keepalived One‑Click Deployment

Inventory defines masters, backups, and real servers. The lvs role installs ipvsadm and keepalived, enables IP forwarding, and renders keepalived.conf.j2 with DR mode, VIP, and per‑host configuration.

The real‑server role configures a VIP on the loopback interface and adjusts ARP settings to prevent direct client connections.

Execution command:

ansible-playbook site.yml -i inventory/hosts --tags lvs

Practical Playbook 3 – Bulk Server Information Collection

Uses gather_facts with a selective gather_subset to collect hostname, OS, memory, CPU, and network details, then writes a summary file to /tmp/ and prints a concise line to the console.

Practical Playbook 4 – Batch NTP Time Synchronization

Installs chrony, replaces default NTP servers with Alibaba Cloud mirrors, restarts the service, forces an immediate step with chronyc -a makestep, and verifies the status.

Practical Playbook 5 – Bare‑Metal Server Initialization

Automates the first‑time setup of a new server:

Set hostname.

Deploy resolv.conf via a Jinja2 template.

Install a base toolset (vim, wget, curl, etc.).

Create an admin user, set a hashed password, and configure password‑less sudo for the wheel group.

Deploy the admin’s SSH public key.

Disable SELinux and firewalld.

Tune kernel parameters (file‑max, somaxconn, tcp_max_syn_backlog, tcp_tw_reuse, vm.swappiness).

Set timezone to Asia/Shanghai.

Install and start chrony for NTP.

Configure remote rsyslog.

Disable unnecessary services (postfix, abrt, etc.).

Reboot if SELinux changes require it.

Variable files provide admin_user, encrypted admin_password, SSH key path, and syslog server address.

Additional Ready‑to‑Use Scripts

Bulk root password change.

Batch SSH key deployment and root login hardening.

Disk usage alert with a threshold of 80%.

Firewall setup using firewalld (open ports 22/80/443, close telnet).

Docker CE installation with repository setup and user group addition.

Conclusion

Using Ansible roles turns chaotic playbooks into maintainable, secure, and high‑performance automation. Key takeaways are:

Structure first – modular roles simplify future changes.

Security first – store all secrets in Vault.

Performance tuning – adjust forks, enable pipelining, cache facts, and choose the appropriate strategy.

The provided LNMP, LVS, information‑gathering, NTP, and bare‑metal playbooks have been battle‑tested in production and can be used directly.

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.

automationDevOpsPerformance TuningansibleLNMPLVSrolesVault
AI Agent Super App
Written by

AI Agent Super App

AI agent applications, installation, large-model testing, computer fundamentals, IT operations and maintenance exchange, network technology exchange, Linux learning

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.