1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

AWS Lambdaの中からPythonでAWSアカウントIDを取得

Last updated at Posted at 2021-05-18

Pythonで書かれたAWS Lambdaの中からAWSのアカウントIDを取得するには、

account_id = boto3.client("sts").get_caller_identity()["Account"]

これで12桁の文字列を取得できす。

なお、リージョンやLambdaの名前などは環境変数から取得できます。

AWS Lambda 環境変数の使用 - AWS Lambda

例: os.environ["AWS_REGION"]

試したサンプルコード

ここではServerless Frameworkを使っています。

Serverless Frameworkのプロジェクト作成

$ serverless create --template aws-python3

serverless.yml 作成

 service: sample01
 frameworkVersion: '2'
 
 provider:
   name: aws
   runtime: python3.8
   lambdaHashingVersion: 20201221
 
   stage: dev
   region: ap-northeast-1
 
 functions:
   hello:
     handler: handler.hello
     events:
       - httpApi:
           path: /
           method: get

handler.py 作成

 import json
 import boto3
 
 def hello(event, context):
     sts_client = boto3.client("sts")
     account_id = sts_client.get_caller_identity()["Account"]
 
     body = {
         "account_id": account_id
     }
 
     response = {
         "statusCode": 200,
         "body": json.dumps(body)
     }
 
     return response

デプロイ

$ serverless deploy -v

デプロイするとURLが表示されますので、アクセスしてみます。

$ curl 'https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/'

{"account_id": "123456789012"} というようなJSONが表示されます。

削除

$ serverless remove
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?