😺

S3トリガー×AWS Lambda×Glue Python Shellの起動パターン整理

に公開

はじめに

AWS Community Builderのぺんぎん(@jitepengin)です。

これまでの記事で、Glue Python Shellを使った軽量ETLを紹介しました。
今回はS3へのファイル配置をトリガーにGlue Python Shellを起動する構成2パターンと、Lambdaを介してGlueを呼ぶ意図について整理したいと思います。

Lambdaを介してGlue Python Shellを呼ぶ意図

S3イベントから直接ETL処理をLambdaだけで完結させることも可能ですが、処理時間やメモリの制約があります。
そのためLambdaをトリガーとし、軽量な事前処理・他サービス連携に専念し、実際のETL処理はGlue Python Shellで実行することで、柔軟なサービス連携と長時間実行を実現します。

LambdaとGlue Python Shellの使い分けについては下記の記事に記載しているので、参考にどうぞ!
https://zenn.dev/penginpenguin/articles/fe2c3999a05013


起動パターン

今回紹介する起動パターンは以下の2つです。
それぞれ、S3へのファイル配置をトリガーに、Glue Python Shellを起動します。

  1. Lambda + start_job_runを使う構成(Job直接実行)
  2. Lambda + start_workflow_runを使う構成(Workflow実行)

これ以外にも例えばS3 → EventBridge → Step Functions → Glue Python Shellなど様々なパターンがあります。

今回は、比較的簡単に構成可能な2パターンに絞って説明したいと思います。

Lambda + start_job_runを使う構成(Job直接実行)

この構成では、S3のファイル配置イベントをLambdaで受け取り、Lambdaからstart_job_runを使ってGlue Python Shellジョブを直接起動します。
前回の記事はこちらの構成となります。

この構成は以下のような特徴があります。

  • Lambdaを活用することで多種多様なサービスと連携できる(柔軟性が高い)
  • エラー時の再試行を検討する必要がある。(Python Shell自体にはジョブ実行キューとリトライ回数が設定できます)
    トリガー部分の再試行はLambda側の設計次第。
  • フロー制御が必要な場合は構成が膨らみやすい。
    例えば、EventBridge → Step Functions → Lambdaのような構成を検討する必要がある。
  • Lambdaで完結してもいいのでは?という疑問がある。
    柔軟性のLambdaか長時間実行可能なGlue Python Shellかの判断が必要となります。

Lambdaサンプルコード

start_job_runで起動したいJob名とパラメータを設定します。
今回はS3のファイルパスを設定しています。
こちらを元にGlue Python Shellでファイルを読み込んで処理を実行します。

import boto3

def lambda_handler(event, context):
    glue = boto3.client("glue")
    
    s3_bucket = event['Records'][0]['s3']['bucket']['name']
    s3_object_key = event['Records'][0]['s3']['object']['key']
            
    s3_input_path = f"s3://{s3_bucket}/{s3_object_key}"
    

    response = glue.start_job_run(
        JobName="ターゲットジョブの名前(置き換えてください)",
        Arguments={
            "--s3_input": s3_input_path
        }
    )

    print(f"Glue Job started: {response['JobRunId']}")
    return response

設定方法

  1. Glue Python Shellを作成する。
import boto3
import sys
import os
from awsglue.utils import getResolvedOptions


def get_job_parameters():
    try:
        required_args = ['s3_input']
        args = getResolvedOptions(sys.argv, required_args)

        s3_file_path = args['s3_input']
        print(f"s3_input: {s3_file_path}")

        return s3_file_path

    except Exception as e:
        print(f"parameters error: {e}")
        raise


def _to_pyarrow_table(result):
    """
    Compatibility helper to extract a pyarrow.Table from a chDB query_result.
    """
    import chdb

    if hasattr(chdb, "to_arrowTable"):
        return chdb.to_arrowTable(result)

    if hasattr(result, "to_pyarrow"):
        return result.to_pyarrow()
    if hasattr(result, "to_arrow"):
        return result.to_arrow()

    raise RuntimeError(
        "Cannot convert chdb query_result to pyarrow.Table. "
        f"Available attributes: {sorted(dir(result))[:200]}"
    )


def normalize_arrow_for_iceberg(table):
    """
    Normalize Arrow schema for Iceberg compatibility.
    - timestamptz -> timestamp
    """
    import pyarrow as pa

    new_fields = []
    new_columns = []

    for field, column in zip(table.schema, table.columns):
        # timestamp with timezone -> timestamp
        if pa.types.is_timestamp(field.type) and field.type.tz is not None:
            new_type = pa.timestamp(field.type.unit)
            new_fields.append(pa.field(field.name, new_type, field.nullable))
            new_columns.append(column.cast(new_type))
        else:
            new_fields.append(field)
            new_columns.append(column)

    new_schema = pa.schema(new_fields)
    return pa.Table.from_arrays(new_columns, schema=new_schema)


def read_parquet_with_chdb(s3_input):
    """
    Read Parquet file from S3 using chDB.
    """
    import chdb

    if s3_input.startswith("s3://"):
        bucket, key = s3_input.replace("s3://", "").split("/", 1)
        s3_url = f"https://{bucket}.s3.ap-northeast-1.amazonaws.com/{key}"
    else:
        s3_url = s3_input

    print(f"Reading data from S3: {s3_url}")

    query = f"""
        SELECT *
        FROM s3('{s3_url}', 'Parquet')
        WHERE VendorID = 1
    """

    result = chdb.query(query, "Arrow")
    arrow_table = _to_pyarrow_table(result)

    print("Original schema:")
    print(arrow_table.schema)

    # Normalize schema for Iceberg compatibility
    arrow_table = normalize_arrow_for_iceberg(arrow_table)

    print("Normalized schema:")
    print(arrow_table.schema)
    print(f"Rows: {arrow_table.num_rows:,}")

    return arrow_table


def write_iceberg_table(arrow_table):
    """
    Write Arrow table to Iceberg table using PyIceberg.
    """
    try:
        print("Writing started...")

        from pyiceberg.catalog import load_catalog

        catalog_config = {
            "type": "glue",
            "warehouse": "s3://your-bucket/your-warehouse/",  # Adjust to your environment.
            "region": "ap-northeast-1",
        }

        catalog = load_catalog("glue_catalog", **catalog_config)
        table_identifier = "icebergdb.yellow_tripdata"

        table = catalog.load_table(table_identifier)

        print(f"Target data to write: {arrow_table.num_rows:,} rows")
        table.append(arrow_table)

        return True

    except Exception as e:
        print(f"Writing error: {e}")
        import traceback
        traceback.print_exc()
        return False


def main():
    try:
        import chdb
        import pyiceberg

        # Read input parameter
        s3_input = get_job_parameters()

        # Read data with chDB
        arrow_tbl = read_parquet_with_chdb(s3_input)
        print(f"Data read success: {arrow_tbl.num_rows:,} rows")

        # Write to Iceberg table
        if write_iceberg_table(arrow_tbl):
            print("\nWriting fully successful!")
        else:
            print("Writing failed")

    except Exception as e:
        print(f"Main error: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()

  1. Lambdaを作成する。

    前述したLambdaサンプルコードを設定します。

  1. S3のトリガーを設定する。

    S3のPUTイベントを設定

実行結果

Lambda + start_workflow_runを使う構成(Workflow実行)


この構成では、S3のファイル配置イベントをLambdaで受け取り、Lambdaからstart_workflow_runを使ってGlue Workflowを起動します。
そして、Glue Workflow内からGlue Python Shellジョブを実行する構成となります。

この構成は以下のような特徴があります。

  • Lambdaの柔軟性とGlue Workflowのフロー管理を両立できる。
    Lambdaを活用することで多種多様なサービスと連携できる(柔軟性が高い)
  • エラー時の再試行を検討する必要がある。
    再試行やエラー制御については、Lambda側とWorkflow側の責務分担を意識して設計する必要がある。
  • Glue Workflow内で処理をフロー化できる。(前処理・後処理を後から追加しやすい。)

Lambdaサンプルコード

start_workflow_runで起動したいGlueのWorkflow名とパラメータを設定します。
start_job_runと同じく、S3のファイルパスを設定しています。
こちらを元にWorkflowが起動され、Workflowから起動されたGlue Python Shellでファイルを読み込んで処理を実行します。

import boto3

def lambda_handler(event, context):
    glue = boto3.client("glue")
    
    s3_bucket = event['Records'][0]['s3']['bucket']['name']
    s3_object_key = event['Records'][0]['s3']['object']['key']
            
    s3_input_path = f"s3://{s3_bucket}/{s3_object_key}"
    

    response = glue.start_workflow_run(
        Name = 'ターゲットワークフローの名前(置き換えてください)',
        RunProperties = { '--s3_input': s3_input_path })
    
    print(f"Glue Job started: {response['RunId']}")
    return response

設定方法

  1. Glue Python Shellを作成する。

1つ目のJob

import boto3
import sys
import os
from awsglue.utils import getResolvedOptions


def get_job_parameters():
    args = getResolvedOptions(sys.argv, ['WORKFLOW_NAME', 'WORKFLOW_RUN_ID'])

    glue = boto3.client('glue')
    resp = glue.get_workflow_run_properties(
        Name=args['WORKFLOW_NAME'],
        RunId=args['WORKFLOW_RUN_ID']
    )

    s3_input = resp['RunProperties'].get('s3_input')
    if not s3_input:
        raise ValueError("s3_input Not Found")
    
    print(f"s3_input: {s3_input}")
    return s3_input

def _to_pyarrow_table(result):
    """
    Compatibility helper to extract a pyarrow.Table from a chDB query_result.
    """
    import chdb

    if hasattr(chdb, "to_arrowTable"):
        return chdb.to_arrowTable(result)

    if hasattr(result, "to_pyarrow"):
        return result.to_pyarrow()
    if hasattr(result, "to_arrow"):
        return result.to_arrow()

    raise RuntimeError(
        "Cannot convert chdb query_result to pyarrow.Table. "
        f"Available attributes: {sorted(dir(result))[:200]}"
    )


def normalize_arrow_for_iceberg(table):
    """
    Normalize Arrow schema for Iceberg compatibility.
    - timestamptz -> timestamp
    - binary -> string
    """
    import pyarrow as pa

    new_fields = []
    new_columns = []

    for field, column in zip(table.schema, table.columns):
        # timestamp with timezone -> timestamp
        if pa.types.is_timestamp(field.type) and field.type.tz is not None:
            new_type = pa.timestamp(field.type.unit)
            new_fields.append(pa.field(field.name, new_type, field.nullable))
            new_columns.append(column.cast(new_type))
        else:
            new_fields.append(field)
            new_columns.append(column)

    new_schema = pa.schema(new_fields)
    return pa.Table.from_arrays(new_columns, schema=new_schema)


def read_parquet_with_chdb(s3_input):
    """
    Read Parquet file from S3 using chDB.
    """
    import chdb

    if s3_input.startswith("s3://"):
        bucket, key = s3_input.replace("s3://", "").split("/", 1)
        s3_url = f"https://{bucket}.s3.ap-northeast-1.amazonaws.com/{key}"
    else:
        s3_url = s3_input

    print(f"Reading data from S3: {s3_url}")

    query = f"""
        SELECT *
        FROM s3('{s3_url}', 'Parquet')
        WHERE VendorID = 1
    """

    result = chdb.query(query, "Arrow")
    arrow_table = _to_pyarrow_table(result)

    print("Original schema:")
    print(arrow_table.schema)

    # Normalize schema for Iceberg compatibility
    arrow_table = normalize_arrow_for_iceberg(arrow_table)

    print("Normalized schema:")
    print(arrow_table.schema)
    print(f"Rows: {arrow_table.num_rows:,}")

    return arrow_table


def write_iceberg_table(arrow_table):
    """
    Write Arrow table to Iceberg table using PyIceberg.
    """
    try:
        print("Writing started...")

        from pyiceberg.catalog import load_catalog

        catalog_config = {
            "type": "glue",
            "warehouse": "s3://your-bucket/your-warehouse/",  # Adjust to your environment.
            "region": "ap-northeast-1",
        }

        catalog = load_catalog("glue_catalog", **catalog_config)
        table_identifier = "icebergdb.yellow_tripdata"

        table = catalog.load_table(table_identifier)

        print(f"Target data to write: {arrow_table.num_rows:,} rows")
        table.append(arrow_table)

        return True

    except Exception as e:
        print(f"Writing error: {e}")
        import traceback
        traceback.print_exc()
        return False


def main():
    try:
        import chdb
        import pyiceberg

        # Read input parameter
        s3_input = get_job_parameters()

        # Read data with chDB
        arrow_tbl = read_parquet_with_chdb(s3_input)
        print(f"Data read success: {arrow_tbl.num_rows:,} rows")

        # Write to Iceberg table
        if write_iceberg_table(arrow_tbl):
            print("\nWriting fully successful!")
        else:
            print("Writing failed")

    except Exception as e:
        print(f"Main error: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()

2つ目のJob

import boto3
import sys
import os
from awsglue.utils import getResolvedOptions


def get_job_parameters():
    args = getResolvedOptions(sys.argv, ['WORKFLOW_NAME', 'WORKFLOW_RUN_ID'])

    glue = boto3.client('glue')
    resp = glue.get_workflow_run_properties(
        Name=args['WORKFLOW_NAME'],
        RunId=args['WORKFLOW_RUN_ID']
    )

    s3_input = resp['RunProperties'].get('s3_input')
    if not s3_input:
        raise ValueError("s3_input Not Found")
    
    print(f"s3_input: {s3_input}")
    return s3_input

def _to_pyarrow_table(result):
    """
    Compatibility helper to extract a pyarrow.Table from a chDB query_result.
    """
    import chdb

    if hasattr(chdb, "to_arrowTable"):
        return chdb.to_arrowTable(result)

    if hasattr(result, "to_pyarrow"):
        return result.to_pyarrow()
    if hasattr(result, "to_arrow"):
        return result.to_arrow()

    raise RuntimeError(
        "Cannot convert chdb query_result to pyarrow.Table. "
        f"Available attributes: {sorted(dir(result))[:200]}"
    )


def normalize_arrow_for_iceberg(table):
    """
    Normalize Arrow schema for Iceberg compatibility.
    - timestamptz -> timestamp
    - binary -> string
    """
    import pyarrow as pa

    new_fields = []
    new_columns = []

    for field, column in zip(table.schema, table.columns):
        # timestamp with timezone -> timestamp
        if pa.types.is_timestamp(field.type) and field.type.tz is not None:
            new_type = pa.timestamp(field.type.unit)
            new_fields.append(pa.field(field.name, new_type, field.nullable))
            new_columns.append(column.cast(new_type))
        else:
            new_fields.append(field)
            new_columns.append(column)

    new_schema = pa.schema(new_fields)
    return pa.Table.from_arrays(new_columns, schema=new_schema)


def read_parquet_with_chdb(s3_input):
    """
    Read Parquet file from S3 using chDB.
    """
    import chdb

    if s3_input.startswith("s3://"):
        bucket, key = s3_input.replace("s3://", "").split("/", 1)
        s3_url = f"https://{bucket}.s3.ap-northeast-1.amazonaws.com/{key}"
    else:
        s3_url = s3_input

    print(f"Reading data from S3: {s3_url}")

    query = f"""
        SELECT *
        FROM s3('{s3_url}', 'Parquet')
        WHERE VendorID = 2
    """

    result = chdb.query(query, "Arrow")
    arrow_table = _to_pyarrow_table(result)

    print("Original schema:")
    print(arrow_table.schema)

    # Normalize schema for Iceberg compatibility
    arrow_table = normalize_arrow_for_iceberg(arrow_table)

    print("Normalized schema:")
    print(arrow_table.schema)
    print(f"Rows: {arrow_table.num_rows:,}")

    return arrow_table


def write_iceberg_table(arrow_table):
    """
    Write Arrow table to Iceberg table using PyIceberg.
    """
    try:
        print("Writing started...")

        from pyiceberg.catalog import load_catalog

        catalog_config = {
            "type": "glue",
            "warehouse": "s3://your-bucket/your-warehouse/",  # Adjust to your environment.
            "region": "ap-northeast-1",
        }

        catalog = load_catalog("glue_catalog", **catalog_config)
        table_identifier = "icebergdb.yellow_tripdata"

        table = catalog.load_table(table_identifier)

        print(f"Target data to write: {arrow_table.num_rows:,} rows")
        table.append(arrow_table)

        return True

    except Exception as e:
        print(f"Writing error: {e}")
        import traceback
        traceback.print_exc()
        return False


def main():
    try:
        import chdb
        import pyiceberg

        # Read input parameter
        s3_input = get_job_parameters()

        # Read data with chDB
        arrow_tbl = read_parquet_with_chdb(s3_input)
        print(f"Data read success: {arrow_tbl.num_rows:,} rows")

        # Write to Iceberg table
        if write_iceberg_table(arrow_tbl):
            print("\nWriting fully successful!")
        else:
            print("Writing failed")

    except Exception as e:
        print(f"Main error: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()

  1. Glue Workflowを作成する。

    今回はフロー内で2つのJobを起動します。

  1. Lambdaを作成する。

    前述したLambdaサンプルコードを設定します。

  1. S3のトリガーを設定する。

    S3のPUTイベントを設定

実行結果


Workflow実行とJob直接実行の比較

Workflow実行のメリット

  • 複数ジョブの依存関係管理が可能
    ジョブ間の順序制御、条件分岐、並列制御が可能となります。
  • 統一されたパラメータ管理
    Run Properties で全ジョブに共通パラメータを渡すことが可能となります。
  • 統合監視・管理
    全体の実行状況を一元管理、エラー時の全体停止・再開、実行履歴の一元化が可能となります。
  • スケジューリング・EventBridge連携
    ワークフロー全体のスケジュール実行やイベント駆動が可能となります。

Workflow実行のデメリット

  • 設定の複雑さ(トリガー設定や依存関係定義が必要)。
  • オーバーヘッド(単一ジョブでも管理コストが発生、実行開始まで時間が長い)。
  • デバッグの難しさ(個別ジョブのテストが困難)。

Job直接実行のメリット

  • シンプルさ:設定が簡単、即座に実行開始できます。
  • 柔軟性:個別にパラメータ設定可能、独立スケジューリング、デバッグが容易となります。
  • コスト効率:必要な時だけ実行、管理オーバーヘッドなし。

Job直接実行のデメリット

  • 依存関係管理が困難となります。(手動で順序制御が必要、エラー処理複雑)
  • パラメータ管理の分散につながります。(各ジョブで個別設定、整合性維持が困難)
  • 監視の分散となる可能性があります。(全体像把握が難しい)

Workflow実行とJob直接実行の使い分けを考える

Workflowを使うべき場合

  • 複数ジョブの連携が必要となる場合。(例:データ取得 → 変換 → 検証 → 出力)
  • 複数ジョブで共通パラメータを使用する場合。
  • 全体の実行状況を統一管理したい。
  • 定期的なバッチ処理。

構成例

S3 → Lambda → Glue Workflow
  ├── Job1: データ取得・前処理
  ├── Job2: データ変換
  └── Job3: データ検証・出力

Job直接実行を使うべき場合

  • 単一ジョブで処理が完結する場合。
  • リアルタイム性が重要な場合。
  • 個別の柔軟な制御が必要となる場合。
  • プロトタイプ・テスト段階。

構成例

S3 → Lambda → Glue Job (単一)

まとめ

今回は、S3のファイルトリガーを起点としたGlue Python Shellの起動方法について2パターンを紹介しました。
S3トリガーでGlue Python Shellを起動する際、Lambdaは単体処理に使わず、Glueを呼ぶ補助として活用すると設計がシンプルになります。

  • 単体処理なら Lambda + Job
  • 複数ジョブやフロー制御が必要なら Lambda + Workflow

Glue Python Shellは、Glue(Spark)やEMR、Lambdaと比べると中途半端な部分があり、使いどころが分かりづらいサービスです。
しかし、比較的低コスト、長時間実行可能、Sparkを前提としないという特性がハマる要件であれば、割と便利なサービスだと思います。

前回の記事で紹介したように、chDBやDuckDBなどと組み合わせることで処理効率を高めることもできますし、トレンドであるIceberg連携もPyIcebergを使えば比較的シンプルに実現可能です。
今回はS3のファイルトリガーの文脈で解説しましたが、S3のファイルトリガーにこだわらなければ、長時間実行可能なJob実行環境としても使用可能です。(こちらの方が一般的だと思います。)

本記事が、データ基盤構築やETL設計を検討する際の一助になれば幸いです。

Discussion