あめがえるのITブログ

頑張りすぎない。ほどほどに頑張るブログ。

AWS Lambda関数(Python)をAWS CLIで作成してみた

GUIでぽちぽちやるのはナンセンスだと上司に言われたのでLambda関数作成をコード化してみました(´┐`)ォェー

◆やること

CloudShellからCLIでLambda関数を作成(+ IAM Role,Policy)

◆構成

◆実践!

1.ポリシー作成

# aws iam create-policy --policy-name MyFunction-policy --policy-document \
'{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "logs:CreateLogGroup",
            "Resource": "arn:aws:logs:ap-northeast-1:xxxxxxxxxxx:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": [
                "arn:aws:logs:ap-northeast-1:xxxxxxxxxxx:log-group:/aws/lambda/MyFunction:*"
            ]
        }
    ]
}'
output:
{
    "Policy": {
        "PolicyName": "MyFunction-policy",
        "PolicyId": "ANPA3QANHVTEE67KDQWUZ",
        "Arn": "arn:aws:iam::xxxxxxxxxxx:policy/MyFunction-policy",
        "Path": "/",
        "DefaultVersionId": "v1",
        "AttachmentCount": 0,
        "PermissionsBoundaryUsageCount": 0,
        "IsAttachable": true,
        "CreateDate": "2023-05-04T06:18:14+00:00",
        "UpdateDate": "2023-05-04T06:18:14+00:00"
    }
}

2.ロール作成

# aws iam create-role --role-name MyFunction-Role --assume-role-policy-document \
'{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "lambda.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}'
output:
{
    "Role": {
        "Path": "/",
        "RoleName": "MyFunction-Role",
        "RoleId": "AROA3QANHVTEK3ZXNHXSV",
        "Arn": "arn:aws:iam::xxxxxxxxxxx:role/MyFunction-Role",
        "CreateDate": "2023-05-04T06:48:43+00:00",
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {
                        "Service": "lambda.amazonaws.com"
                    },
                    "Action": "sts:AssumeRole"
                }
            ]
        }
    }
}

3.ロールにポリシーをアタッチ

# aws iam attach-role-policy --role-name MyFunction-Role \
  --policy-arn arn:aws:iam::xxxxxxxxxxx:policy/MyFunction-policy

4.Pythonコード作成

# vi test1.py
import json

def lambda_handler(event, context):
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

# zip test1.zip test1.py
# ls 
※test1.zipが作成されていること

5.Lambda関数作成

# aws lambda create-function --function-name MyFunction \
--zip-file fileb://test1.zip --handler test1.lambda_handler --runtime python3.10 \
--role arn:aws:iam::xxxxxxxxxx:role/MyFunction-Role
output:
{
    "FunctionName": "MyFunction",
    "FunctionArn": "arn:aws:lambda:ap-northeast-1:xxxxxxxxxx:function:MyFunction",
    "Runtime": "python3.10",
    "Role": "arn:aws:iam::xxxxxxxxxx:role/MyFunction-Role",
    "Handler": "test.lambda_handler",
    "CodeSize": 262,
    "Description": "",
    "Timeout": 3,
    "MemorySize": 128,
    "LastModified": "2023-05-04T06aaws lambda delete-function \
        --function-name ${LAMBDA_FUNC_NAME}:50:24.364+0000",
    "CodeSha256": "B4mMJ3hN8aanPe+HVyWwsom83XOaulceRCFECe/0JRI=",
    "Version": "$LATEST",
    "TracingConfig": {
        "Mode": "PassThrough"
    },
    "RevisionId": "13198a02-4295-4092-a1c8-7f9fdc44039d",
    "State": "Pending",
    "StateReason": "The function is being created.",
    "StateReasonCode": "Creating",
    "PackageType": "Zip",
    "Architectures": [
        "x86_64"
    ],
    "EphemeralStorage": {
        "Size": 512
    },
    "SnapStart": {
        "ApplyOn": "None",
        "OptimizationStatus": "Off"
    },
    "RuntimeVersionConfig": {
        "RuntimeVersionArn": "arn:aws:lambda:ap-northeast-1::runtime:7764dc7f3ff1fc45718f596be4cd03d7bca223f0586f3bfa5fe6584d6af81cd8"
    }
}

★備考 ハンドラーの指定は、[ファイル名※拡張子なし].[関数名]の模様
※下記のように階層が変わってもハンドラーの指定方法は変わらない。

◆後処理

# aws lambda delete-function --function-name MyFunction
※正常に削除された場合、outputはなし。

◆感想

ハンドラーの指定方法が少し癖がありましたがなんとかできた!
コードをZip化するのが面倒なのでこれもCLI化できないかな。