在 Lambda 代码 returns 中使用 boto3 调用 getMetricsData cloudwatch API 访问被拒绝错误
Calling getMetricsData cloudwatch API using boto3 in Lambda code returns access denied error
我在 Lambda 代码中使用 boto 3 Python 调用 GetMetricData cloudwatch API,但出现拒绝访问错误。
"errorMessage": "调用 GetMetricData 操作时发生错误 (AccessDenied): 用户: arn:aws:sts::xxxxxxxxxxxxx:assumed-role/lambda_test15mins-role-88yy778/lambda_test15mins 无权执行: cloudwatch:GetMetricData",
如有任何帮助,我们将不胜感激!
这里是使用的代码
import json
import logging
import os
import boto3
import datetime
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
def lambda_handler(event, context):
client = boto3.client(service_name='cloudwatch', region_name='us-east-2')
response = client.get_metric_data(
MetricDataQueries=[
{
'Id': 'XXXXXXXXXXXXXX',
'MetricStat': {
'Metric': {
'Namespace': 'CMS_API',
'MetricName': 'API_Endpoint_Errors_Metrics',
'Dimensions': [
]
},
'Period': 2000,
'Stat': 'Sum',
'Unit': 'Count'
}
},
],
StartTime= datetime.datetime.now(),
EndTime= datetime.datetime.now() - datetime.timedelta(minutes=15),
NextToken='string',
ScanBy='TimestampDescending',
MaxDatapoints=123,
LabelOptions={
'Timezone': 'string'
}
)
您可以将 inline policy 添加到您的 lambda execution role
:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "cloudwatch:GetMetricData",
"Resource": "*"
}
]
}
我在 Lambda 代码中使用 boto 3 Python 调用 GetMetricData cloudwatch API,但出现拒绝访问错误。
"errorMessage": "调用 GetMetricData 操作时发生错误 (AccessDenied): 用户: arn:aws:sts::xxxxxxxxxxxxx:assumed-role/lambda_test15mins-role-88yy778/lambda_test15mins 无权执行: cloudwatch:GetMetricData",
如有任何帮助,我们将不胜感激!
这里是使用的代码
import json
import logging
import os
import boto3
import datetime
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
def lambda_handler(event, context):
client = boto3.client(service_name='cloudwatch', region_name='us-east-2')
response = client.get_metric_data(
MetricDataQueries=[
{
'Id': 'XXXXXXXXXXXXXX',
'MetricStat': {
'Metric': {
'Namespace': 'CMS_API',
'MetricName': 'API_Endpoint_Errors_Metrics',
'Dimensions': [
]
},
'Period': 2000,
'Stat': 'Sum',
'Unit': 'Count'
}
},
],
StartTime= datetime.datetime.now(),
EndTime= datetime.datetime.now() - datetime.timedelta(minutes=15),
NextToken='string',
ScanBy='TimestampDescending',
MaxDatapoints=123,
LabelOptions={
'Timezone': 'string'
}
)
您可以将 inline policy 添加到您的 lambda execution role
:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "cloudwatch:GetMetricData",
"Resource": "*"
}
]
}