取得漏れの原因:1回で返る件数には上限がある
一覧を返すAPIの多くは、1回の呼び出しで返す件数に上限がある。上限を超えると、レスポンスに「続きを取るためのトークン」が入り、それを付けてもう一度呼び出す必要がある。PART 01 の最小コードのように1回しか呼ばないと、件数が上限を超えたときに残りが黙って切り捨てられる。エラーにならないので気付きにくいのが厄介だ。
上限とトークンの名前はAPIごとにばらばらだ(各APIのリファレンスより)。
| API | 1回で返る件数 | 続きのトークン |
|---|---|---|
Lambda list_functions | 最大50件 | NextMarker |
CloudWatch Logs describe_log_groups | 最大50件 | nextToken |
CloudTrail lookup_events | 最大50件 | NextToken |
RDS describe_db_instances | 既定100件 | Marker |
IAM list_users | 既定100件 | Marker(IsTruncated で判定) |
S3 list_objects_v2 | 最大1,000件 | NextContinuationToken |
Lambda 関数が51個以上ある環境で list_functions() を1回呼ぶだけだと、50個しか返らない。「棚卸しの表に一部の関数が載っていない」という事故はこうして起きる。
Paginator で全件を取る
トークンの名前や判定方法の違いを吸収してくれるのが Paginator だ。client.get_paginator("API名") で作り、paginate() の結果をループすると、続きのページを自動で取りに行く。
import boto3
session = boto3.Session(profile_name="dev", region_name="ap-northeast-1")
lambda_client = session.client("lambda")
paginator = lambda_client.get_paginator("list_functions")
functions = []
for page in paginator.paginate(): # ページ単位で返る
functions.extend(page["Functions"])
print(f"{len(functions)} functions")そのAPIに Paginator があるかは client.can_paginate("list_functions") で確かめられる。ページングするAPIのほとんどには Paginator が用意されているが、Cost Explorer の get_cost_and_usage のように用意されていないものもある。その場合は、次のようにトークンを自分で受け渡す。
def call_all_pages(func, result_key, token_key="NextPageToken", **kwargs):
"""Paginator が無いAPI用。トークンが返らなくなるまで呼び続け、result_key の要素を連結する。"""
items = []
while True:
resp = func(**kwargs)
items.extend(resp.get(result_key, []))
token = resp.get(token_key)
if not token:
return items
kwargs[token_key] = tokenPaginator には、次のオプションを PaginationConfig で渡せる。
| キー | 意味 | 使いどころ |
|---|---|---|
PageSize | 1回の呼び出しで要求する件数 | スロットリングが出るときに小さくする、上限まで大きくして呼び出し回数を減らす |
MaxItems | 全体で取得する最大件数 | 動作確認で「最初の10件だけ見たい」とき |
StartingToken | 途中から再開するトークン | 大量の取得を中断・再開するとき |
絞り込み:サーバー側か、手元か
絞り込みの方法は2つある。APIの引数で絞る(サーバー側)と、全件取ってから Python で絞る(手元)だ。件数が多いほどサーバー側で絞ったほうが速いが、使える条件はAPIによって決まっている。
サーバー側:Filters(EC2 など)
EC2 の describe_* 系は Filters 引数に対応している。同じ Name の中の Values は OR、異なる Name どうしは AND で評価される。
import boto3
session = boto3.Session(profile_name="dev", region_name="ap-northeast-1")
ec2 = session.client("ec2")
filters = [
{"Name": "instance-state-name", "Values": ["running", "stopped"]}, # running または stopped
{"Name": "tag:Env", "Values": ["prod"]}, # かつ Env=prod
]
paginator = ec2.get_paginator("describe_instances")
for page in paginator.paginate(Filters=filters):
for r in page["Reservations"]:
for inst in r["Instances"]:
print(inst["InstanceId"], inst["State"]["Name"])よく使うフィルター名は instance-state-name、instance-type、vpc-id、tag:キー名(タグの値で絞る)、tag-key(タグの有無で絞る)などだ。使えるフィルター名はAPIリファレンスの各APIのページに一覧がある。RDS の describe_db_instances も Filters を受け付けるが、使える名前は engine や db-cluster-id など少数に限られる。
手元:JMESPath で取り出す
Paginator の search() を使うと、AWS CLI の --query と同じ JMESPath 式で、ページをまたいで必要な部分だけを取り出せる。EC2 の深い入れ子を平らにするのに便利だ。
import boto3
session = boto3.Session(profile_name="dev", region_name="ap-northeast-1")
ec2 = session.client("ec2")
paginator = ec2.get_paginator("describe_instances")
# Reservations の入れ子を平らにして、インスタンスを1件ずつ受け取る
for inst in paginator.paginate().search("Reservations[].Instances[]"):
print(inst["InstanceId"], inst["InstanceType"])
# 条件付き:t3 系だけ
for inst in paginator.paginate().search("Reservations[].Instances[?starts_with(InstanceType, 't3.')][]"):
print(inst["InstanceId"], inst["InstanceType"])💡 JMESPath の絞り込みは手元で行われる
search() の条件はダウンロード後に Python 側で評価される。通信量やAPIの呼び出し回数は減らないので、件数が多いときはまず Filters で絞り、残りを JMESPath や Python の内包表記で整える、という順に組み合わせる。
エラー処理:ClientError を読む
AWS 側でエラーになった場合、boto3 は botocore.exceptions.ClientError を送出する。エラーの種類は例外クラスではなく、e.response["Error"]["Code"] の文字列で判別する。
import boto3
from botocore.exceptions import ClientError
session = boto3.Session(profile_name="dev", region_name="ap-northeast-1")
iam = session.client("iam")
try:
role = iam.get_role(RoleName="not-exists-role")
except ClientError as e:
code = e.response["Error"]["Code"] # 例: NoSuchEntity / AccessDenied
message = e.response["Error"]["Message"]
status = e.response["ResponseMetadata"]["HTTPStatusCode"]
print(f"{code} ({status}): {message}")NoSuchEntity (404): The role with name not-exists-role cannot be found.情報取得のスクリプトでは、「権限がない」ものは記録して先に進むのが実用的だ。権限エラーのコードはサービスによって表記が違う点に注意する。
| エラーコード | 主なサービス | 意味 |
|---|---|---|
AccessDenied / AccessDeniedException | IAM・S3 / Lambda・Cost Explorer など | 権限がない |
UnauthorizedOperation | EC2 | 権限がない |
Throttling / ThrottlingException / RequestLimitExceeded | 各サービス / EC2 | 呼び出しが多すぎる(自動でリトライされる) |
AuthFailure / UnrecognizedClientException | EC2 / その他 | 認証情報が無効、または有効化していないリージョン |
サービス固有のエラーは、iam.exceptions.NoSuchEntityException のように client の属性として例外クラスも用意されている。特定のエラーだけを捕まえたいときは、こちらを使うと読みやすい。
import boto3
iam = boto3.Session(profile_name="dev").client("iam")
try:
iam.get_role(RoleName="not-exists-role")
except iam.exceptions.NoSuchEntityException:
print("ロールがありません")リトライとタイムアウトの設定
スロットリングや一時的な通信エラーは、botocore が自動でリトライする。何も設定しないと legacy モード(最大5回の試行)になる。全リージョン・全アカウントを回すように呼び出し回数が多いスクリプトでは、standard モードにして試行回数を増やしておくと安定する。
import boto3
from botocore.config import Config
config = Config(
retries={"total_max_attempts": 10, "mode": "standard"}, # 初回を含めて最大10回
connect_timeout=5, # 接続のタイムアウト(秒)
read_timeout=60, # 応答待ちのタイムアウト(秒)
)
session = boto3.Session(profile_name="dev", region_name="ap-northeast-1")
ec2 = session.client("ec2", config=config)
resp = ec2.describe_regions()
print("リトライした回数:", resp["ResponseMetadata"]["RetryAttempts"])total_max_attempts は初回の呼び出しを含めた回数だ。古い記事にある max_attempts は「リトライの回数」を表すので、max_attempts: 3 は初回と合わせて4回になる。混同しやすいので total_max_attempts を使うのがよい。config ファイルにプロファイル単位で書くこともできる(retry_mode = standard、max_attempts = 10)。
スロットリングが多発する場合は、mode を adaptive にすると、クライアント側で送信の間隔を自動で調整する。ただし公式ドキュメントでは実験的な機能とされているので、まずは standard で試す。
全リージョンを回す
EC2 や RDS は、リージョンごとに呼び出さないと全体が分からない。対象リージョンの一覧の取り方は2通りある。
| 方法 | 返るもの | 注意点 |
|---|---|---|
ec2.describe_regions() | そのアカウントで有効なリージョン | APIを1回呼ぶ。AllRegions=True にすると無効なリージョンも含む |
session.get_available_regions("ec2") | boto3 が知っているリージョンすべて | APIを呼ばない。有効化していないオプトインリージョンも含まれ、そこを呼ぶと認証エラーになる |
棚卸しには describe_regions() を使うのが確実だ。ここまでのパターンを、PART 04 以降で使う共通モジュールにまとめておく。
"""boto3 シリーズで共通に使うヘルパー。"""
from concurrent.futures import ThreadPoolExecutor, as_completed
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
CONFIG = Config(retries={"total_max_attempts": 10, "mode": "standard"},
connect_timeout=5, read_timeout=60)
DENIED = {"AccessDenied", "AccessDeniedException", "UnauthorizedOperation",
"AuthFailure", "UnrecognizedClientException"}
def make_session(profile=None, region="ap-northeast-1"):
return boto3.Session(profile_name=profile, region_name=region)
def enabled_regions(session):
"""アカウントで有効なリージョン名の一覧(名前順)。"""
ec2 = session.client("ec2", config=CONFIG)
return sorted(r["RegionName"] for r in ec2.describe_regions()["Regions"])
def tags_to_dict(tags):
return {t["Key"]: t["Value"] for t in (tags or [])}
def paginate(client, operation, result_key, **kwargs):
"""Paginator で全ページを取り、result_key の要素を連結して返す。"""
items = []
for page in client.get_paginator(operation).paginate(**kwargs):
items.extend(page.get(result_key, []))
return items
def clone_session(session, region):
"""同じ認証情報で、指定リージョンの新しい Session を作る(スレッドごとに使う)。
認証情報はその時点の値で固定されるため、1時間を超える処理では期限切れに注意する。
"""
c = session.get_credentials().get_frozen_credentials()
return boto3.Session(aws_access_key_id=c.access_key, aws_secret_access_key=c.secret_key,
aws_session_token=c.token, region_name=region)
def run_per_region(session, regions, func, max_workers=8):
"""func(session, region) をリージョンごとに並列実行し、(結果リスト, エラーリスト) を返す。
権限がない・無効なリージョンは止めずにエラーリストへ記録する。
"""
results, errors = [], []
with ThreadPoolExecutor(max_workers=max_workers) as pool:
# Session はスレッドセーフではないため、リージョン(タスク)ごとに作ってから渡す
futures = {pool.submit(func, clone_session(session, region), region): region
for region in regions}
for fut in as_completed(futures):
region = futures[fut]
try:
results.extend(fut.result())
except ClientError as e:
code = e.response["Error"]["Code"]
if code not in DENIED:
raise
errors.append((region, code))
return results, errors並列化するときの注意
リージョンを1つずつ順番に回すと、リージョンの数(多くのアカウントで17前後)だけ待ち時間が積み重なる。上の run_per_region のようにスレッドで並列に呼ぶと、全体の時間を大きく縮められる。その際、次の点に気を付ける。
- Session はスレッド間で共有しない:公式ドキュメントでは、client はスレッドセーフだが、Session と resource はスレッドセーフではないとされている。上のモジュールでは、
clone_sessionで元の Session の認証情報を取り出し、タスクごとに新しい Session を作って渡している。この形なら、PART 06 で扱う「別アカウントのロールを引き受けた Session」でもそのまま使える - 同時実行数は控えめに:同じアカウント・同じリージョンへの呼び出しが集中するとスロットリングが起きる。
max_workersは 4〜8 程度から始め、standard モードのリトライと組み合わせる - 結果の順番は保証されない:
as_completedは終わった順に返すので、表にするときはリージョン名などで並べ替える
順番に回す場合との差は、ネットワークの距離やリソースの数で大きく変わる。手元の環境で次のように計測してみると、並列化する価値があるかを判断できる。
import time
from awsutil import enabled_regions, make_session, paginate, run_per_region, CONFIG
def count_instances(session, region):
ec2 = session.client("ec2", region_name=region, config=CONFIG)
insts = paginate(ec2, "describe_instances", "Reservations")
return [(region, sum(len(r["Instances"]) for r in insts))]
session = make_session("dev")
regions = enabled_regions(session)
t = time.perf_counter()
seq = [count_instances(session, r)[0] for r in regions]
print(f"順番に実行: {time.perf_counter() - t:.1f} 秒")
t = time.perf_counter()
par, errors = run_per_region(session, regions, count_instances)
print(f"並列に実行: {time.perf_counter() - t:.1f} 秒 / エラー {errors}")✅ 次の記事では…
PART 04 では、この回のパターンを組み合わせて、全リージョンの EC2・RDS・S3・Lambda を1つの表にまとめる棚卸しスクリプトを作る。