AWS – Script to create EC2 snapshots and automatically rename them

amazon ec2amazon-web-servicesparsingrename

I'm currently trying to setup a script (using AWS CLI from an Ubuntu server) that will do the following:

  • Create a snapshot of every existing volume. Those volumes already have a NAME tag (Like SERVER1, SERVER1DATA, SERVER2, SERVER2DATA etc).

  • Rename those snapshots taken with the same tag NAMES (so then, on the AWS console i could filter them by date and would be able to easily identificate them).

The automatic rename is my main issue here.

I've been toying with ec2-describe-volumes , ec2-create-snapshot and ec2addtag commands but my scripting is not that good. So far i've been able to setup this by creating a list with VOLUME NAME and NAME TAG (those parameters are then taken by the ec2addtag) but i would have to manually update that list every time i add or remove a volume on the environment.

Any help will be greatly appreciated it.

Best Answer

I'm not positive I understand your question completely, but if what you want is to be able to generate a list of your volumes, along with name tags, something like this might work:

aws ec2 describe-tags --query "Tags[*].{Name:Value,ResourceId:ResourceId}" --filters "Name=key,Values=Name"  --filters "Name=resource-type,Values=volume" --output json

Basically what that says is "Give me the resource id and the value of the tag "name" for every resource of type "Volume". In this case, I specified json as the output. You may also specify "text" or "table" depending on your needs.

Another approach:

aws ec2 describe-volumes --query "Volumes[*].{ID:VolumeId}" --output text

This would return a list of your volumes. If you piped this to a text file, the file would just contain a list of volume identifiers - one per line.

You could then get the Name tag for each volume in the list with something like this:

aws ec2 describe-tags --query "Tags[*].{Name:Value,ResourceId:ResourceId}" --filters "Name=key,Values=Name"  --filters "Name=resource-type,Values=volume" --filters "Name=resource-id,Values=vol-2e293949" --output json

This is basically saying "give me the resource id and the value of the tag name for the specified id vol-2e293949.

As you can see the CLI commands can be hard to read and the filtering and querying is a bit difficult. (These examples use a recent version of the AWS CLI)