Ansible
Ansible
What is Ansible?
Ansible is an agentless automation tool used for:
- Server configuration
- Application deployment
- Orchestration
- Infrastructure automation
Uses YAML Playbooks + works over SSH.
๐งพ Check Installation
ansible --version๐ Inventory (Hosts File)
Default inventory file:
/etc/ansible/hostsExample:
[webservers]
192.168.1.10
192.168.1.11
[db]
192.168.1.20Custom inventory usage:
ansible -i inventory.ini all -m ping๐ SSH Setup (Passwordless Recommended)
Generate key:
ssh-keygenCopy key:
ssh-copy-id user@server๐งช Test Connection
ansible all -m pingSpecific group:
ansible webservers -m ping๐งญ Ad-hoc Commands
Run command on remote:
ansible all -m command -a "uptime"Install package:
ansible all -m apt -a "name=nginx state=present" --becomeCopy file:
ansible all -m copy -a "src=file.txt dest=/home/user/"Create directory:
ansible all -m file -a "path=/opt/test state=directory"๐ Playbook Structure
A playbook is YAML:
- hosts: webservers
become: yes
tasks:
- name: Install nginx
apt:
name: nginx
state: presentRun playbook:
ansible-playbook site.yml๐งฉ Common Modules
| Module | Purpose |
|---|---|
ping |
test connectivity |
apt / yum |
package management |
service |
manage services |
copy |
copy files |
file |
manage files/dirs |
command |
run commands |
shell |
run shell commands |
user |
user management |
โ๏ธ Service Management
- name: Start nginx
service:
name: nginx
state: startedEnable service:
- name: Enable nginx
service:
name: nginx
enabled: yes๐ Copy & Templates
Copy file:
- name: Copy config
copy:
src: config.conf
dest: /etc/app/config.confTemplate (Jinja2):
- name: Deploy template
template:
src: config.j2
dest: /etc/app/config.conf๐ Become (Root Privilege)
In playbook:
become: yesIn command:
ansible-playbook play.yml --become๐ง Variables
vars:
package: nginx
tasks:
- name: Install package
apt:
name: "{{ package }}"
state: present๐ฏ Handlers (Run Only When Changed)
tasks:
- name: Install nginx
apt:
name: nginx
state: present
notify: restart nginx
handlers:
- name: restart nginx
service:
name: nginx
state: restarted๐งช Dry Run (Check Mode)
ansible-playbook site.yml --check๐๏ธ Speed Tips
Disable SSH host checking:
[defaults]
host_key_checking = FalseRun in parallel:
ansible-playbook site.yml -f 10๐งพ Facts (System Info)
Show facts:
ansible all -m setupUse in play:
ansible_facts['ansible_hostname'][!Summary]
Ansible is awesome because it is:
- Agentless
- Simple YAML-based
- Secure (SSH)
- Scalable
- DevOps standard