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

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

手順の目的 [why]

Lambda関数"handson-cli-lambda-boto3-ec2-revoke-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-revoke-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-revoke-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-revoke-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-revoke-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-revoke-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-revoke-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-revoke-function.py"
    FILE_LAMBDA_FUNCTION_CODE="${FILE_LAMBDA_FUNCTION_CODE}"

END

コマンド:

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

def lambda_handler(event, context):

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

    ec2 = boto3.client('ec2', region_name=region)
    try:
        security_group = ec2.describe_security_groups(
            GroupIds=[security_group_id],
            Filters=[
                {
                    'Name': 'vpc-id',
                    'Values': [
                        vpc_id,
                    ]
                },
            ]
        )
        for rule in security_group['SecurityGroups'][0]['IpPermissions']:
            cidr_ip = rule['IpRanges'][0]['CidrIp']
            to_port = rule['ToPort']
            ip_protocol = rule['IpProtocol']
            print('## Delete Rule')
            print(rule)
            response = ec2.revoke_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 json
import boto3
from botocore.exceptions import ClientError

def lambda_handler(event, context):

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

    ec2 = boto3.client('ec2', region_name=region)
    try:
        security_group = ec2.describe_security_groups(
            GroupIds=[security_group_id],
            Filters=[
                {
                    'Name': 'vpc-id',
                    'Values': [
                        vpc_id,
                    ]
                },
            ]
        )
        for rule in security_group['SecurityGroups'][0]['IpPermissions']:
            cidr_ip = rule['IpRanges'][0]['CidrIp']
            to_port = rule['ToPort']
            ip_protocol = rule['IpProtocol']
            print('## Delete Rule')
            print(rule)
            response = ec2.revoke_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-revoke-function.py (deflated 14%)

完了確認

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

コマンド:

ls ${FILE_LAMBDA_FUNCTION_ZIP}

結果(例):

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

手順の完了