您好,登錄后才能下訂單哦!
上一篇豆子已經配置在PyCharm里面添加了boto3和pyboto3,因此寫腳本的時候可以直接在自己的PyCharm里面編寫。
下面是一個例子遍歷所有的region查找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的Lambda里創建一個新的函數, 這里我已經自定義了一個role了,確保這個role可以對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里面添加一個新的rule
創建向導,這里選擇schedule,這里使用 cron的表達式,注意他是GMT的時間,因此需要自己和本地時間轉換一下
寫好之后他會有個友好的提示界面
完成創建
回到Lambda的界面, 可以看見他的觸發器多了一個CloudWatch Events
等待執行之后,可以查看日志
也可以確認EC2 服務 的確關機了
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。