This lab demonstrates how to use variables and conditional logic in Ansible to install and configure different database systems. Based on user input, the playbook installs and configures either MySQL or PostgreSQL.
.
├── hosts.ini
├── setup_db.yaml
├── mysql.cnf.j2
└── postgresql.conf.j2vi hosts.ini[all]
server1 ansible_host=server1 ansible_user=server1_admin ansible_ssh_pass='server1_admin@123!' ansible_become=true ansible_become_pass='server1_admin@123!'vi mysql.cnf.j2# MySQL configuration settings
[mysqld]
bind-address = 0.0.0.0
max_connections = 150vi postgresql.conf.j2# PostgreSQL Configuration File
listen_addresses = '*'
max_connections = 100
shared_buffers = 128MBvi setup_db.yaml---
- name: Install and Configure Databases Based on Variable
hosts: all
become: yes
vars_prompt:
- name: "db_engine"
prompt: "Enter the database engine (mysql or postgresql)"
private: no
tasks:
- name: Install MySQL
when: db_engine == 'mysql'
block:
- name: Install MySQL packages
apt:
name: mysql-server
state: present
- name: Configure MySQL
template:
src: mysql.cnf.j2
dest: /etc/mysql/mysql.conf.d/custom.cnf
notify: restart mysql
- name: Install PostgreSQL
when: db_engine == 'postgresql'
block:
- name: Install PostgreSQL packages
apt:
name: postgresql
state: present
- name: Configure PostgreSQL
template:
src: postgresql.conf.j2
dest: /etc/postgresql/16/main/postgresql.conf
notify: restart postgresql
handlers:
- name: restart mysql
service:
name: mysql
state: restarted
- name: restart postgresql
service:
name: postgresql
state: restartedansible-playbook -i hosts.ini setup_db.yamlYou will be prompted to choose:
mysql→ installs and configures MySQLpostgresql→ installs and configures PostgreSQL
- Conditional execution using
when - Grouping tasks with
block - Dynamic configuration using templates
- User input using
vars_prompt - Handlers for service restarts
This lab demonstrates how Ansible can dynamically configure different services based on variable input, enabling flexible and reusable automation workflows.