See the document below. .. .. .. .. https://aws.amazon.com/jp/premiumsupport/knowledge-center/lambda-function-assume-iam-role/
I don't understand at all even if I read it, so With the account (account A) that has the information you want to get I tried it with the account (account B) I want to pass it to
CostExplorerFullAccess, AWSOrganizationsFullAccess, etc.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": [
"arn:aws:iam::Account number of account B:role/service-role/Account B role name"
],
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
Give Administrator Access for the time being
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": "arn:aws:iam::Account number of account A:role/Account A role name"
}
}
The boto3 documentation has detailed instructions on how to get it. See below for details. https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sts.html https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/organizations.html https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ce.html#CostExplorer.Client.get_cost_forecast https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetCostAndUsage.html
import boto3
def lambda_handler(event, context):
#Get a set of security credentials used to access other accounts AWS resources
sts_connection = boto3.client('sts')
acct_b = sts_connection.assume_role(
RoleArn="arn:aws:iam::Account number of account A:role/Account A role name",
RoleSessionName="cross_acct_lambda"
)
ACCESS_KEY = acct_b['Credentials']['AccessKeyId']
SECRET_KEY = acct_b['Credentials']['SecretAccessKey']
SESSION_TOKEN = acct_b['Credentials']['SessionToken']
#Get information about organizations in account A
organizations = boto3.client(
'organizations',
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY,
aws_session_token=SESSION_TOKEN,
)
responses = []
res = {}
while True:
if 'NextToken' in res:
res = organizations.list_accounts(NextToken = res['NextToken'])
else:
res = organizations.list_accounts()
responses += res['Accounts']
if 'NextToken' not in res:
break
print(responses)
#Get information about CostExplorer for account A
ce = boto3.client(
'ce',
region_name='us-east-1',
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY,
aws_session_token=SESSION_TOKEN,
)
response = ce.get_cost_and_usage(
TimePeriod = {"Start": "2020-10-01", "End": "2020-11-01"},
Granularity = 'MONTHLY',
Metrics = ["UnblendedCost"],
GroupBy=[{'Type': 'DIMENSION','Key': 'LINKED_ACCOUNT'}]
)
print(response)
Recommended Posts