ハンズオン(簡易版): Lambda基礎 Boto3 (Python SDK)

2.1.8. Python関数コードファイルの作成 (handson-cli-lambda-boto3-ec2-authorize-function)

手順の目的 [why]

Lambda関数"handson-cli-lambda-boto3-ec2-authorize-function"のソースコードファイルを作成します。

設定値の指定

設定値の指定

手順に必要な設定値を変数に格納をします。

1. Python関数名

Python関数名を指定します。

変数の設定:

PYTHON_FUNCTION_NAME='lambda_handler'

2. Lambda関数コードファイル用ディレクトリ

Lambda関数コードファイル用ディレクトリを指定します。

変数の設定:

DIR_LAMBDA_FUNCTION_CODE="${HOME}/environment/conf-handson-cli-lambda"

ディレクトリが存在することを確認します。

コマンド:

ls -d ${DIR_LAMBDA_FUNCTION_CODE}

結果(例:存在する場合):

${HOME}/environment/conf-handson-cli-lambda

存在しない場合は作成します。

コマンド:

mkdir -p ${DIR_LAMBDA_FUNCTION_CODE}

結果(例):

(出力なし)

3. Lambda関数コードファイル名

Lambda関数コードファイル名を指定します。

変数の設定:

LAMBDA_FUNCTION_CODE_NAME='handson-cli-lambda-boto3-ec2-authorize-function.py'

変数の設定:

FILE_LAMBDA_FUNCTION_CODE="${DIR_LAMBDA_FUNCTION_CODE}/${LAMBDA_FUNCTION_CODE_NAME}" \
  && echo ${FILE_LAMBDA_FUNCTION_CODE}

結果(例):

${HOME}/environment/conf-handson-cli-lambda/handson-cli-lambda-boto3-ec2-authorize-function.py

4. Lambda関数コードZIPファイル用ディレクトリ

Lambda関数コードZIPファイル用ディレクトリを指定します。

変数の設定:

DIR_LAMBDA_FUNCTION_ZIP="${HOME}/environment/artifact-handson-cli-lambda"

ディレクトリが存在することを確認します。

コマンド:

ls -d ${DIR_LAMBDA_FUNCTION_ZIP}

結果(例:存在する場合):

${HOME}/environment/artifact-handson-cli-lambda

存在しない場合は作成します。

コマンド:

mkdir -p ${DIR_LAMBDA_FUNCTION_ZIP}

結果(例):

(出力なし)

5. Lambda関数コードZIPファイル

Lambda関数名を指定します。

変数の設定:

LAMBDA_FUNCTION_NAME='handson-cli-lambda-boto3-ec2-authorize-function'

Lambda関数コードZIPファイルを指定します。

変数の設定:

FILE_LAMBDA_FUNCTION_ZIP="${DIR_LAMBDA_FUNCTION_ZIP}/${LAMBDA_FUNCTION_NAME}.zip" \
  && echo ${FILE_LAMBDA_FUNCTION_ZIP}

結果(例):

${HOME}/environment/artifact-handson-cli-lambda/handson-cli-lambda-boto3-ec2-authorize-function.zip

設定値の確認

各変数に正しい設定値が格納されていることを確認しながら保存します。

変数の確認:

cat << END

  # 1. PYTHON_FUNCTION_NAME:"lambda_handler"
       PYTHON_FUNCTION_NAME="${PYTHON_FUNCTION_NAME}"
  # 2. DIR_LAMBDA_FUNCTION_CODE:"${HOME}/environment/conf-handson-cli-lambda"
       DIR_LAMBDA_FUNCTION_CODE="${DIR_LAMBDA_FUNCTION_CODE}"
  # 3. FILE_LAMBDA_FUNCTION_CODE:"${HOME}/environment/conf-handson-cli-lambda/handson-cli-lambda-boto3-ec2-authorize-function.py"
       FILE_LAMBDA_FUNCTION_CODE="${FILE_LAMBDA_FUNCTION_CODE}"
  # 4. DIR_LAMBDA_FUNCTION_ZIP:"${HOME}/environment/artifact-handson-cli-lambda"
       DIR_LAMBDA_FUNCTION_ZIP="${DIR_LAMBDA_FUNCTION_ZIP}"
  # 5. FILE_LAMBDA_FUNCTION_ZIP:"${HOME}/environment/artifact-handson-cli-lambda/handson-cli-lambda-boto3-ec2-authorize-function.zip"
       FILE_LAMBDA_FUNCTION_ZIP="${FILE_LAMBDA_FUNCTION_ZIP}"

END

下段の変数が入っていない、もしくは上段と同等の値が入っていない場合は、それぞれの手順番号に戻って変数の設定を行います。

処理の実行

関数コードファイルの作成します。

変数の確認:

cat << END

  # FILE_LAMBDA_FUNCTION_CODE:"${HOME}/environment/conf-handson-cli-lambda/handson-cli-lambda-boto3-ec2-authorize-function.py"
    FILE_LAMBDA_FUNCTION_CODE="${FILE_LAMBDA_FUNCTION_CODE}"

END

コマンド:

cat << EOF > ${FILE_LAMBDA_FUNCTION_CODE}
import os
import boto3
from botocore.exceptions import ClientError

def lambda_handler(event, context):

    # environments
    region = os.environ.get('REGION')
    security_group_id = os.environ.get('SECURITY_GROUP_ID')

    # payload
    cidr_ip = event['cidr_ip']
    to_port = int(event['to_port'])
    ip_protocol = event['ip_protocol']

    print('## Payload')
    print('to_port: ' + str(to_port))
    print('cidr_ip: ' + cidr_ip)
    print('ip_protocol: ' + ip_protocol)

    ec2 = boto3.client('ec2', region_name=region)
    try:
        print('## Create Rule')
        response = ec2.authorize_security_group_ingress(
            GroupId = security_group_id,
            IpPermissions = [
                {
                    'FromPort': to_port,
                    'IpProtocol': ip_protocol,
                    'IpRanges': [
                        {
                            'CidrIp': cidr_ip,
                        },
                    ],
                    'ToPort': to_port,
                },
            ],
        )

    except ClientError as e:
        print(e)

    print('#remaining time')
    print(context.get_remaining_time_in_millis())
EOF

cat ${FILE_LAMBDA_FUNCTION_CODE}

結果(例):

import os
import boto3
from botocore.exceptions import ClientError

def lambda_handler(event, context):

    # environments
    region = os.environ.get('REGION')
    security_group_id = os.environ.get('SECURITY_GROUP_ID')

    # payload
    cidr_ip = event['cidr_ip']
    to_port = int(event['to_port'])
    ip_protocol = event['ip_protocol']

    print('## Payload')
    print('to_port: ' + str(to_port))
    print('cidr_ip: ' + cidr_ip)
    print('ip_protocol: ' + ip_protocol)

    ec2 = boto3.client('ec2', region_name=region)
    try:
        print('## Create Rule')
        response = ec2.authorize_security_group_ingress(
            GroupId = security_group_id,
            IpPermissions = [
                {
                    'FromPort': to_port,
                    'IpProtocol': ip_protocol,
                    'IpRanges': [
                        {
                            'CidrIp': cidr_ip,
                        },
                    ],
                    'ToPort': to_port,
                },
            ],
        )

    except ClientError as e:
        print(e)

    print('#remaining time')
    print(context.get_remaining_time_in_millis())

ZIPファイルを作成します。

コマンド:

zip -j -X ${FILE_LAMBDA_FUNCTION_ZIP} ${FILE_LAMBDA_FUNCTION_CODE}

結果(例):

adding: handson-cli-lambda-boto3-ec2-authorize-function.py (deflated 14%)

完了確認

「Lambda関数コードZIPファイル"${HOME}/environment/artifact-handson-cli-lambda/handson-cli-lambda-boto3-ec2-authorize-function.zip"が存在する。」ことを確認します。

コマンド:

ls ${FILE_LAMBDA_FUNCTION_ZIP}

結果(例):

${HOME}/environment/artifact-handson-cli-lambda/handson-cli-lambda-boto3-ec2-authorize-function.zip

手順の完了