python2.7のLambdaEC2自動起動スクリプトをpython3.7化してみた

https://dev.classmethod.jp/cloud/aws/simple-auto-start-stop-for-ec2/
上記のサイトを丸写ししてEC2の自動起動をしていたんだけれども、python2.7のサポート終了が近付いてきているので、Lambda関数をpython3.7化してみた。

最初にLambdaをそのまま3.7に切替えてみたんですが動作しない。
CloudWatchのログを見てみるとエラー出てるじゃないですか。
※先にログ見ろよな

[ERROR] Runtime.UserCodeSyntaxError: Syntax error in module 'lambda_function': invalid syntax (lambda_function.py, line 10)
Traceback (most recent call last):
  File "/var/task/lambda_function.py" Line 10
            print 'started your instances: ' + ", ".join(instances)


そりゃそうですよねぇ。そのままで動くと思ったらprint文で引っかかるんですね。
ひとまずエラーの内容を元に以下の通り書き替えました。

import boto3

def lambda_handler(event, context):
    region = event['Region']
    operate = event['Action'] 
    instances = event['Instances']

    ec2 = boto3.client('ec2', region_name=region)
    if  operate == 'start':
        ec2.start_instances(InstanceIds=instances)
        msg = 'started your instances: ' + ", ".join(instances)
        print(msg)
    elif operate == 'stop':
        ec2.stop_instances(InstanceIds=instances)
        msg = 'stopped your instances: ' + ", ".join(instances)
        print(msg)

まさかprintで引っかかるなんて思わなかった。
これで使っているLambda関数の中から2系は消滅したのでしばらくは安全ですね。
以上、小ネタでした。ちなみにshutdownはcronで動かしています。

コメント

このブログの人気の投稿

証券外務員1種勉強(計算式暗記用メモ)

GASでGoogleDriveのサブフォルダとファイル一覧を出力する

マクロ経済学(IS-LM分析)