You need to enable JavaScript to run this app. 计算Lambda按客户端时区自动启停的Windows AWS EC2总运行时长的脚本方案
优惠活动
大模型
产品
解决方案
定价
更多

计算Lambda按客户端时区自动启停的Windows AWS EC2总运行时长的脚本方案

Windows系统AWS EC2累计运行时长统计方案

方案适配性说明

由于实例配置了Lambda自动启停规则,Windows本地系统的开机时长会在每次停止启动后重置,无法直接累加得到全周期的累计值,需依托AWS侧的实例生命周期状态事件计算全量运行片段的时长,统计精度和账单计费口径一致。

可直接复用的PowerShell脚本

运行前提:

  • 实例已绑定具备ec2:DescribeInstances、ec2:DescribeInstanceStatus权限的IAM角色,无需手动配置访问密钥
  • 已在实例上安装AWS Tools for PowerShell模块
# 从实例元数据自动获取实例ID与所在区域
$metadataBase = "http://169.254.169.254/latest/meta-data"
$instanceId = (Invoke-RestMethod -Uri "$metadataBase/instance-id")
$region = (Invoke-RestMethod -Uri "$metadataBase/placement/region")
Set-DefaultAWSRegion -Region $region

# 初始化统计参数
$instanceInfo = Get-Ec2Instance -Instance $instanceId
$launchTime = $instanceInfo.Instances.LaunchTime
$currentTime = Get-Date
$totalRunSeconds = 0

# 分页拉取全量状态变更事件
$nextToken = $null
do {
    $statusEvents = Get-EC2InstanceStatus `
        -InstanceId $instanceId `
        -StartTime $launchTime `
        -EndTime $currentTime `
        -MaxResults 1000 `
        -NextToken $nextToken
    foreach ($event in $statusEvents) {
        # 匹配所有状态切换到运行的时间点
        if ($event.InstanceState.Name -eq "running") {
            $runStartTime = $event.Timestamp
            # 查找该次运行后的第一个停止时间点
            $stopEvent = $statusEvents | 
                Where-Object {$_.Timestamp -gt $runStartTime -and $_.InstanceState.Name -eq "stopped"} | 
                Sort-Object Timestamp | 
                Select-Object -First 1
            if ($stopEvent) {
                # 累加该段运行的时长
                $totalRunSeconds += ($stopEvent.Timestamp - $runStartTime).TotalSeconds
            } else {
                # 若当前仍处于运行状态,累加截至当前时间的时长
                $totalRunSeconds += ($currentTime - $runStartTime).TotalSeconds
            }
        }
    }
    $nextToken = $statusEvents.NextToken
} while ($nextToken)

# 格式化输出统计结果
$totalRunHours = [math]::Round($totalRunSeconds / 3600, 2)
Write-Host "实例自创建以来累计运行总时长:$totalRunHours 小时"

边界注意事项

  • EC2实例状态事件的原始记录默认仅保留90天,如需统计超过90天的历史累计时长,需提前从已归档的CloudTrail日志中拉取更早的状态变更记录补充计算
  • 脚本统计的时长和AWS账单中对应的实例运行计费时长完全匹配,不会存在本地时区、系统计时重置带来的偏差

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.01 05:54:02