Memo/AmazonWebServices/SDK/Python

https://dexlab.net:443/pukiwiki/index.php?Memo/AmazonWebServices/SDK/Python
 

AWS SDK(boto, boto3)


SwitchRole/AssumeRole


V4署名リクエスト


テスト


awscliのproflieを使った認証

  • 例: awscli configure --profile exampleで設定した認証情報を使い、account_idを表示
    • aws_profile.py
      #!/usr/bin/env python
      # -*- coding: utf-8 -*-
      
      import boto3
      from boto3.session import Session
      from pprint import pprint
      
      session = Session(profile_name='example')
      client = session.client('sts')
      account_id = client.get_caller_identity()["Account"]
      print("account_id:", account_id)
  • 例: awscli configure --profile loginで設定した認証情報を使い、StsAssumeRole「1234567890/example-assumerole-readonly」へ切り替えて、account_idを表示
    • aws_assumerole.py
      #!/usr/bin/env python
      # -*- coding: utf-8 -*-
      
      import boto3
      from boto3.session import Session
      from pprint import pprint
      
      def sts_assume_role(session, account_id, role_name):
          role_arn = "arn:aws:iam::" + account_id + ":role/" + role_name
          session_name = account_id + role_name
          region = "ap-northeast-1"
      
          client = session.client('sts')
      
          response = client.assume_role(
              RoleArn=role_arn,
              RoleSessionName=session_name
          )
      
          session = Session(
              aws_access_key_id = response['Credentials']['AccessKeyId'],
              aws_secret_access_key = response['Credentials']['SecretAccessKey'],
              aws_session_token = response['Credentials']['SessionToken'],
              region_name = region
          )
      
          return session
      
      session = Session(profile_name='login')
      client = session.client('sts')
      account_id = client.get_caller_identity()["Account"]
      print("account_id:", account_id)
      
      account_id = "1234567890"
      role_name = "example-assumerole-readonly"
      session2 = sts_assume_role(session, account_id,role_name)
      client2 = session2.client('sts')
      account_id2 = client2.get_caller_identity()["Account"]
      print("account_id:", account_id2)

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2019-11-26 (火) 14:06:32 (20d)