Lambda 更新のスクリプトについて適当にまとめておく

2024年1月26日

階層

階層は以下の通りで sh deploy.sh でデプロイする。

.
├── requirements.txt
├── lambda_function.py
└── deploy.sh

ファイル

requirements.txt

Lambda から slack 通知を送れるようにライブラリを記載しておく。

slackweb==1.0.5

lambda_function.py

Lambda メインの処理でここでは slack の通知を送るだけ。

import json
import slackweb

def execute(execute_from):

    start_message = f"""
    Lamda の実行を開始しました。
    実行環境: {execute_from}
    """
    end_message = f"""
    Lamda の実行が完了しました。
    実行環境: {execute_from}
    """

    slack = slackweb.Slack(url="https://hogehoge")
    slack.notify(text=start_message)

    # ここで何かの処理。。。

    slack.notify(text=end_message)

    return {
        'statusCode': 200,
        'body': json.dumps(f'done')
    }

def lambda_handler(event, context):
    execute("lambda")

if __name__ == '__main__':
    execute("local")

deploy.sh

デプロイスクリプトは以下の通り。
最上位の階層にライブラリをインストールすると、散らかりGITでの管理ができないので tmp 配下にインストールして、必要なファイルも tmp 配下にコピーしています。

#!/bin/sh

FUNCTION_NAME="test"
ENV_VARIABLES="{MESSAGE1=hogehoge,MESSAGE2=fugafuga}"

config_updated=false
code_updated=false

mkdir ./tmp
cp -ip ./* ./tmp/
cd ./tmp

pip install -r requirements.txt -t ./
zip -r upload.zip ./

while true; do
    aws lambda update-function-configuration --function-name $FUNCTION_NAME --environment Variables="$ENV_VARIABLES"
    if [ $? -eq 0 ]; then
        echo "Configuration updated successfully"
        config_updated=true
        break
    else
        echo "Error occurred. Retrying in 5 seconds..."
        sleep 5
    fi
done

while true; do
    aws lambda update-function-code --function-name $FUNCTION_NAME --zip-file fileb://upload.zip
    if [ $? -eq 0 ]; then
        echo "Code updated successfully"
        code_updated=true
        break
    else
        echo "Error occurred. Retrying in 5 seconds..."
        sleep 5
    fi
done

while true; do
    if $config_updated && $code_updated; then
        cd ../
        rm -Rf ./tmp
        break
    else
        echo "Operating..."
    fi
done
YouTube

2024年1月26日