Ansible is an open-source automation tool that simplifies IT configuration management, application deployment, and orchestration. It operates agentlessly over SSH and does not require any additional software installation on the target nodes.
- The machine where Ansible is installed and from which tasks are executed.
- Requires Python 3.x installed.
- Runs Ansible commands, playbooks, and modules.
- The remote servers or devices managed by the Ansible control node.
- Communicated via SSH (or WinRM for Windows).
- No agent or software installation is required on the managed nodes.
sudo apt update
sudo apt install ansible -y
Enable EPEL repository:
sudo yum install epel-release -y
Install Ansible:
sudo yum install ansible -y
ansible --version
An inventory file defines the hosts and groups of hosts that Ansible manages.
[webservers]
192.168.1.10
192.168.1.11
[dbservers]
192.168.1.20 ansible_user=root ansible_ssh_private_key_file=/path/to/key
- Groups:
[webservers]
,[dbservers]
- Variables:
ansible_user
,ansible_ssh_private_key_file
The primary configuration file is ansible.cfg
. It can be located:
/etc/ansible/ansible.cfg
- Current working directory (
./ansible.cfg
)
[defaults]
inventory = ./inventory
remote_user = ubuntu
private_key_file = /path/to/private_key
host_key_checking = False
Ansible allows executing single commands without writing a playbook.
ansible all -m ping
ansible webservers -a "uptime"
ansible dbservers -m apt -a "name=nginx state=present"
Playbooks are YAML files used to define multiple tasks and configurations.
---
- name: Configure webservers
hosts: webservers
become: true
tasks:
- name: Install Nginx
apt:
name: nginx
state: present
- name: Start and enable Nginx service
service:
name: nginx
state: started
enabled: true
ansible-playbook site.yml
Ansible modules are the core tools for executing tasks.
ping
: Checks connectivity.shell
/command
: Executes commands on remote nodes.apt
/yum
: Manages packages.copy
: Copies files to remote hosts.service
: Manages system services.
ansible webservers -m copy -a "src=/local/file dest=/remote/path"
- The master system where Ansible is installed.
- Manages multiple managed nodes.
- Any server, device, or system managed by Ansible.
- Can be grouped logically for better organization.
-
Organize Inventory:
- Group hosts logically in the inventory file.
- Use variables to simplify tasks.
-
Use Roles:
- Encapsulate playbooks, variables, templates, and tasks.
- Example folder structure:
roles/ webserver/ tasks/ handlers/ templates/ vars/ defaults/
-
Secure Sensitive Data:
- Use
ansible-vault
to encrypt sensitive information.ansible-vault encrypt secrets.yml
- Use
-
Test Playbooks:
- Always test on a staging environment before deploying to production.
-
Version Control:
- Store playbooks and configurations in Git for tracking and collaboration.
Use the -vvv
flag for detailed output:
ansible-playbook -i inventory site.yml -vvv
ansible all -m ping
ansible-playbook site.yml --syntax-check