Kanji
・クラウドエンジニア / フリーランス ・1993年生まれ ・愛媛県出身 / 東京都渋谷区在住 ・AWS歴5年 プロフィールの詳細
目次
python3.12
python3.11
PowerShell 7.4
InputPayload
sys.argv
def handler(events, context):
events
outputs
$.Payload.*
$0.00003/秒
aws:executeScript
僕がマルチアカウント環境の運用自動化を進める中で、「オペレーターに強い IAM 権限を渡さず、マネジメントコンソールから承認付きで安全に Python スクリプトを実行したい」と考え、AWS Systems Manager(SSM)オートメーションの aws:executeScript アクションを採用したときのことです。
普段の AWS Lambda と同じ感覚で CloudFormation と Python コードを書いてデプロイしたところ、初日から 3 つの手戻りに直面しました。
FalconPythonWrapper.lambda_handler
def script_handler(events, context):
sha256
ModuleNotFoundError
modules.zip
files.checksums.sha256
time.sleep()
while
time.sleep(30)
$0.00003 / 秒
aws:waitForAwsResourceProperty
この記事では、こうした現場での失敗と検証ログを踏まえ、 aws:executeScript の内部アーキテクチャ、データ受け渡しの正確な実装パターン、CloudFormation / Terraform の完全な定義コード、そして最小権限 IAM とコスト最適化の勘所をまとめます。
▲ AWS Systems Manager Automation における aws:executeScript の隔離実行基盤(Falcon Sandbox)とデータ連携アーキテクチャ
SSM オートメーションの aws:executeScript は、ランブック(SSM Document)のステップ内で独自の Python または PowerShell スクリプトをサーバーレスに実行できるアクションです。
実際に aws:executeScript 内で os.environ をダンプしてみると分かりますが、このアクションは AWS が内部管理する専用アカウント上の AWS Lambda 環境(通称 Falcon コンテナ) で実行されています。
os.environ
{ "_HANDLER": "FalconPythonWrapper.lambda_handler", "AWS_EXECUTION_ENV": "AWS_Lambda_python3.12", "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "512", "AWS_LAMBDA_FUNCTION_NAME": "Falcon-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "AWS_LAMBDA_LOG_GROUP_NAME": "/aws/lambda/Falcon-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "LAMBDA_TASK_ROOT": "/var/task", "PYTHONPATH": "/var/runtime:/tmp/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "TZ": ":UTC" }
この環境変数から読み取れる通り、設計時に必ず押さえておくべきハードウェア・ネットワーク制約があります。
TimeoutSeconds
/tmp
aws:runCommand
「普通の AWS Lambda 関数を作るのと何が違うのか?」「VPC 内のサーバーや DB を操作したい場合はどうするのか?」という疑問に対しては、以下の基準で使い分けます。
aws:invokeLambdaFunction
aws:approve
以前は python3.7 や python3.8 が広く使われていましたが、現在それらはサポート終了(廃止)となっています。新規作成および既存ランブックのリライト時は、必ず python3.12 または python3.11 (PowerShell の場合は PowerShell 7.4 )を指定してください。
python3.7
python3.8
python3.10
python3.9
PowerShell 7.2
PowerShell Core 6.0
$.Payload
aws:executeScript で最も間違いやすいのが、ランブックのパラメータをスクリプトへ渡し、スクリプトの処理結果を後続ステップへ引き渡すデータフローです。
runbook.py
Python の場合、 inputs.Handler に <ファイル名(拡張子なし)>.<関数名> (インラインスクリプトの場合は <関数名> のみ)を指定します。関数シグネチャは必ず def handler(events, context): とし、 InputPayload で渡したキーを events.get("キー名") で取り出します。
inputs.Handler
<ファイル名(拡張子なし)>.<関数名>
<関数名>
events.get("キー名")
# src/runbook.py import logging from typing import Any, Dict, List import boto3 from botocore.exceptions import ClientError logger = logging.getLogger() logger.setLevel(logging.INFO) def main(events: Dict[str, Any], context: Any) -> Dict[str, Any]: """ SSM Automation aws:executeScript エントリポイント InputPayload の内容は第1引数 `events` (dict) として渡される。 """ target_tag_key = events.get("TagKey", "Environment") target_tag_value = events.get("TagValue", "Staging") dry_run = str(events.get("DryRun", "true")).lower() == "true" print(f"[INFO] Starting scan: Tag {target_tag_key}={target_tag_value}, DryRun={dry_run}") ec2 = boto3.client("ec2") matched_instance_ids: List[str] = [] try: # Describe 系 API は件数上限による取りこぼしを防ぐため必ず Paginator を使用する paginator = ec2.get_paginator("describe_instances") page_iterator = paginator.paginate( Filters=[ {"Name": f"tag:{target_tag_key}", "Values": [target_tag_value]}, {"Name": "instance-state-name", "Values": ["running"]}, ] ) for page in page_iterator: for reservation in page.get("Reservations", []): for instance in reservation.get("Instances", []): matched_instance_ids.append(instance["InstanceId"]) print(f"[INFO] Found {len(matched_instance_ids)} running instances: {matched_instance_ids}") # 辞書型で return した内容が、SSM 側で自動的に $.Payload.<Key> に格納される return { "MatchedCount": len(matched_instance_ids), "InstanceIds": matched_instance_ids, "DryRun": dry_run, "ExecutionStatus": "SUCCESS", } except ClientError as err: print(f"[ERROR] AWS API Error: {err}") raise
PowerShell の場合の違い : PowerShell では Handler の指定は不要です。 InputPayload は環境変数 $env:InputPayload に JSON 文字列として格納されるため、 $payload = $env:InputPayload | ConvertFrom-Json でパースして利用します。
Handler
$env:InputPayload
$payload = $env:InputPayload | ConvertFrom-Json
Lambda のレイヤーとは異なり、 aws:executeScript で requirements.txt の外部ライブラリ(または最新バージョンの boto3 )を使う場合は、 パッケージ群とスクリプトを同一階層(フラット)に展開した状態で ZIP 化 し、S3 に配置します。
requirements.txt
boto3
# 1. パッケージ格納用ディレクトリを作成し、その直下へ pip install -t する mkdir -p build_pkg cp src/runbook.py build_pkg/ pip install -r src/requirements.txt -t build_pkg/ --upgrade # 2. 親フォルダを含めず、build_pkg の中身だけをルートとして ZIP 化する(重要) (cd build_pkg && zip -rq ../modules.zip .) # 3. SSM Document の files セクションに記載する SHA-256 ハッシュを取得する shasum -a 256 modules.zip
ここで zip -rq modules.zip build_pkg のように親ディレクトリごと固めてしまうと、展開後のパスがずれて Handler: runbook.main が見つからずエラーになるため、必ず (cd build_pkg && zip -rq ../modules.zip .) でルート直下に配置してください。
zip -rq modules.zip build_pkg
Handler: runbook.main
(cd build_pkg && zip -rq ../modules.zip .)
実際に本番・検証環境へそのままデプロイできる IaC テンプレートを示します。
AWS::SSM::Document
CloudFormation で定義する際の最大の注意点は Name プロパティの扱いと Attachments / files の対応付け です。 Name を固定文字列にすると、更新時にリソース置換(Replacement)が必要になった際、同名ドキュメントの重複エラーでデプロイが失敗します。また、S3 上の ZIP を使う場合は Attachments とステップ内の Attachment 、および最下部の files.<Zip名>.checksums.sha256 の 3 箇所が完全一致している必要があります。
Name
Attachments
files
Attachment
files.<Zip名>.checksums.sha256
AWSTemplateFormatVersion: "2010-09-09" Description: SSM Automation Runbook with aws:executeScript (Python 3.12) Parameters: ArtifactBucketName: Type: String Description: S3 bucket name storing modules.zip ModuleZipSha256: Type: String Description: SHA-256 checksum of modules.zip (64 hex chars) AutomationAssumeRoleArn: Type: String Description: IAM Role ARN assumed by SSM Automation Resources: InstanceScanRunbook: Type: AWS::SSM::Document Properties: DocumentType: Automation DocumentFormat: YAML UpdateMethod: NewVersion Attachments: - Key: S3FileUrl Name: modules.zip Values: - !Sub "https://${ArtifactBucketName}.s3.${AWS::Region}.amazonaws.com/runbooks/modules.zip" Content: schemaVersion: "0.3" description: "Scan running EC2 instances by tag using Python 3.12" assumeRole: "{{ AutomationAssumeRole }}" parameters: AutomationAssumeRole: type: String default: !Ref AutomationAssumeRoleArn TagKey: type: String default: "Environment" TagValue: type: String default: "Staging" DryRun: type: String allowedValues: ["true", "false"] default: "true" mainSteps: - name: ScanInstancesStep action: "aws:executeScript" timeoutSeconds: 300 inputs: Runtime: "python3.12" Handler: "runbook.main" Attachment: "modules.zip" InputPayload: TagKey: "{{ TagKey }}" TagValue: "{{ TagValue }}" DryRun: "{{ DryRun }}" outputs: - Name: InstanceIds Selector: "$.Payload.InstanceIds" Type: StringList - Name: MatchedCount Selector: "$.Payload.MatchedCount" Type: Integer files: modules.zip: checksums: sha256: !Ref ModuleZipSha256
aws_ssm_document
Terraform を使うと、 data.archive_file と filesha256() 関数を組み合わせることで、最も厄介な 「ZIP の再生成・S3 アップロード・SHA-256 ハッシュ値の埋め込み」を完全自動化 できます。
data.archive_file
filesha256()
resource "terraform_data" "pip_install" { triggers_replace = [ filesha256("${path.module}/src/requirements.txt"), filesha256("${path.module}/src/runbook.py"), ] provisioner "local-exec" { command = <<-EOT rm -rf "${path.module}/build_pkg" mkdir -p "${path.module}/build_pkg" cp "${path.module}/src/runbook.py" "${path.module}/build_pkg/" pip install -r "${path.module}/src/requirements.txt" -t "${path.module}/build_pkg" --upgrade EOT } } data "archive_file" "modules_zip" { depends_on = [terraform_data.pip_install] type = "zip" source_dir = "${path.module}/build_pkg" output_path = "${path.module}/dist/modules.zip" } resource "aws_s3_object" "modules_zip" { bucket = var.artifact_bucket_name key = "runbooks/modules-${data.archive_file.modules_zip.output_sha256}.zip" source = data.archive_file.modules_zip.output_path etag = data.archive_file.modules_zip.output_md5 } resource "aws_ssm_document" "instance_scan_runbook" { name = "InstanceScanRunbook" document_type = "Automation" document_format = "JSON" attachments_source { key = "S3FileUrl" name = "modules.zip" values = ["https://${var.artifact_bucket_name}.s3.${data.aws_region.current.name}.amazonaws.com/${aws_s3_object.modules_zip.key}"] } content = jsonencode({ schemaVersion = "0.3" description = "Scan running EC2 instances by tag using Python 3.12" assumeRole = var.automation_assume_role_arn parameters = { TagKey = { type = "String", default = "Environment" } TagValue = { type = "String", default = "Staging" } DryRun = { type = "String", default = "true" } } mainSteps = [ { name = "ScanInstancesStep" action = "aws:executeScript" timeoutSeconds = 300 inputs = { Runtime = "python3.12" Handler = "runbook.main" Attachment = "modules.zip" InputPayload = { TagKey = "{{ TagKey }}" TagValue = "{{ TagValue }}" DryRun = "{{ DryRun }}" } } outputs = [ { Name = "InstanceIds" Selector = "$.Payload.InstanceIds" Type = "StringList" }, { Name = "MatchedCount" Selector = "$.Payload.MatchedCount" Type = "Integer" } ] } ] files = { "modules.zip" = { checksums = { sha256 = data.archive_file.modules_zip.output_sha256 } } } }) }
S3 のオブジェクトキー自体に modules-${output_sha256}.zip とハッシュ値を含めておくことで、S3 側のキャッシュやバージョン不整合によるデプロイ失敗を確実に防げます。
modules-${output_sha256}.zip
AssumeRole
SSM オートメーションをセキュリティ統制の観点で導入する最大のメリットは、 「オペレーター自身には EC2 や RDS の操作権限を一切与えず、特定のランブックを起動する権限だけを付与できる」 点にあります。
ssm:StartAutomationExecution
arn:aws:ssm:<region>:<account>:automation-definition/<RunbookName>:*
ssm:GetAutomationExecution
arn:aws:ssm:<region>:<account>:automation-execution/*
ssm:StopAutomationExecution
ssm:SendAutomationSignal
iam:PassRole
assumeRole
iam:PassedToService: ssm.amazonaws.com
iam:PassRole の特権昇格防止 : オペレーターに iam:PassRole を許可する際は、Resource 句を必ずそのランブック専用の IAM ロール ARN に限定し、かつ Condition で StringEquals: {"iam:PassedToService": "ssm.amazonaws.com"} を付けて他のサービス(EC2 や Lambda 等)へロールを流用されないようロックしてください。
Condition
StringEquals: {"iam:PassedToService": "ssm.amazonaws.com"}
最後に、僕が実際の運用ランブック開発で徹底している 5 つの設計ルールをまとめます。
sleep
aws:executeScript の中で time.sleep() を使ってリソースの状態変化を待つと、10 分(600 秒)の上限に達しやすいだけでなく、待機している秒数すべてに $0.00003 / 秒 の実行時間課金が発生します。 ポーリング待機が必要な場合は、必ずスクリプトを一度終了させ、次ステップで aws:waitForAwsResourceProperty または aws:sleep アクションを挟んでから後続の aws:executeScript を呼ぶ構成にしてください。
aws:sleep
concurrent.futures
512 MB メモリ・600 秒の枠内で数十〜数百リソースに対して API を順次呼び出すと、ネットワーク I/O 待ちでタイムアウトします。Python 標準の concurrent.futures.ThreadPoolExecutor(max_workers=10) を使い、スロットリング( ThrottlingException )に対する Exponential Backoff( botocore.config.Config(retries={"max_attempts": 10, "mode": "adaptive"}) )を設定した上で並列実行するのが効果的です。
concurrent.futures.ThreadPoolExecutor(max_workers=10)
ThrottlingException
botocore.config.Config(retries={"max_attempts": 10, "mode": "adaptive"})
print()
return
先述の通り、 aws:executeScript は AWS 管理下の内部 Lambda で動くため、自分のアカウントの CloudWatch Logs に自動でロググループが作られるわけではありません。ステップが正常終了した際にもマネジメントコンソール上で中間状態を確認できるよう、 print() による標準出力とあわせて、関数の return 辞書内にサマリー情報を入れておくとトラブルシューティングが格段に速くなります。
AWS-*
最初からすべてを Python で書く前に、 Systems Manager Automation ランブックリファレンス や既存の aws: executeAwsApi アクションだけで完結できないかを確認します。単純な 1〜2 回の API 呼び出しであれば、 aws:executeAwsApi を使う方がランタイムの EOL 更新コスト(Python バージョンアップ対応)をゼロに抑えられます。
aws: executeAwsApi
aws:executeAwsApi
aws:executeScript 単体ではプライベートサブネット内の RDS や内部エンドポイントへ到達できません。ランブックの承認フローを活かしつつ閉域リソースを操作したい場合は、ランブック内から aws:invokeLambdaFunction (VPC 接続済み Lambda)を呼ぶか、踏み台・管理用 EC2 に対して aws:runCommand を実行するハイブリッド構成を採るのが現実的です。
SSM オートメーションの aws:executeScript は、裏側で動く Falcon サンドボックス(メモリ 512 MB・最大 600 秒・VPC 非接続)の特性と、 events / $.Payload のデータ受け渡し規約さえ最初に押さえておけば、わざわざ個別の Lambda 関数や UI を作ることなく、堅牢で最小権限な運用ツールを素早く構築できます。
一方で、スクリプトが複雑化し外部ライブラリが肥大化してくると、S3 上の modules.zip 管理や SHA-256 ハッシュ更新の手間が通常の Lambda コンテナイメージ管理と変わらなくなってくる側面もあります。僕自身は現在、「300 行以内で完結する AWS パブリック API の組み合わせ処理は aws:executeScript (インラインまたは軽量 ZIP)」「それ以上の重い処理や VPC 内通信を伴うものは Step Functions + Lambda」という境界線で運用していますが、今後のランタイム上限緩和も含めて引き続き現場で見極めていきたいところです。
本番さながらのAI電話で初通話もデート誘いも余裕に。通話中の対話をリアルタイム解析し、最適な切り返しや好感度アップの助言を即座にサジェスト。24時間いつでも通話練習が可能です(無料体験あり・1レッスン 約150円〜)。
レシートを撮影するだけでGemini AIが品目・金額を高精度OCR解析。LINEログインで友人との面倒な立替・割り勘計算を美しく完結します。
占い師・執事・バーテンダーなどのAIキャラクターが進行役となり、お題やゲームを出題。集まる時間を最高にエキサイティングにするiOSアプリ。
日本株・グローバル企業の適時開示・決算速報をAIクオンツ解析。市場モメンタムや注目銘柄をリアルタイムに可視化するデータポータルです。
人工甘味料や添加物のNG成分除外フィルターと、有効成分あたりの実質単価を徹底比較・可視化するヘルスケア比較データベースです。
本記事で解説した 4大AIエージェント(Antigravity, Kiro, Claude Code, Codex)完全対応の AGENTS.md テンプレート、hooks.json、Gitガードスクリプト一式をGumroadにて配布準備中です。