Day02 - harishgorla5/Ansible GitHub Wiki
๐งโ๐ซ Ansible Training - Day 2: Playbooks, Variables, Tasks & Conditions
๐ 1. What is a Playbook?
A Playbook is a YAML file containing one or more "plays". Each play targets a group of hosts and runs a list of tasks using Ansible modules.
๐น Basic Playbook Structure
- name: Play Name (describes the purpose)
hosts: group_name
become: true # use sudo
tasks:
- name: Task name
module_name:
option1: value1
option2: value2
web_setup.yml
๐ 2. Create Your First Playbook: - name: Install and start Apache on Web Servers
hosts: web
become: true
tasks:
- name: Install Apache
yum:
name: httpd
state: present
- name: Start and enable Apache
service:
name: httpd
state: started
enabled: yes
๐ Run the playbook:
ansible-playbook -i inventory web_setup.yml
๐ก 3. Variables in Playbooks
You can define variables at different levels:
- Inside playbooks
- Inside inventory (host/group)
- External files
๐ธ Inline variable
vars:
my_package: httpd
tasks:
- name: Install a package
yum:
name: "{{ my_package }}"
state: present
db_setup.yml
๐ 4. Example: DB Setup Playbook - name: Install and start MariaDB
hosts: db
become: true
tasks:
- name: Install MariaDB
yum:
name: mariadb-server
state: present
- name: Start and enable MariaDB
service:
name: mariadb
state: started
enabled: yes
when
Condition
๐ 5. Using Run a task only when a condition is met.
- name: Create special user only on Amazon Linux
hosts: all
become: true
tasks:
- name: Create user
user:
name: specialuser
when: ansible_distribution == "Amazon"
๐งช 6. Real-World Lab: Web + DB Setup Using Playbooks
๐ Inventory file (same as Day 1):
[web]
172.31.9.115 ansible_user=ec2-user ansible_ssh_private_key_file=~/.ssh/your-key.pem
[db]
172.31.15.215 ansible_user=ec2-user ansible_ssh_private_key_file=~/.ssh/your-key.pem
web_setup.yml
๐ Playbook file 1: - name: Configure Apache web server
hosts: web
become: true
tasks:
- name: Install Apache
yum:
name: httpd
state: present
- name: Start Apache
service:
name: httpd
state: started
enabled: yes
- name: Copy homepage
copy:
content: "Welcome to the Apache Web Server"
dest: /var/www/html/index.html
db_setup.yml
๐ Playbook file 2: - name: Configure MariaDB server
hosts: db
become: true
tasks:
- name: Install MariaDB
yum:
name: mariadb-server
state: present
- name: Start MariaDB
service:
name: mariadb
state: started
enabled: yes
โถ๏ธ Run:
ansible-playbook -i inventory web_setup.yml
ansible-playbook -i inventory db_setup.yml
๐ง 7. Homework & Practice
- Create a playbook to:
- Install
git
on all nodes - Create a user
devops
on onlyweb
nodes - Set the timezone to
Asia/Kolkata
on all hosts
- Install
๐ Summary (What Students Learned)
Topic | Covered |
---|---|
Playbook Syntax | โ |
YAML Structure | โ |
Tasks and Modules | โ |
Variables | โ |
Conditions (when ) |
โ |
Multiple Playbooks | โ |
Hands-on Lab | โ |