How to get the information of organizations, Cost Explorer of another AWS account with Lambda (python)

Conclusion

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

Processing on the account A side

1. Create a role for lambda in account A

2. Attach the required policy to get the information to the role

CostExplorerFullAccess, AWSOrganizationsFullAccess, etc.

3. Press Edit Trusts on the Role Summary Trusts tab.

キャプチャ.PNG

4. Paste and update the following policy.

{
  "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"
    }
  ]
}

Account B side processing (IAM)

1. Create a role for account B and give it the required permissions.

Give Administrator Access for the time being

2. From the Roles Overview Permissions tab, press Add Inline Policy

3. Click the Json tab, paste the following as an inline policy and press Confirm Policy to apply

{
    "Version": "2012-10-17",
    "Statement": {
        "Effect": "Allow",
        "Action": "sts:AssumeRole",
        "Resource": "arn:aws:iam::Account number of account A:role/Account A role name"
    }
}

Account B side processing (lambda)

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

How to get the information of organizations, Cost Explorer of another AWS account with Lambda (python)
PhytoMine-I tried to get the genetic information of plants with Python
I tried to get the movie information of TMDb API with Python
Note: How to get the last day of the month with python (added the first day of the month)
How to get a list of files in the same directory with python
[Introduction to Python] How to get the index of data with a for statement
Get information equivalent to the Network tab of Chrome developer tools with Python + Selenium
How to get into the python development environment with Vagrant
[Introduction to Python] How to get data with the listdir function
Get the source of the page to load infinitely with python.
How to get the Python version
How to get started with Python
How to get the ID of Type2Tag NXP NTAG213 with nfcpy
[Python] How to get the first and last days of the month
Connect to s3 with AWS Lambda Python
Summary of how to write AWS Lambda
[Yahoo! Weather Replacement Version] How to get weather information with LINE Notify + Python
How to crop the lower right part of the image with Python OpenCV
How to get the date and time difference in seconds with python
[Introduction to Python] How to sort the contents of a list efficiently with list sort
I tried to get the authentication code of Qiita API with Python.
How to deal with the problem that build fails when CI / CD of Python Function with AWS Amplify
Get the latest AMI information with the AWS CLI
How to specify attributes with Mock of python
How to get dictionary type elements of Python 2.7
How to get the files in the [Python] folder
[AWS / Lambda] How to load Python external library
Summary of studying Python to use AWS Lambda
Python script to get note information with REAPER
How to get the variable name itself in python
Add information to the bottom of the figure with Matplotlib
[Introduction to Python] How to iterate with the range function?
[Python] How to specify the download location with youtube-dl
I want to AWS Lambda with Python on Mac!
[Python] Summary of how to specify the color of the figure
[Python] How to rewrite the table style with python-pptx [python-pptx]
Extract the band information of raster data with python
How to identify the element with the smallest number of characters in a Python list?
How to get started with Visual Studio Online ~ The end of the environment construction era ~
How to check in Python if one of the elements of a list is in another list
How to count the number of occurrences of each element in the list in Python with weight
The 15th offline real-time I tried to solve the problem of how to write with python
Try to get the function list of Python> os package
I tried to get the location information of Odakyu Bus
I want to specify another version of Python with pyvenv
Run the program without building a Python environment! !! (How to get started with Google Colaboratory)
How to write offline real time I tried to solve the problem of F02 with Python
Minimum knowledge to get started with the Python logging module
[AWS] Try adding Python library to Layer with SAM + Lambda (Python)
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
I want to get the operation information of yahoo route
How to scrape stock prices of individual stocks from the Nikkei newspaper website with Python
Try to automate the operation of network devices with Python
How to know the number of GPUs from python ~ Notes on using multiprocessing with pytorch ~
How to get a list of built-in exceptions in python
Try to import to the database by manipulating ShapeFile of national land numerical information with Python
How to use Python lambda
Get Alembic information with Python
Process the gzip file UNLOADed with Redshift with Python of Lambda, gzip it again and upload it to S3
Memo of the program to get the date in two digits with javascript, Ruby, Python, shell script
[Python] Convert CSV file uploaded to S3 to JSON file with AWS Lambda