![](http://aws-guide.work/wp-content/themes/cocoon-master/images/b-woman.png)
この記事では
・EC2を停止するLamdba関数を作成
します!
![](http://aws-guide.work/wp-content/themes/cocoon-master/images/b-woman.png)
今回は
・Pythonのコードを作成
します!
前提
Lamdba関数用のIAMロールが作成されていること。
IAMロールの作成の詳細は、以下の記事をご確認ください。
サンプルコード
Lamdba関数の具体的な作成方法は、以下の記事をご確認ください。
ここでは例として
・EC2「i-xxxxxxxxxxxxxxxxx」を停止するLamdba関数を作成
します。
※「i-xxxxxxxxxxxxxxxxx」はEC2のインスタンスIDです。
import boto3
region = 'ap-northeast-1'
instances = ['i-xxxxxxxxxxxxxxxxx']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.stop_instances(InstanceIds=instances)
print('stopped your instances: ' + str(instances))
実行結果
対象のEC2を停止できました。
![](https://aws-guide.work/wp-content/uploads/2024/02/aws_lamdba_create_ec2_stop_001.png)
![実行結果②](https://aws-guide.work/wp-content/uploads/2024/02/aws_lamdba_create_ec2_stop_002.png)