AWSメモ >

AWS Lambdaで環境変数を使用する

Lambda関数の作成

index.py

# coding: utf-8
import os


def handler(event, context):
    env1 = os.environ.get('SampleEnv1') if os.environ.get('SampleEnv1') else 'blank!'
    env2 = os.environ.get('SampleEnv2') if os.environ.get('SampleEnv2') else 'blank!'
    return f'SampleEnv1 is {env1}. SampleEnv2 is {env2}.'

template.yml の作成

ここではAWS::Serverless変換 を使用して作成する事とする。またデプロイは package & deploy の手順で行う為、codeUri は指定しない。
※ create-stack で一発作成する場合は s3への事前アップロード 及び template での codeUri の指定が必要。

template.yml

AWSTemplateFormatVersion : "2010-09-09"
Transform: "AWS::Serverless-2016-10-31"
Description: "Sample Lambda Environments."
Parameters:
  SampleEnv1:
    Type: "String"
    Default: ""
  SampleEnv2:
    Type: "String"
    Default: ""
  FuncName:
    Type: "String"
    Default: "SampleLambdaEnv"

Resources:
  SampleLambdaEnv:
    Type: "AWS::Serverless::Function"
    Properties:
      FunctionName: !Ref FuncName
      Description: "Get Environment Lambda Sample"
      Environment:
        Variables:
          SampleEnv1: !Ref SampleEnv1
          SampleEnv2: !Ref SampleEnv2
      Handler: index.handler
      MemorySize: 128 
      Role: !GetAtt SampleLambdaEnvRole.Arn
      Runtime: "python3.6"
      Timeout: 30
  SampleLambdaEnvRole:
    Type: "AWS::IAM::Role"
    Properties: 
      RoleName: SampleLambdaEnvRole
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: "Allow"
            Principal:
              Service: "lambda.amazonaws.com"
            Action: "sts:AssumeRole"
      Policies:
        - PolicyName: "LambdaEnvPolicy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: "Allow"
                Action:
                  - "logs:*"
                Resource: "*" 

デプロイ 及び Lambda実行用のシェル作成

parameter-overrides を使用して環境変数を上書きしてデプロイできるようなシェルを作成しておく。

make.sh

#!/bin/bash

# AWSアカウントID
ACCOUNT_ID=`aws sts get-caller-identity | grep Account | awk '{print $2}' | sed -e "s/[^0-9]//g"`

# バケット名(世界で唯一である必要がある為、末尾にアカウントID等を付与しておく)
S3_BUCKET=my-cloudformation-templates-${ACCOUNT_ID}

# スタック名
STACK_NAME=SampleEnvFunctionStack

# Lambda関数名
FUNC_NAME=SampleLambdaEnv


# デプロイ
deploy(){

    # アップロード用のS3バケットの作成
    bucket_count=`aws s3api list-buckets | grep my-cloudformation-templates-675008719274 | wc -l | awk '{print $1}'`
    if [ "$bucket_count" == "0" ]; then
        aws s3api create-bucket --create-bucket-configuration '{"LocationConstraint": "ap-northeast-1"}' --bucket $S3_BUCKET
    fi  

    # 検証&パッケージング&デプロイ
    aws cloudformation validate-template --template-body file://template.yml \
      && aws cloudformation package --template-file template.yml --s3-bucket $S3_BUCKET --output-template-file packaged-template.yml \
      && aws cloudformation deploy --template-file packaged-template.yml --stack-name $STACK_NAME \
             --parameter-overrides FuncName=$FUNC_NAME SampleEnv1="${SAMPLE_ENV1}" SampleEnv2="${SAMPLE_ENV2}" \
             --capabilities CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND

    # エラー時はスタック作成時のイベントを表示
    err_count=`aws cloudformation describe-stacks --stack-name $STACK_NAME | grep StackStatus | grep ROLLBACK_COMPLETE | wc -l | awk '{print $1}'`
    if [ "$err_count" != "0" ]; then
        aws cloudformation describe-stack-events --stack-name $STACK_NAME
    fi  
}

# 実行
execute(){
    aws lambda invoke --invocation-type RequestResponse --function-name $FUNC_NAME --region ap-northeast-1 --log-type Tail outputfile.txt
    echo "--- result ---"
    cat outputfile.txt
    echo -e "\n--------------"
    rm -rf outputfile.txt
}

# デプロイ or 実行
case $1 in
deploy)
    deploy
    ;;  
execute)
    execute
    ;;  
*)
*)
    echo "Argument Error!!"
    echo -e "\nUsage)"
    echo -e "  ./make.sh (deploy|execute)\n"
    exit 1
esac

デプロイ & 実行

./make.sh deploy && ./make.sh execute

{
    "Description": "Sample Lambda Environments.", 
    "Parameters": [
        {
            "DefaultValue": "", 
            "NoEcho": false, 
            "ParameterKey": "SampleEnv2"
        }, 
        {
            "DefaultValue": "", 
            "NoEcho": false, 
            "ParameterKey": "SampleEnv1"
        }, 
        {
            "DefaultValue": "SampleLambdaEnv", 
            "NoEcho": false, 
            "ParameterKey": "FuncName"
        }
    ]
}
Uploading to 618582a63c2f8....  3243 / 3243.0  (100.00%)
Successfully packaged artifacts and wrote output template to file packaged-template.yml.
Execute the following command to deploy the packaged template
aws cloudformation deploy --template-file /path_to/packaged-template.yml --stack-name 

Waiting for changeset to be created..
Waiting for stack create/update to complete
Successfully created/updated stack - SampleEnvFunctionStack
{
    "LogResult": "U1RBUlQgUmVxdWVzdElkOiBhZ......==", 
    "ExecutedVersion": "$LATEST", 
    "StatusCode": 200
}
--- result ---
"SampleEnv1 is blank!. SampleEnv2 is blank!."
--------------

パラメータを変えてデプロイ & 実行

export SAMPLE_ENV1=ABC
export SAMPLE_ENV2=DEF
./make.sh deploy && ./make.sh execute


{
    "Description": "Sample Lambda Environments.", 
    "Parameters": [
        {
            "DefaultValue": "", 
            "NoEcho": false, 
            "ParameterKey": "SampleEnv2"
        }, 
        {
            "DefaultValue": "", 
            "NoEcho": false, 
            "ParameterKey": "SampleEnv1"
        }, 
        {
            "DefaultValue": "SampleLambdaEnv", 
            "NoEcho": false, 
            "ParameterKey": "FuncName"
        }
    ]
}
Uploading to 618582a63c2f8....  3243 / 3243.0  (100.00%)
Successfully packaged artifacts and wrote output template to file packaged-template.yml.
Execute the following command to deploy the packaged template
aws cloudformation deploy --template-file /path_to/packaged-template.yml --stack-name 

Waiting for changeset to be created..
Waiting for stack create/update to complete
Successfully created/updated stack - SampleEnvFunctionStack
{
    "LogResult": "U1RBUlQgUmVxdWVzdElkOiBhZ......==", 
    "ExecutedVersion": "$LATEST", 
    "StatusCode": 200
}
--- result ---
"SampleEnv1 is ABC. SampleEnv2 is DEF."
--------------

トップ   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS