複数アカウントを回す3つの方法

別のアカウントの情報を読むには、そのアカウントのIAMロールを引き受ける(AssumeRole)のが基本だ。引き受け方によって3通りの書き方がある。

方法アカウントの指定向いている場面
A. SSO のプロファイルを並べるconfig にアカウントごとのプロファイルを書き、順に Session(profile_name=...)手元のPCで、数アカウントを対象に人が実行する
B. config の role_arn引き受けるロールを config に書くと、boto3 が自動で AssumeRole し、期限前に更新もする対象アカウントが固定で、数が少ない
C. コードで assume_roleOrganizations からアカウント一覧を取り、ループの中で AssumeRole するアカウントが多い・増減する。定期実行

方法Bの config は次のように書く。source_profile が「引き受ける側」の認証情報、role_arn が引き受けるロールだ。EC2 上で動かすなら、source_profile の代わりに credential_source = Ec2InstanceMetadata と書けば、インスタンスのロールから引き受けられる。

~/.aws/config(方法B)
[profile hub]
region = ap-northeast-1
# (hub 自体の認証情報は SSO やアクセスキーで用意しておく)

[profile prod-readonly]
role_arn = arn:aws:iam::111111111111:role/InventoryReadOnly
source_profile = hub
role_session_name = inventory-taro
region = ap-northeast-1

コード側は boto3.Session(profile_name="prod-readonly") と書くだけでよい。以下では、アカウント数が増えても対応できる方法Cを詳しく見る。

引き受けられる側のロールを用意する

各アカウントに、読み取り用のロール(ここでは InventoryReadOnly)を作る。ポイントは信頼ポリシーで、「どのアカウント・ロールからなら引き受けてよいか」を書く。権限ポリシーには、PART 01 で紹介した ViewOnlyAccess などや、必要なアクションだけを付ける。

信頼ポリシー(各アカウントの InventoryReadOnly ロール)
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::999999999999:role/InventoryRunner" },
      "Action": "sts:AssumeRole"
    }
  ]
}

999999999999 はスクリプトを動かす側(ハブ)のアカウント、InventoryRunner はそこで使うロールだ。ハブ側のロールには、sts:AssumeRole を arn:aws:iam::*:role/InventoryReadOnly に対して許可しておく。全アカウントに同じロールを配るには、CloudFormation StackSets を使うと楽だ。

assume_role で全アカウントを回す

Organizations の list_accounts でアカウント一覧を取り、各アカウントのロールを引き受けて、PART 04 の棚卸しを実行する例だ。list_accounts を呼べるのは、管理アカウントか、Organizations の委任管理者として登録されたアカウントだけである点に注意する。

multi_account.py
"""Organizations の全アカウントで、EC2 / RDS / Lambda の棚卸しを実行する。"""
import boto3
from botocore.exceptions import ClientError

from awsutil import enabled_regions, paginate, run_per_region
from inventory import collect_per_region

ROLE_NAME = "InventoryReadOnly"
hub = boto3.Session(profile_name="hub", region_name="ap-northeast-1")


def assume(account_id, region="ap-northeast-1"):
    """指定アカウントのロールを引き受けた Session を返す。"""
    sts = hub.client("sts")
    cred = sts.assume_role(
        RoleArn=f"arn:aws:iam::{account_id}:role/{ROLE_NAME}",
        RoleSessionName="inventory",       # CloudTrail に残る。誰の処理か分かる名前にする
        DurationSeconds=3600,
    )["Credentials"]
    return boto3.Session(
        aws_access_key_id=cred["AccessKeyId"],
        aws_secret_access_key=cred["SecretAccessKey"],
        aws_session_token=cred["SessionToken"],
        region_name=region,
    )


org = hub.client("organizations")
accounts = [a for a in paginate(org, "list_accounts", "Accounts")
            if a.get("State", a.get("Status")) == "ACTIVE"]

all_rows = []
for acct in accounts:
    try:
        session = assume(acct["Id"])
    except ClientError as e:
        print(f'[skip] {acct["Id"]} {acct["Name"]}: {e.response["Error"]["Code"]}')
        continue
    rows, errors = run_per_region(session, enabled_regions(session), collect_per_region)
    for r in rows:
        r["account"] = f'{acct["Id"]} ({acct["Name"]})'
    all_rows += rows
    print(f'{acct["Id"]} {acct["Name"]}: {len(rows)} resources, skipped regions {len(errors)}')

all_rows を CSV に出すときは、PART 04 の COLUMNS の先頭に "account" を加えて書き出せばよい。

  • 一時的な認証情報には期限がある:assume_role で得た認証情報は既定で1時間有効だ(ロールの最大セッション時間まで延ばせる)。ただし、引き受けたロールからさらに別のロールを引き受ける「ロールの連鎖」では最大1時間に制限される。1アカウントの処理が長引く場合は、アカウントごとに引き受け直す今の形が安全だ
  • 方法Bとの違い:config の role_arn を使うと期限前の更新は boto3 が自動で行うが、上のように自分で assume_role した認証情報は更新されない
  • RoleSessionName は監査の手がかり:各アカウントの CloudTrail には、この名前で呼び出しが記録される。定期実行なら inventory-batch のように用途が分かる名前にしておく

エラーの切り分けの順番

ここからはトラブルシューティングだ。PART 01 の図で見たとおり、リクエストは「認証情報を決める → 送る → AWS が判定する」の順に進む。手前から順に確かめると早い。

① 認証情報は見つかっているか?
 └─ NoCredentialsError / ProfileNotFound / SSO のトークン切れ
② 想定した「誰」として接続しているか?
 └─ PART 02 の whoami.py(get_caller_identity)で Account と Arn を確認
③ リージョンは合っているか?
 └─ NoRegionError / 結果が0件 / 有効化していないリージョン
④ AWS まで届いているか?
 └─ EndpointConnectionError / SSL のエラー / タイムアウト
⑤ AWS に拒否されていないか?
 └─ AccessDenied / UnauthorizedOperation / ExpiredToken / スロットリング

エラー別の原因と対処

例外・エラーコードメッセージの例主な原因対処
NoCredentialsErrorUnable to locate credentialsプロファイルも環境変数もロールもないプロファイル名、AWS_PROFILE の綴りを確認。EC2 ならインスタンスプロファイルの有無
ProfileNotFoundThe config profile (dev) could not be foundconfig にそのプロファイルがないsession.available_profiles で確認。[profile dev] の書式か
UnauthorizedSSOTokenError ほかThe SSO session associated with this profile has expired…SSO トークンの期限切れaws sso login --profile dev(PART 02)
NoRegionErrorYou must specify a region.リージョンの設定がないregion_name を指定、または config に region
ParamValidationErrorParameter validation failed: Unknown parameter in input…引数名の誤り・型の誤り。AWS に送る前に検出される大文字始まりの引数名か、リストで渡すべき値か(Values=["x"])を確認
EndpointConnectionErrorCould not connect to the endpoint URL…リージョン名の誤り、ネットワーク・プロキシ、そのリージョンにないサービスURL のリージョン部分を確認。社内ネットワークならプロキシ設定(HTTPS_PROXY)
SSLErrorcertificate verify failed社内プロキシが通信を検査し、独自の証明書を挟んでいる社内のルート証明書を AWS_CA_BUNDLE(または config の ca_bundle)で指定。検証の無効化はしない
ExpiredTokenThe security token included in the request is expired一時的な認証情報の期限切れ(古い環境変数・長時間の処理)環境変数を消す/ロールを引き受け直す
InvalidClientTokenId / UnrecognizedClientException / AuthFailureThe security token included in the request is invalidキーの誤り・無効化済み、または有効化していないリージョンへの呼び出しwhoami.py で確認。リージョンは describe_regions() の一覧に絞る
SignatureDoesNotMatch などSignature expired: … is now earlier than …PCの時計のずれOSの時刻同期を確認
AccessDenied / UnauthorizedOperation… is not authorized to perform: ec2:DescribeInstances …権限不足(IAMポリシー・SCP・権限境界・リソースポリシーのどれか)メッセージ中のアクション名を許可する。下の節を参照
Throttling / RequestLimitExceededRate exceeded呼び出しが多すぎるstandard モードで試行回数を増やす、並列数を減らす(PART 03)

AccessDenied を読み解く

権限エラーのメッセージには、拒否されたアクション名と、拒否の理由の種類が含まれていることが多い。まずメッセージを最後まで読むのが近道だ。

メッセージの例
An error occurred (AccessDeniedException) when calling the ListFunctions operation:
User: arn:aws:sts::123456789012:assumed-role/InventoryReadOnly/inventory
is not authorized to perform: lambda:ListFunctions on resource: *
with an explicit deny in a service control policy
  • because no identity-based policy allows ...:IAMポリシーに許可がない → ロールにアクションを追加する
  • with an explicit deny in a service control policy:組織の SCP で拒否されている → 自分のロールをいくら直しても通らない。組織の管理者に確認する(使わないリージョンを SCP で禁止している組織は多い)
  • ... permissions boundary:権限境界で制限されている

EC2 の UnauthorizedOperation では、詳細がエンコードされた文字列で返ることがある。これは STS の decode_authorization_message で読める(sts:DecodeAuthorizationMessage の権限が必要)。

decode_message.py
import json
import re

import boto3
from botocore.exceptions import ClientError

session = boto3.Session(profile_name="dev", region_name="ap-northeast-1")
ec2 = session.client("ec2")
try:
    ec2.describe_instances()
except ClientError as e:
    m = re.search(r"Encoded authorization failure message: (\S+)", e.response["Error"]["Message"])
    if m:
        decoded = session.client("sts").decode_authorization_message(EncodedMessage=m.group(1))
        detail = json.loads(decoded["DecodedMessage"])
        print(json.dumps(detail, indent=2, ensure_ascii=False))
    else:
        print(e)

それでも分からないときはログを見る

boto3 の内部ログを出すと、どのエンドポイントに、どの認証情報の取得元で、何回リトライしたかが分かる。

debug_log.py
import logging

import boto3

boto3.set_stream_logger("botocore", logging.DEBUG)   # 大量に出るので調査時だけ

session = boto3.Session(profile_name="dev", region_name="ap-northeast-1")
session.client("sts").get_caller_identity()

ログには「Found credentials in ...」(認証情報の取得元)や、送信先のURL、リトライの有無が出る。ただし、リクエストやレスポンスの中身も出力されるため、ログをそのまま人に共有しない。アカウントIDやリソース名を伏せてから共有する。

✅ CloudTrail からも確認できる

AWS 側に届いて拒否された呼び出しは、CloudTrail のイベント履歴に errorCode: AccessDenied として記録される。スクリプトの実行ログが残っていなくても、いつ・どのロールで・どのAPIが拒否されたかを後から確認できる。boto3 で検索する方法は PART 07 の逆引きにまとめた。

✅ 次の記事では…

最終回の PART 07 では、boto3 で取得できる主な情報をサービス・目的別に一覧にし、「こういうことを知りたい」から使うAPIを引ける逆引きをまとめる。

→ PART 07 — 付録:boto3で取得できる情報一覧と逆引きへ