Running Ansible involves a few steps, from installation to executing tasks defined in playbooks. Here’s a step-by-step guide to get you started:
Step 1: Install Ansible
On Linux
You can install Ansible using package managers like apt for Ubuntu/Debian or yum for CentOS/RHEL.
On macOS
You can use Homebrew:
brew install ansible
On Windows
Ansible is primarily designed for Unix-like systems, but you can run it on Windows via Windows Subsystem for Linux (WSL). Follow the instructions for installing Ansible on Ubuntu under WSL.
Step 2: Set Up Your Inventory
Ansible uses an inventory file to define which hosts it will manage. This file can be in INI or YAML format.
Example of INI inventory file (hosts.ini):
[webservers]
server1.example.com
server2.example.com
[databases]
dbserver.example.com
Step 3: Write a Playbook
Create a YAML file that defines the tasks you want to run on your hosts. Here is a simple example playbook.yml that installs and starts Apache on the web servers:
- name: Install and start Apache
hosts: webservers
become: yes # Use 'become' for privilege escalation, if necessary
tasks:
- name: Install Apache
yum:
name: httpd
state: present
- name: Ensure Apache is running
service:
name: httpd
state: started
Step 4: Run the Playbook
Use the ansible-playbook command to execute your playbook.
ansible-playbook -i hosts.ini playbook.yml
-i hosts.ini: Specifies the inventory file you created.
playbook.yml: The playbook you want to run.
Step 5: Verify the Outcome
To verify that your tasks ran successfully, you can check the output of the ansible-playbook command, which will indicate whether each task was changed, skipped, or failed. You can also log into your target machines to check manually.
Additional Commands
-
Ping All Hosts: To check connectivity with the hosts defined in the inventory:
ansible all -i hosts.ini -m ping
-
Run Ad-Hoc Commands: Ansible allows you to run one-off commands without writing a playbook. For example, to install a package:
ansible webservers -i hosts.ini -m yum -a "name=httpd state=present" --become
-
Check Ansible Version: To check the installed version of Ansible:
ansible --version
Conclusion
This is the basic workflow for running Ansible. As you become more familiar with it, you can explore more advanced features like variables, templates, roles, and playbook optimizations. Ansible's flexibility makes it a powerful tool for automating various IT tasks. If you have any specific use cases or further questions about Ansible, feel free to ask!