fbpx

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.

Enjoy!

Loreno Edelmondo
Loreno Edelmondo
Articoli: 24

2 commenti

  1. Just curios to know whether above playbook performs snapshots of the multiple volumes(instances) at once. I see that you are using ‘ec2_instances.instances.0.id’ value which performes snapshot only for the first instance.

    • Our example does it for a single volume. you can edit the script as you need and take multi-volume snapshots.

Rispondi a RaviCancella risposta

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *

Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.