Today I want to show you that how to calculate the sum size of a snapshot of Amazon EBS cost through EBS Direct API.
The price that you pay to use the EBS direct APIs depends on the requests you make [1].
We can use list-snapshot-blocks
in AWS CLI of EBS to get how many block of this snapshot used, and the unit of this number is sector
. A sector in Amazon EBS snapshot is 512KiB [2], so we can get the number of sectors about a snapshot then multiplying it by 512 KiB.
But here is a point need to notice, the max value of list-snapshot-blocks
is 10000 [3], and you need to check if there is a NextToken
of this snapshot. If it is, we need to use this token to run list-snapshot-blocks
again for a loop until this token become a empty value.
To calculate it easier, I just wrote a script here to get the sum of an EBS snapshot with while
loop, please refer to it:
#!/bin/sh
#set -x
SNAPSHOT_ID="<SNAPSHOT ID>"
REGION="<REGION>"
echo "===EBS Snapshot Calculator==="
echo "Getting Snapshot Blocks through EBS direct APIs..."
BLOCKS=`aws ebs list-snapshot-blocks --snapshot-id $SNAPSHOT_ID --region $REGION --output text | grep 'BLOCKS' | wc -l | awk '{print $1}'`
NEXT_TOKEN=`aws ebs list-snapshot-blocks --snapshot-id $SNAPSHOT_ID --region $REGION --query 'NextToken' --no-cli-pager | sed -e 's/"//g'`
while [ "$NEXT_TOKEN" != "null" ]
do
NEXT_BLOCKS=`aws ebs list-snapshot-blocks --snapshot-id $SNAPSHOT_ID --region $REGION --next-token $NEXT_TOKEN --output text | grep 'BLOCKS' | wc -l | awk '{print $1}'`
BLOCKS=$(($BLOCKS+$NEXT_BLOCKS));
NEXT_TOKEN=`aws ebs list-snapshot-blocks --snapshot-id $SNAPSHOT_ID --region $REGION --next-token $NEXT_TOKEN --query 'NextToken' --no-cli-pager | sed -e 's/"//g'`
done
KiB=$(($BLOCKS*512))
MiB=`echo "$KiB/1024" | bc`
GiB=`echo "$MiB/1024" | bc`
echo "The EBS Snapshot $SNAPSHOT_ID has $BLOCKS blocks, 1 block = 512 KiB.\nTotal cost: $(($BLOCKS*512)) KiB = $(($BLOCKS*512/1024)) MiB = $(($BLOCKS*512/1024/1024)) GiB $(($BLOCKS*512/1024%1024)) MiB"
Here is the output of this script:
$ sh snapshot_size.sh
===EBS Snapshot Calculator===
Getting Snapshot Blocks through EBS direct APIs...
The EBS Snapshot <SNAPSHOT ID> has 16384 blocks, 1 block = 512 KiB.
Total cost: 8388608 KiB = 8192 MiB = 8 GiB 0 MiB
Thanks for you reading.