Using Ansible to copy MySQL databases

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
become: true
- name: create a backup
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.

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

centos ansible_host=IP_address_here ansible_user=root
website1_development ansible_host=IP_address_here ansible_user=root

[Need urgent assistance to Copy MySQL databases using Ansible? – We are available 24*7]


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.

For Linux Tutorials

We create Linux HowTos and Tutorials for Sys Admins. Visit us on

Also for Tech related tips, Visit or General Technical tips on