How to copy MySQL databases using Ansible

In this guide, you will learn how to copy a MySQL database from one remote server to another using Ansible as the controller. Database migration in the world of DevOps is a challenging job but with Ansible this is can be very accomplished.

Ansible provides a featureful MySQL module. With the help of the module, we could copy databases between two hosts, create regular backups, users, and many more database operations.


  • Ansible Controller can successfully connect to both Server A and Server B.
  • Server A can SSH into Server B.
  • Both servers have MySQL server working.

Database Migration

The diagram below shows the steps involved in a MySQL database migration. The Ansible Controller is where our playbook is executed. Will use the mysql_db module to create a dump of the database. 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.

Let’s assume that we need to migrate the database “wordpress” which is hosted in the Production inventory to our development server called (neo_development).

  - hosts: production
    become: true
      - name: create a backup
          name: wordpress
          state: dump
          target: /var/www/html/wordpress.sql
          login_host: localhost
          login_user: root
          login_password: 123456
      - name: copy the database to the development server
        raw: rsync /var/www/html/wordpress.sql root@
      - name: import the database
          name: wordpress
          state: import
          target: /home/vagrant/wordpress.sql
          login_user: root
          login_password: '123456'
        delegate_to: neo_development

In this case, we will set the host to be “production“, this is because we want to store the backup file on the production server, not on the Ansible Controller.

Store your credentials in Ansible vaults!

The raw module lets us execute a raw shell command. Using rsync will transfer the backup to the development server (neo_development). In the final step, we will import the database.

The important note in step 3 is “delegate_to“. Delegate_to lets us run the command on the remote host machine.

Below is the inventory file which we have used in our example to let Ansible identify production and development machines.

centos ansible_host= ansible_user=root
neo_development ansible_host= ansible_user=root


Ansible speeds up your daily manual tasks by automating it. Database migration can be automated and this reduces the chances of making errors. In some cases, there are post-migration scripts that execute certain MySQL operations on the imported databases.

If you are looking to find out best practices using Ansible, read this article.