首页 > 解决方案 > 实例平均 CPU 利用率未显示,但其他所有内容都显示了吗?

问题描述

目前我有一个记录正在运行的实例的平均 CPUUtilization 的函数。但问题是这个 cloudwatch 功能即使在配置 CPU 利用率时放置了 time.sleep 以让实例有时间开始运行,但它仍然不显示平均 CPU 利用率,如下面的错误消息所示.

#!/usr/bin/env python3
import sys
import boto3
import time
ec2 = boto3.resource('ec2', region_name = 'eu-west-1')
s3 = boto3.resource('s3')
keyname = 'key1.pem'
s3_resource = boto3.resource('s3')
user_data = '''#!/bin/bash
yum update -y
yum install httpd -y
systemctl enable httpd
systemctl start httpd'''

try:
        resp = s3.create_bucket(ACL='private',Bucket='buket2',C$
        print (resp)
except Exception as error:
    print (error)

try:
        s3_resource.Bucket('buket2').upload_file('image.jpg', 'image$

try:
        gg = ec2.create_security_group(GroupName='Server', Description = '$
        print (gg)
except Exception as error:
    print (error)

response = sg.authorize_ingress(
    IpPermissions=[
        {
            "FromPort": 22,
            "ToPort": 22,
            "IpProtocol": "tcp",
            "IpRanges": [
                {"CidrIp": "0.0.0.0/0", "Description": "Server"},
            ],
        },
        {
            "FromPort": 80,
            "ToPort": 80,
            "IpProtocol": "tcp",
            "IpRanges": [
                {"CidrIp": "0.0.0.0/0", "Description": "Server1"},
            ],
        },
    ],
)
instance = ec2.create_instances(
 ImageId='ami-03odd1b743b23e5d2',
 MinCount=1,
 MaxCount=1,
 InstanceType='t2.nano',
 KeyName = 'key1.pem',
 UserData = user_data, 
 SecurityGroupIds=[sg.group_id] 
)


from datetime import datetime, timedelta
time.sleep(390)
client = boto3.client('cloudwatch')
response = client.get_metric_statistics(
            Namespace='AWS/EC2',
            MetricName='CPUUtilization',
            Dimensions=[
                {
                'Name': 'AMIID',
                'Value': 'ami-03odd1b743b23e5d2'
                },
            ],
            StartTime=datetime(2021, 7, 17) - timedelta(seconds=300),
            EndTime=datetime(2021, 7, 17),
            Period=300,
            Statistics=[
                'Average',
            ],
            Unit='Percent'
        )
print(response)

for cpu in response['Datapoints']:
  print(cpu)
s3.Bucket(name='buket2')
ec2.SecurityGroup(id='sg-06b84927ae5rd3ad1')
{'Label': 'CPUUtilization', 'Datapoints': [], 'ResponseMetadata': {'RequestId': 'ba4352d5-67ee-4d51-b03f-d1c532dbfe7', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'ba421b45-63dd-4d51-b03f-d14212e2fe7', 'content-type': 'text/xml', 'content-length': '337', 'date': 'Sun, 18 Jul 2021 00:26:57 GMT'}, 'RetryAttempts': 0}}
sg-06b84927ae5rd3ad1

标签: amazon-web-servicesamazon-ec2boto3amazon-cloudwatch

解决方案


Period通常会设置为 5 分钟,除非您为实例启用了详细监控。然后也可以设置为 1 分钟。

您的StartTimeEndTime仅相隔 5 分钟。在如此短的时间跨度内可能没有度量点。


推荐阅读