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.
How 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
- name: create a backup
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.
Transferring and importing the database backup
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
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:
centos ansible_host=IP_address_here ansible_user=root
website1_development ansible_host=IP_address_here ansible_user=root