0
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?

boto v2 と boto3 で AssumeRole + リージョン固有 STS エンドポイントを使う方法

Last updated at Posted at 2025-06-20

AWS の AssumeRole 機能は、権限分離やクロスアカウント操作など、セキュアな運用において非常に重要です。しかし、プライベートネットワーク環境(VPCエンドポイント使用時など)では、グローバルエンドポイントではなくリージョン固有のエンドポイントを使用する必要があります。

この記事では、boto v2 と boto3 それぞれで、リージョン固有の STS エンドポイントを使って AssumeRole を行う方法 を解説します。

⚠️ 注意点
boto v2 は公式に非推奨 されています。
ただし、既存システムやレガシーコードでまだ使われているケースも多い ため、ここでは両方の実装を比較してご紹介します。
📦 前提条件
image.png

🛠️ boto v2 での実装(非推奨だが現実的な対応)

✅ 使用するクラス
RegionInfo
STSConnection

🔧 コード例
from boto.sts import STSConnection
from boto.regioninfo import RegionInfo

---- Step 1: RegionInfo を定義 ----

region_name = 'ap-northeast-1'
endpoint = 'sts.ap-northeast-1.amazonaws.com'

region = RegionInfo(
name=region_name,
endpoint=endpoint,
connection_cls=STSConnection
)

---- Step 2: STSConnection を生成 ----

sts = STSConnection(region=region)

---- Step 3: AssumeRole 実行 ----

assumed_role = sts.assume_role(
role_arn='arn:aws:iam::123456789012:role/YourTargetRole',
role_session_name='MySession'
)

---- Step 4: 取得した資格情報を使う ----

creds = assumed_role.credentials
print(f"AccessKeyId: {creds.access_key}")
print(f"SecretAccessKey: {creds.secret_key}")
print(f"SessionToken: {creds.session_token}")

🚀 boto3 での実装(推奨)

✅ 使用する機能
boto3.client('sts')
環境変数 AWS_STS_REGIONAL_ENDPOINTS=regional (オプション)
🔧 コード例
import boto3

---- Step 1: boto3 クライアント生成 ----

sts = boto3.client('sts', region_name='ap-northeast-1')

---- Step 2: AssumeRole 実行 ----

assumed_role = sts.assume_role(
RoleArn='arn:aws:iam::123456789012:role/YourTargetRole',
RoleSessionName='MySession'
)

---- Step 3: 取得した資格情報を使う ----

creds = assumed_role['Credentials']
print(f"AccessKeyId: {creds['AccessKeyId']}")
print(f"SecretAccessKey: {creds['SecretAccessKey']}")
print(f"SessionToken: {creds['SessionToken']}")

📝 まとめ

boto v2 のような非推奨環境でも、リージョン固有の STS エンドポイント経由で AssumeRole が可能であることを検証しました。
この記事が、古いシステムの改修や移行において、この情報が少しでもお役に立てば幸いです。

📢 (おまけ)
📁 boto v2 のソースコード場所確認方法

import boto
print(boto.__file__)

0
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
0
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?