Sometimes, there is need for Website Administrators to perform Database migrations from one server to another. With Ansible as the controller, MySQL databases can be easily moved from one remote server to another.
Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform SQL related tasks.
In this context, we shall look into the steps to copy MySQL databases using Ansible.
Lets say that we need to migrate the database "website1" which is hosted in the Production inventory to our development server called (website1_development).
Here we will use the mysql_db module to create a dump of the database. Further, using rsync we will copy the database to the other server.
After successfully copying the database will use the mysql_db module to import the database.
---
- hosts: production
become: true
tasks:
- name: create a backup
mysql_db:
name: website1
state: dump
target: /var/www/html/website1.sql
login_host: localhost
login_user: root
login_password: 123456
Here, we want to store the backup file on the production server, not on the Ansible Controller. Thus, we will set the host to be "production" in this case.
The raw module lets us execute a raw shell command. For instance, it helps us to use the rsync command to transfer the backup to the development server (website1_development).
- name: copy the database to the development server
raw: rsync /var/www/html/website1.sql root@IP_address_here:/home/username/website1.sql
Finally, we will import the database. Note to replace the IP address, username, and password with the actual values.
- name: import the database
mysql_db:
name: website1
state: import
target: /home/username/website1.sql
login_host: IP_address_here
login_user: root
login_password: '123456'
delegate_to: website1_development
Here, Delegate_to lets us run the command on the remote host machine.
Further, below is the inventory file which we have used in our example to let Ansible identify production and development machines:
[production]
centos ansible_host=IP_address_here ansible_user=root
[development]
website1_development ansible_host=IP_address_here ansible_user=root
This article will guide us on how to perform database migration using Ansible as the controller which can help to copy a MySQL database from one remote server to another.