Ansible for Databases
What DBAs automate with Ansible, idempotent PostgreSQL tasks, patching Oracle safely in waves, running Ansible for the team, and best practices.
What DBAs automate with Ansible
Ansible is where most day-to-day DBA automation lives: preparing servers, installing and patching database software, creating databases and users, running health checks, and refreshing test environments. This lesson shows how those jobs look as playbooks, with patching as the main example, and the practices that keep them safe.
| Task | How it's done with Ansible |
|---|---|
| Server preparation | Packages, the oracle user, kernel parameters, limits, and directories, as in Playbooks and Modules |
| Software install | Copy the installer, render a response file from a template, and run a silent install, guarded by creates: so it runs only once |
| Database creation | Run dbca silently with a templated response file, or use database modules for PostgreSQL and MySQL |
| Patching | Prechecks, patch in batches, run datapatch, and verify, as shown below |
| Users and grants | Idempotent modules for PostgreSQL and MySQL; checked SQL scripts for Oracle |
| Health checks and compliance | Gather versions, parameters, backup status, and security settings from every server into one report |
| Test refreshes | Restore or clone production, mask sensitive data, and reset passwords, in one playbook |
| Standard files | Keep sqlnet.ora, tnsnames.ora, /etc/oratab, and backup scripts the same everywhere |
An idempotent example: PostgreSQL
For PostgreSQL and MySQL, collections provide true database modules, so creating a database and a user is safe to run any number of times:
- name: Sales database and its read-only user
hosts: postgres
become: true
become_user: postgres
tasks:
- name: Ensure the sales database exists
community.postgresql.postgresql_db:
name: sales
state: present
- name: Ensure the reporting user exists
community.postgresql.postgresql_user:
name: sales_ro
password: "{{ vault_sales_ro_password }}"
state: present
no_log: true
- name: Give it read access to the sales schema
community.postgresql.postgresql_privs:
database: sales
roles: sales_ro
type: table
schema: public
objs: ALL_IN_SCHEMA
privs: SELECT
Patching Oracle with Ansible
Quarterly patching across many Oracle databases is the classic DBA automation project. A safe playbook follows the same steps a careful DBA would, on each server in turn:
# patch_oracle.yml (simplified)
- name: Apply the Oracle Release Update
hosts: oracle # run with --limit test first, then --limit prod
become: true
become_user: oracle
serial: [1, 2] # one server first, then two at a time
max_fail_percentage: 0
tasks:
- name: Patch this server
block:
- name: Precheck free space in the Oracle home filesystem
ansible.builtin.assert:
that: (ansible_mounts | selectattr('mount', 'equalto', '/u01') | first).size_available > 15000000000
fail_msg: "Less than 15 GB free on /u01"
- name: Check the patch for conflicts
ansible.builtin.command: >
{{ oracle_home }}/OPatch/opatch prereq CheckConflictAgainstOHWithDetail
-ph {{ patch_dir }}
changed_when: false
- name: Stop the database and listener
ansible.builtin.shell: |
. ~/.bash_profile
echo "SHUTDOWN IMMEDIATE" | sqlplus -s / as sysdba
lsnrctl stop
- name: Apply the Release Update
ansible.builtin.command: "{{ oracle_home }}/OPatch/opatch apply -silent {{ patch_dir }}"
- name: Start the database and listener, then run datapatch
ansible.builtin.shell: |
. ~/.bash_profile
lsnrctl start
echo "STARTUP" | sqlplus -s / as sysdba
{{ oracle_home }}/OPatch/datapatch -verbose
rescue:
- name: Stop and alert the DBA team
ansible.builtin.fail:
msg: "Patching failed on {{ inventory_hostname }}. Rollout stopped. See the log."
- block and rescue
- Tasks in a
blockrun in order; if any fails, therescuetasks run instead, much like exception handling. Here, rescue stops the run and raises an alert; it could also roll the patch back. - serial: [1, 2]
- Patch one server first, as a canary, then two at a time, finishing each batch before starting the next.
- assert
- Checks a condition and fails with a clear message if it's not true, which makes prechecks easy to read.
Running Ansible for the team
- From a pipeline: playbooks run from GitHub Actions, GitLab CI, or Jenkins on every merge, with lint and check mode on every pull request.
- From AWX or Ansible Automation Platform: a web interface where playbooks become job templates that others can run with a click, with permissions, schedules, surveys for inputs, and a full log of every run.
- After Terraform: the pipeline runs Terraform to build servers, then Ansible to configure them, finding them through a dynamic inventory or Terraform's outputs.
- From events: Event-Driven Ansible runs a playbook when monitoring raises an alert, such as adding space when a filesystem fills up.
Best practices
- Keep everything in Git, reviewed through pull requests, and pin collection versions.
- Use full module names, and prefer modules to
commandandshell; make commands safe to repeat. - Name every task clearly; the names are the log of what happened.
- Lint and dry-run every change; try it on a test server with
--limitfirst. - Roll out in batches with
serial, stop on failure, and handle errors withblockandrescue. - Keep secrets in Ansible Vault or a central vault, and use
no_log: true. - Keep separate inventories per environment, and check
--list-hostsbefore production runs. - Run playbooks twice in testing: the second run should report
changed=0. - Test roles automatically, for example with Molecule, which runs a role on throwaway containers or VMs and checks the result.
Key takeaways
- Ansible handles DBA work from server preparation and installs to patching, users, health checks, and refreshes.
- PostgreSQL and MySQL have idempotent database modules; Oracle work often uses carefully written commands, or community collections.
- Safe patching playbooks run prechecks, patch in waves with
serial, and stop withblockandrescuewhen anything fails. - Prefer out-of-place patching in production, and patch standbys or RAC nodes first.
- Run Ansible from pipelines, AWX, or events, after Terraform builds the servers, and follow the best practices to keep it safe.