
この記事では
・EC2を開始するLamdba関数を作成
します!

今回は
・Pythonのコードを作成
します!
前提
Lamdba関数用のIAMロールが作成されていること。
IAMロールの作成の詳細は、以下の記事をご確認ください。
Lamdba関数の作成
ここでは例として
・EC2「i-xxxxxxxxxxxxxxxxx」を開始するLamdba関数を作成
します。
※「i-xxxxxxxxxxxxxxxxx」はEC2のインスタンスIDです。
手順
Lamdba関数のページの「関数の作成」をクリックする。

手順
①「関数名」に任意の名前を入力する。
※今回は例として「test-ec2-start-func」とします。
②「ランタイム」に「Python 3.12」を選択する。

手順
「デフォルトの実行ロールの変更」をクリックし、「既存のロールを使用する」にチェックを入れて、作成済みの「Lamdba関数用のIAMロール」を選択する。
※今回は例として「EC2-start-stop-Role」を選択します。

手順
「関数を作成」をクリックする。

手順
以下のコードを入力して、「Deploy」をクリックする。
※EC2「i-xxxxxxxxxxxxxxxxx」を開始するコードです。
import boto3
region = 'ap-northeast-1'
instances = ['i-xxxxxxxxxxxxxxxxx']
ec2 = boto3.cli
ent('ec2', region_name=region)
def lambda_handler(event, context):
ec2.start_instances(InstanceIds=instances)
print('started your instances: ' + str(instances))

動作確認
「Test」をクリックすることで、Lamdba関数を実行できます。

「Test」をクリックすると、実行結果が表示されます。

EC2のページにて、問題無く対象のEC2が起動したことを確認できます。

ClooudWatch Logsのページにて、問題無くログが出力されたことも確認できます。
