Via G. Falcone 5, Pollenza (MC), Italy
+39 0733 203595

EC2 snapshots automating with Ansible

We were looking for a way to have our EC2 EBS volumes snapshotted on a daily basis.

We already use AWS and Ansible, so the solution comes quite straightforward:

Ansible + AWS = Daily Snapshots

Our procedure works with Ansible >= 2.1.

First step is about gathering every information required to build the snapshot from a given name:

{{ name }} is the tag instance on which we want to operate.

As a second step we might want to verify if the snapshot already exists. If yes, then you can use “del_snapshot” to delete it (as showed later).

Next step is about creating the snapshot:

In detail:

  • add_volume_device_name: device where making the snapshot on
  • snapshot_tags: key value item that can be chosen at will, very important to tag items

Finally, we delete the old snapshot:

Now we proceed with the creation of the playbook:

In detail:

  • add_snapshot: this option creates the snapshot
  • del_snapshot: this option deletes the snapshot

We have all the elements to create our snapshot. We proceed with a bash script:

In detail:

  • why “infrastructure_add_components_ec2.yml”? because the playbook is used to add other components too (topics for another article!)
  • name: is the tag instance on which we want to operate
  • add_snapshot/del_snapshot: changes the flags true and false as you need

Now we schedule the execution of a cron for creating the snapshot.

Pay attention to data integrity. As written into the official documentation:

“You can take a snapshot of an attached volume that is in use. However, snapshots only capture data that has been written to your Amazon EBS volume at the time the snapshot command is issued. This might exclude any data that has been cached by any applications or the operating system. If you can pause any file writes to the volume long enough to take a snapshot, your snapshot should be complete. However, if you can’t pause all file writes to the volume, you should unmount the volume from within the instance, issue the snapshot command, and then remount the volume to ensure a consistent and complete snapshot. You can remount and use your volume while the snapshot status is pending.”

It was not the case, but you must check.

We have a simple daily snapshot system.


Leave a reply