安装aws-cli并安装jq
brew install awscli
brew install jq
配置
# 配置 AWS AK
aws configure
# 测试是否可用,查询EC2服务器列表
aws ec2 describe-instances
查询脚本
以下是查询脚本query.sh
# 查询当月入站流量
in=$(aws cloudwatch get-metric-statistics \
--namespace AWS/EC2 \
--metric-name NetworkIn \
--start-time "$(date -v-1m '+%Y-%m-01T00:00:00Z')" \
--end-time "$(date '+%Y-%m-01T00:00:00Z')" \
--period 2592000 \
--statistics Sum \
--dimensions Name=InstanceId,Value=i-0d9061485933c946b \
| jq '.Datapoints[].Sum / (1024*1024*1024)')
# 查询当月出站流量
out=$(aws cloudwatch get-metric-statistics \
--namespace AWS/EC2 \
--metric-name NetworkOut \
--start-time "$(date -v-1m '+%Y-%m-01T00:00:00Z')" \
--end-time "$(date '+%Y-%m-01T00:00:00Z')" \
--period 2592000 \
--statistics Sum \
--dimensions Name=InstanceId,Value=i-0d9061485933c946b \
| jq '.Datapoints[].Sum / (1024*1024*1024)')
# 总用量
sum=$(echo "$in $out" | awk '{printf "%.2f", $1 + $2}')
echo "本月入站用量: $in GB"
echo "本月出站用量: $out GB"
echo "本月总量用量: $sum GB"
查询结果
bash query.sh
本月入站用量: 11.260806784033775 GB
本月出站用量: 8.412478620186448 GB
本月总量用量: 19.67 GB