您好,登錄后才能下訂單哦!
上一篇豆子已經(jīng)配置在PyCharm里面添加了boto3和pyboto3,因此寫腳本的時候可以直接在自己的PyCharm里面編寫。
下面是一個例子遍歷所有的region查找EC2,如果狀態(tài)是開機,那就關(guān)掉;或者倒過來也可以寫成 如果是關(guān)機狀態(tài),就開機。
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)
執(zhí)行一下是工作的
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里創(chuàng)建一個新的函數(shù), 這里我已經(jīng)自定義了一個role了,確保這個role可以對ec2有開機和關(guān)機的權(quán)限
IAM的權(quán)限如下所示:
{
"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": "*"
}
]
}
拷貝函數(shù)上來
接下來 在cloudwatch里面添加一個新的rule
創(chuàng)建向?qū)?,這里選擇schedule,這里使用 cron的表達式,注意他是GMT的時間,因此需要自己和本地時間轉(zhuǎn)換一下
寫好之后他會有個友好的提示界面
完成創(chuàng)建
回到Lambda的界面, 可以看見他的觸發(fā)器多了一個CloudWatch Events
等待執(zhí)行之后,可以查看日志
也可以確認EC2 服務 的確關(guān)機了
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。