AWS Lambda Python で AWS CLI を実行する方法

9月 30, 2020AWS,AWS CLI,Lambda,Programming,Python

AWS LambdaでPython言語を使用できるようになり、AWS Lambdaを使用したアプリケーション開発、システム構築は更に幅を広げました。

AWS Lambda Python、API Gatewayを使用すればサーバーレス(サーバの完全マネージド)なシステム構築が実現可能です。

しかし、一方でAWS Lambdaはまだ早熟な部分もありAWS Lambda関数が実行されるサーバではインストールされていないライブラリも多く、現時点でAWS CLIも実行できない状態です。

そこで今回は現状のAWS Lambda Pythonの環境でAWS CLIを実行する方法を備忘録として記載しておきたいと思います。

AWS Lambda Python で AWS CLI を実行する方法

AWS CLIを実行するAWS Lambda Python用のディレクトリの作成と必要モジュールのローカルインストール

[mag4j@localhost ~]$ mkdir aws_cli
[mag4j@localhost aws_cli]$ cd aws_cli
[mag4j@localhost aws_cli]$ pip install awscli -t ./
[mag4j@localhost aws_cli]$ pip install simplejson -t ./
[mag4j@localhost aws_cli]$ pip install argparse -t ./

awsコマンドスクリプトの作成と動作確認

[mag4j@localhost aws_cli]$ vim aws
#!/usr/bin/python
# Copyright 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.

# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at

#     https://aws.amazon.com/apache2.0/

# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import sys
import os

if os.environ.get('LC_CTYPE', '') == 'UTF-8':
    os.environ['LC_CTYPE'] = 'en_US.UTF-8'
import awscli.clidriver


def main():
    return awscli.clidriver.main()


if __name__ == '__main__':
    sys.exit(main())
[mag4j@localhost aws_cli]$ ./aws --version
aws-cli/1.9.5 Python/2.6.6 Linux/2.6.32-573.7.1.el6.i686 botocore/1.3.5

AWS Lambda Pythonの実行スクリプト作成

今回はテスト用に「print(_(“./aws s3 ls"))」を実行しています。

[mag4j@localhost aws_cli]$ vim lambda_function.py
import commands
import json
import os
from cStringIO import StringIO
import re

print('Loading function')

def _(cmd):
    return commands.getoutput(cmd) 
    
def lambda_handler(event, context):
    print(_("./aws s3 ls"))

ファイルへの実行権限付与とZIPファイルの作成

[mag4j@localhost aws_cli]$ chmod 755 -R *
[mag4j@localhost aws_cli]$ zip -r aws_cli.zip *

AWS Lambda Pythonで実行

zipファイルを作成した後はAWS Lambda Pythonで実行するのみです。
AWS Lambda Pythonで実行する際にはRoleに付与されているポリシーにAWS CLIで実行するコマンドに関する権限が付与されていることが必要です。

Reference: Tech Blog citing related sources