Calling getMetricsData cloudwatch API using boto3 in Lambda code returns access denied error

Viewed 548

I am calling GetMetricData cloudwatch API using boto 3 Python in Lambda code, but getting access denied error.

"errorMessage": "An error occurred (AccessDenied) when calling the GetMetricData operation: User: arn:aws:sts::xxxxxxxxxxxxx:assumed-role/lambda_test15mins-role-88yy778/lambda_test15mins is not authorized to perform: cloudwatch:GetMetricData",

Any help would be appreciated!

Here is the code used

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'
    }
)
1 Answers

You can add inline policy to your lambda execution role:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "cloudwatch:GetMetricData",
            "Resource": "*"
        }
    ]
}
Related