Are you tired of manually configuring servers one by one? Welcome to the world of Ansible, where infrastructure automation becomes simple, repeatable, and scalable. In this guide, I’ll walk you through setting up your first Ansible environment from scratch.
graph TB
A[Control Node] --> B[Inventory Files]
B --> C[Static Inventory]
B --> D[Dynamic Inventory]
C --> E[Playbooks]
D --> E
E --> F[Modules]
F --> G[SSH Connection]
F --> H[WinRM Connection]
G --> I[Node1]
G --> J[Node2]
H --> K[Windows Server]
I --> L[Configuration Applied]
J --> L
K --> L
M[Ansible.cfg] -.-> A
M -.-> G
M -.-> H
N[Variables] -.-> E
O[Roles] -.-> F
style A fill:#e1f5e1
style C fill:#fffacd
style D fill:#fffacd
style I fill:#f0f8ff
style J fill:#f0f8ff
style K fill:#f0f8ffUnderstanding Ansible Components
Before diving into configuration, let’s understand the four key pillars of Ansible:
- Inventories – Your list of managed machines
- Playbooks – YAML files defining what to do and in what order
- Modules – The workhorses that actually perform tasks
- Plugins – Extend functionality for logging, connections, and dynamic data
YAML: The Language of Ansible
Everything in Ansible—playbooks, roles, tasks, variables—is written in YAML. Remember these essentials:
- Start files with
---(optional but recommended) - Key-value pairs form your data structure
- Use
-for list items - Indentation matters! It defines parent-child relationships
Setting Up Your Control Node
Prerequisites
- Python 3.8 or later
- Internet connectivity
- RHEL 9.0+ (or Ubuntu with appropriate packages)
Installation Steps
# For RHEL-based systems
subscription-manager register
dnf list ansible-core
dnf install ansible-core
# Create Ansible user
sudo useradd ansible
sudo passwd ansibleConfiguring Managed Nodes
Linux Prerequisites
- Python 2.6 or later
- SSH installed and enabled
- Account with administrative privileges
Windows Prerequisites
- PowerShell 3.0 or higher
- WinRM enabled and configured
- WinRM allowed through firewall
- Administrative account
Building Your SSH Infrastructure
# Switch to ansible user
su ansible
cd ~
# Generate SSH keys
ssh-keygen
# Copy keys to managed nodes
ssh-copy-id node1
ssh-copy-id node2Configuring Passwordless Sudo
On each managed node, create a sudoers file:
sudo vim /etc/sudoers.d/ansibleAdd this line:
ansible ALL=(ALL) NOPASSWD: ALLVerify with:
sudo systemctl restart crondCreating Your First Inventory
Inventories can be static or dynamic. Let’s start with static:
mkdir ansible
vim inventoryAdd your nodes:
node1
node2
Note: these nodes have been added to the host file with their corresponding IPs
Test connectivity:
ansible node1 -i inventory -m ping
ansible node2 -i inventory -m pingOrganizing with Groups
Create a more structured inventory with the following contents:
vim group_inventory[webservers]
node1
[databaseservers]
node2
[production:children]
webservers
databaseserversConfiguring Ansible Defaults
Create ansible.cfg to simplify commands:
$ vim ansible.cfg[defaults]
inventory=inventory
remote_user=ansible
[privilege_escalation]
become=true
become_method=sudo
become_user=rootMastering Ad-Hoc Commands
Test basic operations:
# Check connectivity
ansible node1 -m ping
# Run commands
ansible all -m command -a "uptime"
ansible all -m command -a "whoami"
# Use shell module
ansible all -m shell -a "echo $HOME > /home/ansible/home.txt"
# File operations
ansible all -m copy -a "src=/etc/hosts dest=/home/ansible/host.file"
ansible all -m file -a "path=/home/ansible/testdir state=directory mode=0777"Managing Packages and Services
# Install packages
ansible node2 -m dnf -a "name=httpd state=latest"
# Manage services
ansible all -m service -a "name=httpd state=started"
ansible all -m service -a "name=httpd state=stopped"
ansible all -m service -a "name=httpd state=restarted enabled=1"
# Check status
ansible all -m command -a "systemctl status httpd"Creating Your First Playbook
Playbooks make automation repeatable. Configure your editor first:
vim ~/.vimrcAdd:
autocmd FileType yaml setlocal ai ts=2 sw=2 etNow create your playbook:
---
- name: my first play
hosts: node1
tasks:
- name: Ensure file exists
file:
path: /home/ansible/mytext.txt
state: touch
- name: Add welcome message
lineinfile:
path: /home/ansible/mytext.txt
line: "Welcome from Playbook"Run it:
ansible-playbook playbook.ymlUnderstanding Playbook Output Colors
- Green: No changes made
- Yellow/Orange: Changes were made
- Red: Execution failed
Troubleshooting and Best Practices
Ansible Lint
Install this essential tool:
pip3 install --user ansible-lint
ansible-lint playbook.yml
ansible-lint -v playbook.yml # Detailed reportCommon Troubleshooting Steps
- Start with error logs
- Increase verbosity with
-v,-vv, or-vvv - Check syntax:
ansible-playbook --syntax-check playbook.yml - Dry run:
ansible-playbook --check playbook.yml - Use the debug module for variable inspection
Gathering Facts
# Method 1: Add in playbook
gather_facts: true
# Method 2: Ad-hoc command
$ ansible all -m setupDynamic Inventories
For cloud environments, create dynamic inventory scripts:
#!/usr/bin/env python3
import json
import sys
if __name__ == '__main__':
if '--list' in sys.argv:
print(json.dumps({
"webservers": {
"hosts": ["node1", "node2"],
"vars": {
"ansible_user": "ansible"
}
},
"_meta": {
"hostvars": {
"node1": {
"ansible_host": "192.168.1.101"
},
"node2": {
"ansible_host": "192.168.1.102"
}
}
}
}))
elif '--host' in sys.argv:
# This is for single host queries
print(json.dumps({}))
else:
print(json.dumps({
"webservers": {
"hosts": ["node1", "node2"]
}
}))# Make it executable
$ chmod +x dynamic_inventory.py
# Test with --list flag
$ ./dynamic_inventory.py --list
# Test in Ansible
$ ansible webservers -i dynamic_inventory.py --list-hosts
# Test ping with dynamic inventory
$ ansible webservers -i dynamic_inventory.py -m pingWrapping Up
You’ve now set up a complete Ansible environment! Remember:
- Keep playbooks in version control
- Use roles for complex configurations
- Regularly run
ansible-lintto maintain quality - Test with
--checkbefore applying changes
Ansible transforms infrastructure management from a chore into a streamlined process. Start small, automate one task at a time, and watch your efficiency soar.