LoginSignup
1
0

【Lambda】Parameter Storeの値を取得する処理を共通化する

Last updated at Posted at 2024-05-30

まとめ

処理をmjsファイルに記述してレイヤー登録する


例として、supabaseを使用するためのパラメータを登録・取得してみます
lambdaからsupabaseをいじいじする記事はこちら

1. ファイルの用意

touch getParameters.mjs

2. 処理をmjsファイルに記述

以下のように記述してみます

getParameters.mjs
import { SSMClient, GetParameterCommand } from "@aws-sdk/client-ssm";

const client = new SSMClient({ region: "ap-northeast-1" });

export async function getParameter(name) {
  const params = {
    Name: name,
    WithDecryption: true,
  };
  const command = new GetParameterCommand(params);
  const response = await client.send(command);
  return response.Parameter.Value;
}

3. zip化してレイヤーに登録

zip -r hogehoge.zip getParameters.mjs

レイヤー登録のわかりやすい手順はこちら

4. 実行ロールに権限を渡す

ssm:GetParameterが付与されていればOKです

新しくgetHogeHogeParamsというポリシーを作成して、lambdaに紐づいているロールに許可ポリシーとして登録してみましょう

// getHogeHogeParams.jsonの中身
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ssm:DescribeParameters"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "ssm:GetParameter"
            ],
            "Resource": [
                "arn:aws:ssm:ap-northeast-1:000000000000:parameter/SUPABASE_KEY",
                "arn:aws:ssm:ap-northeast-1:000000000000:parameter/SUPABASE_URL"
            ]
        }
    ]
}

5. レイヤーを使用する

/opt/作成したファイル名.mjsをfromすること

import { createClient } from '@supabase/supabase-js';
import { getParameter } from '/opt/getParams.mjs';


export const handler = async (event) => {
  const supaUrl = await getParameter('SUPABASE_URL');
  const supaKey = await getParameter('SUPABASE_KEY');

        
  const supabase = createClient(supaUrl, supaKey);

  ...
1
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
1
0