Automate Your Wordpress Farm Backups & Updates

This maybe usefull if you are responsible of a high number of Wordpress sites.

Concept

The target here is to backup & update (core, db and plugins) a Wordpress farm, i mean, a bunch of different Wps over several servers.

Tools

In case your servers run PHP v5.3+ you may know wp-cli, if not, go try! wp-cli allows you to run different Wp tasks on command-line, so great point to automate.

My tool of choice to manage servers is Ansible, an infrastructure automation tool, simple and to the point.

Approach

We want to set the servers and paths, and path to the backups. We want to have one in case any update breaks something. Also we may need a name for the backup files.

So we need to associate a name and a path to each Wp host.

Structured data per host on Ansible

In order to accomplish such a structured data per host on Ansible I didn’t find any proper way, as the inventory file doesn’t to support this. I opened a Feature request for that.

After trying several dict approaches, my solution, was to associate the host on a list (I couldn’t make a dict to work), through a var-name relation such as:

1
2
3
4
5
6
7
8
9
10
# inventory
111.111.111.111 server=hostingA

# vars
hostingA
- [ 
    domain1.tld ,
    /var/www/vhosts/domain1.tld/httpdocs/blog 
  ]
- [ ...

You can test this with the debug command:

1
2
debug: host={{ item }} msg="host {{ inventory_hostname }} - var_server {{ server }} - var_name {{ item[0] }}"
  with_nested: server

Tasks

Now the data per host is set and we can target as follows:

1
2
3
shell: wp db export {{ backup_path }}/{{ item[0] }}.sql
    chdir={{ item[1] }}
    with_nested: server

This lacks a nice informative timestamp.

Timestamps on Ansible

Again Ansible doesn’t provide a standarized way of timestamp. There is another Feature Request, closed, but it is recently taking relevance.

So I managed to get it from a register:

1
2
shell: date '+%Y_%m_%d_%H%M'
    register: timestamp

Now we can make a proper log name such as:

1
shell: wp db export {{ backup_path }}/{{ item[0] }}.{{ timestamp.stdout }}.sql

I made a playbook to install wp-cli, backup Wp files & db, and update Wp core, db & plugins.

Results

You can take a look to the final role available at Github.

First make a small task manually, then automate it. Second add complex manually, then:

Automate all the things!

Comments