Johnman.md

プログラミングのことや個人的なことを書きます。たぶん。

embulkを使ってS3からGCSにファイルを送る

はじめに

お久しぶりです。
最近AWS S3からGCP Google Cloud Storageにファイルを送信しなければいけないことがあったので、その備忘録的に書こうと思います。

検索するとgsutilコマンドとかStorage Transfer Serviceが出てきますが、いろいろ理由があってこれらは使えなかったので、今回はembulkを使いました。

(今回はあくまでembulkを使ってS3からGCSにファイルを送ることに焦点を当てたので、embulkそのものの設定などについては書きません)

embulk

embulkはFluentdなどを開発した古橋さんが開発したオープンソースのデータ転送ツールです。Fluentdのバッチ版とか言われたりしますね。

github.com

Embulk is a parallel bulk data loader that helps data transfer between various storages, databases, NoSQL and cloud services.

Embulk supports plugins to add functions. You can share the plugins to keep your custom scripts readable, maintainable, and reusable.

とあるように、プラグインを導入することで様々なストレージやデータベースの間でデータをやり取りできます。

今回使ったプラグイン

今回はS3からGCSへファイルを送りたいので、以下のプラグインを使いました。

  • embulk-input-s3
  • embulk-output-gcs

github.com

github.com

設定ファイル

実際の設定ファイルは以下です。

S3上にあるgzip圧縮されたCSVファイルをGCSへ送信します。 embulk-output-gcsプラグインの認証には3種類の方法がありますが、今回はjson_keyを使いました。

in:
  type: s3
  bucket: # S3バケット名
  region: ap-northeast-1
  path_prefix:  s3/example/20200222/
  decoders:
    - {type: gzip}
  auth_method: default
  parser:
    type: csv
    newline: LF
    delimiter: ','
    quote: '"'
    escape: '"'
    skip_header_lines: 0
    columns:
      - {name: "id", type: "long"}
      - {name: "name", type: "string"}
      - {name: "gender", type: "string"}
      - {name: "created_at": type: "timestamp", format: "%Y-%m-%d %H:%M:%S"}
out:
  type: gcs
  bucket: # GCSバケット名
  path_prefix: gcs/example/20200222/
  sequence_format: "user_%02d"
  file_ext: .gz
  auth_method: json_key
  json_keyfile:
    content: |
      {
        "type": "service_account",
        "project_id": "XXXXXXXXXX",
        "private_key_id": "プライベートキーID",
        "private_key": "プライベートキー",
        "client_email": "client@XXXXXXXXXX.iam.gserviceaccount.com",
        "client_id": "123456789",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/client%40XXXXXXXXXX.iam.gserviceaccount.com"
      }
  encoders:
    - {type: gzip}
  formatter:
    type: csv
    newline: LF
    delimiter: ','
    quote: '"'
    escape: '"'
    header_line: false
    column_options:
      created_at: {format: "%Y-%m-%d %H:%M:%S"}

まとめ

今回はembulkを使ってS3からGCSへファイルを送信する話を書きました。

大量のデータを一括で送信したい時にはembulk非常に便利なのでおすすめです。