How to read cross-account CloudWatch metrics programmatically?

1

Hi, I want to ask about how to get CloudWatch metrics from another (shared) account in the organization, when I'm working in the monitoring account.

I want to collect CloudWatch metrics from every account in the organization, and then process them in a central place in the monitoring account. Since we create and delete AWS accounts frequently, it isn't feasible to create a fixed dashboard to collect all metrics in the console.

I have tried to share CloudWatch metrics from an account to a central monitoring account. Although I can access the metrics in the console, it seems to fail when I call cloudwatch_client.get_metric_data in the Python code. I have set up the cross-account metrics sharing config, but the code (using credentials from the monitoring account) is not authorized to perform cloudwatch:GetMetricData on the shared account's instances.

Is there anything wrong that I have done? If so, how can I use CloudWatch Python client to read metrics of a shared account in my monitoring account.

AzNorm
gefragt vor 2 Jahren3607 Aufrufe
1 Antwort
2

The CloudWatch cross account features is enabled via a role in each source account, called CloudWatch-CrossAccountSharingRole. That role gives the monitoring account GetMetricData API access.

To retrieve metrics from source accounts you just need to assume CloudWatch-CrossAccountSharingRole and then call GetMetricData with the credentials returned from assume role. Code would be something like (note: untested):

sts = boto3.client("sts", region_name="us-east-1")
account_b = sts.assume_role(
    RoleArn="arn:aws:iam::012345678901:role/CloudWatch-CrossAccountSharingRole",
    RoleSessionName="cross_acct_cloud",
)
access_key = account_b["Credentials"]["AccessKeyId"]
secret_key = account_b["Credentials"]["SecretAccessKey"]
session_token = account_b["Credentials"]["SessionToken"]
cloudwatch = boto3.client(
    "cloudwatch",
    aws_access_key_id=access_key,
    aws_secret_access_key=secret_key,
    aws_session_token=session_token,
)
res = cloudwatch.get_metric_data(...)
AWS
beantwortet vor 2 Jahren

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen