You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计EC2实例处于停止状态的总天数?(附现有查询命令)

计算EC2停止实例的已停止天数

我明白你已经能通过AWS CLI筛选出停止状态的EC2实例并拿到它们的停止时间信息,接下来要搞定的就是计算这些实例已经停了多少天对吧?这其实可以通过把现有命令和一些文本处理、时间计算工具结合起来实现,我给你一步步拆解:

核心思路

你的现有命令输出里,StateTransitionReason字段包含了实例转入停止状态的时间(格式类似User initiated (2024-05-20T12:34:56Z)),我们需要:

  1. 从这个字段里提取出具体的时间戳
  2. 将时间戳转换为可计算的格式(比如Unix时间戳)
  3. 和当前时间计算差值,转换成天数

完整实现命令

Linux环境下的版本

aws ec2 describe-instances --region us-west-2 --filters "Name=instance-state-code,Values=80" --query 'Reservations[].Instances[].[Tags[?Key==`Name`] | [0].Value, State.Name, StateTransitionReason]' --output text | while read -r name state reason; do
    # 提取括号中的停止时间字符串
    stop_time=$(echo "$reason" | grep -oP '\(\K[^)]+')
    # 转换为Unix时间戳(秒数)
    stop_unix=$(date -d "$stop_time" +%s)
    # 获取当前时间的Unix时间戳
    current_unix=$(date +%s)
    # 计算已停止天数(取整数,忽略不足一天的部分)
    days=$(( (current_unix - stop_unix) / 86400 ))
    # 格式化输出,处理无名称标签的情况
    echo "实例名称: ${name:-无名称} | 已停止天数: $days 天"
done | sort -k 4,4n

macOS环境下的版本(date命令参数不同)

aws ec2 describe-instances --region us-west-2 --filters "Name=instance-state-code,Values=80" --query 'Reservations[].Instances[].[Tags[?Key==`Name`] | [0].Value, State.Name, StateTransitionReason]' --output text | while read -r name state reason; do
    stop_time=$(echo "$reason" | grep -oP '\(\K[^)]+')
    # macOS下的时间戳转换方式
    stop_unix=$(date -j -f "%Y-%m-%dT%H:%M:%SZ" "$stop_time" +%s)
    current_unix=$(date +%s)
    days=$(( (current_unix - stop_unix) / 86400 ))
    echo "实例名称: ${name:-无名称} | 已停止天数: $days 天"
done | sort -k 4,4n

关键步骤解释

  • while read -r name state reason:逐行读取AWS CLI输出的三个字段(实例名称、状态、转换原因)
  • grep -oP '\(\K[^)]+':用正则表达式精准提取括号里的时间字符串,\(\K表示匹配到(之后忽略前面的内容,只取到)之前的部分
  • Unix时间戳计算:把ISO格式的停止时间和当前时间都转成从1970年开始的秒数,这样直接相减就能得到总秒数,除以86400(一天的秒数)就得到天数
  • ${name:-无名称}:处理那些没有设置Name标签的实例,避免输出空值
  • 最后的sort -k 4,4n:按已停止天数从小到大排序,方便你快速找到停最久的实例

内容的提问来源于stack exchange,提问作者beginnertopython

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:44:38