Ansible: Playbook
Ad-hoc commands are great for simple tasks. For more complex automation (like configuring servers, installing packages, or running multiple tasks), use an Ansible playbook.
1. Create a Simple Playbook (YAML file)
Create a file named site.yml
:
- name: Example playbook to update and install Apache on webserver
hosts: webservers
become: yes
tasks:
- name: Update apt repo
apt:
update_cache: yes
- name: Install Apache2
apt:
name: apache2
state: present
2. Run the Playbook
ansible-playbook -i hosts.ini site.yml
- This runs the playbook tasks on all servers in the
[webservers]
group.
3. Extend Playbook for Other Servers
You can add more plays/tasks for dbservers
, users, files, etc.
4. Folder Structure Example
project_folder/
├── hosts.ini
└── site.yml
5. Best Practices
- Use separate playbooks for different roles (web, db, monitoring, etc).
- Store passwords/secrets with Ansible Vault.
- Use variables for customization.