PyCharmで構成されている前の豆を使用して、したがって、内部のあなたのPyCharmに直接書き込むことができたときにスクリプトを記述し、boto3とpyboto3を追加しました。
それがオンにされ、又はそれがオフになっているかのように逆にも書き込むことができ、状態がオンであれば、ここで領域の例は、すべてのEC2に目を通すされ、次いでオフ。
import boto3
def lambda_handler(event, context):
# Get list of regions
ec2_client = boto3.client('ec2')
regions = [region['RegionName']
for region in ec2_client.describe_regions()['Regions']]
# Iterate over each region
for region in regions:
ec2 = boto3.resource('ec2', region_name=region)
print("Region:", region)
# Get only running instances
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name',
'Values': ['running']}])
#Stop the instances
for instance in instances:
instance.stop()
print('Stopped instance: ', instance.id)
# instances = ec2.instances.filter(
# Filters=[{'Name': 'instance-state-name',
# 'Values': ['stopped']}])
#
# for instance in instances:
# instance.start()
# print('Start instance: ', instance.id)
if __name__ == '__main__':
lambda_handler(0,0)
どのような作品の実装
C:\Users\yuan\PycharmProjects\aws\venv\Scripts\python.exe C:/Users/yuan/PycharmProjects/aws/StopInstance.py
Region: eu-north-1
Region: ap-south-1
Region: eu-west-3
Region: eu-west-2
Region: eu-west-1
Region: ap-northeast-2
Region: ap-northeast-1
Region: sa-east-1
Region: ca-central-1
Region: ap-southeast-1
Region: ap-southeast-2
Stopped instance: i-0bb70cc9666ce2af3
Region: eu-central-1
Region: us-east-1
Stopped instance: i-00e9dc7c254dbe497
Region: us-east-2
Region: us-west-1
Region: us-west-2
その後、我々は、ラムダ年のAWSに新しい関数を作成し、私はこの役割が起動する権限を持つことができることを保証する役割の定義とEC2のシャットダウン以来、ここにしてきました
次のようにIAMの権限は以下のとおりです。
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ec2:DescribeInstances",
"ec2:DescribeRegions",
"ec2:StartInstances",
"ec2:StopInstances"
],
"Resource": "*"
}
]
}
コピー機能アップ
次に、そのCloudWatchの中に新しいルールを追加
cronの式の使用、彼の注意は、GMT時間であり、そのためならば、独自のローカル時間の変更を必要と作成ウィザード、選択したスケジュール、
彼の後に書かれた、迅速かつフレンドリーなインターフェイスが存在します
フィニッシュ作成
戻るラムダ・インタフェース、あなたは彼のトリガー1つの以上CloudWatchのイベントを見ることができます
実行されるのを待った後、あなたはログを表示することができます
EC2サービスは、実際にシャットダウンすることを確認することができます。