LoginSignup
0
0

More than 3 years have passed since last update.

CodeBuildを使ってDocumentDBを操作する

Last updated at Posted at 2021-03-12

概要

CodeBuildを使ってDocumentDBを操作(抽出、挿入、削除)する

方法の概略
1. DocumentDBと同じVPC内でCodeBuildを作成
2. buildspec.yml にDocumentDBを操作するためのコマンドを書く
3. CodeBuildを実行する

事前準備

  • 「public/private subnet」があるVPCとDocumentDBを用意

    • NAT Gatewayを作成
    • private subnetにNAT Gatewayへのルートを設定
    • private subnet内にDcoumentDBを作成 image.png
  • CodeBuildが読み取るコードの場所を用意

    • 一般的にはCodeCommitがよく利用される

やってみる

1. DocumentDBと同じVPC内でCodeBuildを作成

VPCにCodeBuildプロジェクトを作成する。
作成する時には以下のことに気をつける。

2. buildspec.yml にDocumentDBを操作するためのコマンドを書く

buildspec.yml
version: 0.2

phases:
  install:
    commands:
      # mongo-shellをインストールする
      - echo -e "[mongodb-org-4.0] \nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/amazon/2013.03/mongodb-org/4.0/x86_64/\ngpgcheck=1 \nenabled=1 \ngpgkey=https://www.mongodb.org/static/pgp/server-4.0.asc" | tee /etc/yum.repos.d/mongodb-org-4.0.repo 
      - yum install -y mongodb-org-shell
  build:
    commands:
      # SSL接続のために公開鍵をダウンロードしておく
      - wget https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem
      # 対話シェルが使えないので、script.jsを読み込ませてる
      # TODO: ${}にはそれぞれ適当な値を入れること
      - mongo --ssl --host ${HOST} ${DB_NAME} --sslCAFile rds-combined-ca-bundle.pem --username ${USERNAME} --password ${PASSWORD} < script.js

script.jsのコード例(詳細説明は他の記事で)

script.js
/* --------------------------------- */
/* コレクション一覧 */
/* --------------------------------- */
db.getCollectionNames();

/* --------------------------------- */
/* ドキュメント内容 */
/* --------------------------------- */
// collectionを参照。存在しない場合は勝手に作成される。
collection = db.getCollection(<collection_name>);
collection.find();

/* --------------------------------- */
/* データを挿入 */
/* --------------------------------- */
collection = db.getCollection(<collection_name>);

doc_1 = {
    name: "bar",
    favarite: "foo"
};
collection.insert(doc_1);

/* --------------------------------- */
/* データを削除 */
/* --------------------------------- */
collection = db.getCollection(<collection_name>);

collection.remove({name: "bar"});

一応、CodeCommitのフォルダ構成

./
 - buildspec.yml
 - script.js

3. CodeBuildを実行

buildspec.ymlの内容が実行される
そして、DocumentDBに対してscript.jsの操作が行われる

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0