LoginSignup
3
3

More than 1 year has passed since last update.

[Python] DynamoDBをLambdaから使ってみる

Last updated at Posted at 2022-05-10

はじめに

Boto3の公式ドキュメントを参考にしてLambdaからPythonを使ってDynamoDBを読み書きしてみます。

DynamoDBでテーブルの作成

テーブル名とパーティションキーだけ指定して作成します。

image.png

Lambdaで権限設定

実行ロールをクリックして編集します。

image.png

今回は割当てているロールにAmazonDynamoDBFullAccessのポリシーを追加します。

image.png

Lambdaから項目(レコード)追加

LambdaにBoto3ライブラリを使った以下のコードを記述します。

import boto3

dynamodb = boto3.resource('dynamodb')

def lambda_handler(event, context):

    table = dynamodb.Table('dns-a')

    table.put_item(
    	Item={
    		"fqdn": "dns.google.com",
    		"ipaddresses": ["8.8.8.8", "8.8.4.4"],
    		"timestamp": "2022/05/10 09:00:00"
    	}
    )

    return

保存・Deploy後にテスト実行します。

image.png

うまく動作するとテーブルにアイテムが追加されます。

image.png

なお同一パーティションキー(今回はfqdn)が存在する場合は、エラーとならず更新処理が行われます。

以上。

3
3
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
3
3