Skip to content

Latest commit

 

History

History
151 lines (111 loc) · 2.88 KB

File metadata and controls

151 lines (111 loc) · 2.88 KB

Ansible Use Case: Conditional Database Setup

Overview

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.


Project Structure

.
├── hosts.ini
├── setup_db.yaml
├── mysql.cnf.j2
└── postgresql.conf.j2

Implementation Steps

1. Create Inventory File

vi 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!'

2. Create MySQL Template

vi mysql.cnf.j2
# MySQL configuration settings
[mysqld]
bind-address = 0.0.0.0
max_connections = 150

3. Create PostgreSQL Template

vi postgresql.conf.j2
# PostgreSQL Configuration File
listen_addresses = '*'
max_connections = 100
shared_buffers = 128MB

4. Create Playbook

vi 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: restarted

5. Run Playbook

ansible-playbook -i hosts.ini setup_db.yaml

You will be prompted to choose:

  • mysql → installs and configures MySQL
  • postgresql → installs and configures PostgreSQL

Key Concepts

  • Conditional execution using when
  • Grouping tasks with block
  • Dynamic configuration using templates
  • User input using vars_prompt
  • Handlers for service restarts

Summary

This lab demonstrates how Ansible can dynamically configure different services based on variable input, enabling flexible and reusable automation workflows.