Ansible Playbook
1. Install Ansible
Ensure Ansible is installed on your control node (the machine from which you run the playbooks).
sudo apt update
sudo apt install ansible -y
2. Set Up Inventory File
Define the inventory file (hosts), which lists the managed nodes and groups of nodes. The default inventory file is located at /etc/ansible/hosts, but you can specify a custom file using the -i option.
Example (hosts file):
[webservers]
web1.example.com
web2.example.com
[dbservers]
db1.example.com
3. Create a Playbook File
A playbook is a YAML file containing one or more plays. Each play maps a group of hosts to roles.
领英推荐
Example (site.yml):
---
- name: Install and configure web servers
hosts: webservers
become: yes
tasks:
- name: Ensure Apache is installed
apt:
name: apache2
state: present
update_cache: yes
- name: Ensure Apache is started
service:
name: apache2
state: started
- name: Deploy HTML file
copy:
src: /path/to/index.html
dest: /var/www/html/index.html
- name: Install and configure database servers
hosts: dbservers
become: yes
tasks:
- name: Ensure MySQL is installed
apt:
name: mysql-server
state: present
update_cache: yes
- name: Ensure MySQL is started
service:
name: mysql
state: started
4. Playbook Structure
5. Run the Playbook
Execute the playbook using the ansible-playbook command.
ansible-playbook -i hosts site.yml
Thank you for reading