boto 相当于 AWS 客户端命令

huangapple go评论58阅读模式
英文:

boto equivalent of aws client command

问题

我有这个正常工作的命令。
但我想要使用boto代替。

import boto3

cloudwatch = boto3.client('cloudwatch', region_name='ap-south-1')

response = cloudwatch.get_metric_statistics(
    Namespace='AWS/RDS',
    MetricName='DBLoad',
    StartTime='2023-06-12T21:00:00Z',
    EndTime='2023-06-12T23:59:00Z',
    Period=60,
    Statistics=['Average'],
    Dimensions=[
        {
            'Name': 'DBInstanceIdentifier',
            'Value': 'sql-rds'
        }
    ]
)

boto是否支持所有参数?

英文:

I have this command that works as expected.
But I will like to use boto instead.

aws cloudwatch get-metric-statistics \
    --region ap-south-1 \
    --namespace AWS/RDS \
    --metric-name DBLoad  \
    --period 60 \
    --statistics Average \
    --start-time 2023-06-12T21:00:00Z \
    --end-time 2023-06-12T23:59:00Z \
    --dimensions Name=DBInstanceIdentifier,Value=sql-rds

Does boto support all the parameters?

答案1

得分: 2

AWS CloudWatch功能,包括get_metric_statistics操作,在Boto3中可用。

请查看这里:Boto3文档 - CloudWatch客户端 - get_metric_statistics

使用Boto3 - 代码如下:

import boto3
from datetime import datetime, timedelta

client = boto3.client('cloudwatch', region_name='ap-south-1')

response = client.get_metric_statistics(
    Namespace='AWS/RDS',
    MetricName='DBLoad',
    Dimensions=[
        {
            'Name': 'DBInstanceIdentifier',
            'Value': 'sql-rds'
        },
    ],
    StartTime=datetime(2023, 6, 12, 21, 0, 0),
    EndTime=datetime(2023, 6, 12, 23, 59, 0),
    Period=60,
    Statistics=['Average']
)

print(response)

> 注意
> AWS不再官方维护Boto
> Boto文档可能不是最新的
> 它不提供与Boto3相同级别的AWS服务支持。

但是,如果您需要使用Boto,文档在这里:boto.ec2.cloudwatch

使用Boto - 代码如下:

import boto

conn = boto.connect_cloudwatch()
region = 'ap-south-1'

namespace = 'AWS/RDS'
metric_name = 'DBLoad'
dimensions = {'DBInstanceIdentifier': 'sql-rds'}

start_time = '2023-06-12T21:00:00Z'
end_time = '2023-06-12T23:59:00Z'

period = 60
statistics = ['Average']

response = conn.get_metric_statistics(
    period=period,
    start_time=start_time,
    end_time=end_time,
    metric_name=metric_name,
    namespace=namespace,
    statistics=statistics,
    dimensions=dimensions,
    region=region
)

print(response)
英文:

The AWS CloudWatch functionality, including the get_metric_statistics operation, is available in Boto3

See here: Boto3 documentation - CloudWatch Client - get_metric_statistics

Using Boto3 - the code would be :

import boto3
from datetime import datetime, timedelta

client = boto3.client('cloudwatch', region_name='ap-south-1')

response = client.get_metric_statistics(
    Namespace='AWS/RDS',
    MetricName='DBLoad',
    Dimensions=[
        {
            'Name': 'DBInstanceIdentifier',
            'Value': 'sql-rds'
        },
    ],
    StartTime=datetime(2023, 6, 12, 21, 0, 0),
    EndTime=datetime(2023, 6, 12, 23, 59, 0),
    Period=60,
    Statistics=['Average']
)

print(response)

> N.B.
> Boto is no longer officially maintained by AWS
> Boto documentation might not be up-to-date
> It does not provide the same level of support for AWS
> services as Boto3.

However, if you need to use Boto the documentation is here: boto.ec2.cloudwatch

Using Boto - the code would be :

import boto

conn = boto.connect_cloudwatch()
region = 'ap-south-1'

namespace = 'AWS/RDS'
metric_name = 'DBLoad'
dimensions = {'DBInstanceIdentifier': 'sql-rds'}

start_time = '2023-06-12T21:00:00Z'
end_time = '2023-06-12T23:59:00Z'

period = 60
statistics = ['Average']

response = conn.get_metric_statistics(
    period=period,
    start_time=start_time,
    end_time=end_time,
    metric_name=metric_name,
    namespace=namespace,
    statistics=statistics,
    dimensions=dimensions,
    region=region
)

print(response)

答案2

得分: 1

以下是使用 boto3 的方式进行操作:

import boto3
import matplotlib.pyplot as plt
from tabulate import tabulate
from unskript.enums.aws_k8s_enums import StatisticsType
from datetime import datetime, timedelta

timestamps = []
values = []
cloudwatchClient = boto3.client('cloudwatch', region_name='ap-south-1')
start_time = datetime(2023, 6, 12, 21, 0, 0)
end_time = datetime(2023, 6, 12, 23, 59, 0)
dimensions = [{'Name': 'name-1', ... }]
metric_name = 'DBLoad' # 在您的情况下
period = 60 # 返回数据点的粒度(以秒为单位)。
statistics = ['Average'] # 在您的情况下

res = cloudwatchClient.get_metric_data(
      MetricDataQueries=[
        {
            'Id': metric_name.lower(),
            'MetricStat': {
                'Metric': {
                    'Namespace': 'AWS/RDS',
                    'MetricName': metric_name,
                    'Dimensions': dimensions
                },
                'Period': period,
                'Stat': statistics,
            },
        },
    ],
    StartTime= start_time,
    EndTime=end_time,
    ScanBy='TimestampAscending'
)

for timestamp in res['MetricDataResults'][0]['Timestamps']:
    timestamps.append(timestamp)
for value in res['MetricDataResults'][0]['Values']:
    values.append(value)

timestamps.sort()
values.sort()

plt.plot_date(timestamps, values, "-o")

data = []
for dt, val in zip(
    res['MetricDataResults'][0]['Timestamps'],
    res['MetricDataResults'][0]['Values']
    ):
    data.append([dt.strftime('%Y-%m-%d::%H-%M'), val])
head = ["Timestamp", "Value"]
table = tabulate(data, headers=head, tablefmt="grid")

print(table)

如果您需要更多帮助或有其他问题,请随时提出。

英文:

You can do it this way using boto3-

import boto3
import matplotlib.pyplot as plt
from tabulate import tabulate
from unskript.enums.aws_k8s_enums import StatisticsType
from datetime import datetime, timedelta

timestamps = []
values = []
cloudwatchClient = boto3.client('cloudwatch', region_name='ap-south-1')
start_time = datetime(2023, 6, 12, 21, 0, 0)
end_time = datetime(2023, 6, 12, 23, 59, 0)
dimensions = [{'Name': 'name-1', ... }]
metric_name = 'DBLoad' # in your case
period = 60 #The granularity, in seconds, of the returned data points.
statistics = ['Average'] #in your case

res = cloudwatchClient.get_metric_data(
      MetricDataQueries=[
        {
            'Id': metric_name.lower(),
            'MetricStat': {
                'Metric': {
                    'Namespace': 'AWS/RDS',
                    'MetricName': metric_name,
                    'Dimensions': dimensions
                },
                'Period': period,
                'Stat': statistics,
            },
        },
    ],
    StartTime= start_time,
    EndTime=end_time,
    ScanBy='TimestampAscending'
)

for timestamp in res['MetricDataResults'][0]['Timestamps']:
    timestamps.append(timestamp)
for value in res['MetricDataResults'][0]['Values']:
    values.append(value)

timestamps.sort()
values.sort()

plt.plot_date(timestamps, values, "-o")

data = []
for dt, val in zip(
    res['MetricDataResults'][0]['Timestamps'],
    res['MetricDataResults'][0]['Values']
    ):
    data.append([dt.strftime('%Y-%m-%d::%H-%M'), val])
head = ["Timestamp", "Value"]
table = tabulate(data, headers=head, tablefmt="grid")

print(table)

huangapple
  • 本文由 发表于 2023年6月13日 12:36:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76461714.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定