上一篇豆子已經(jīng)配置在PyCharm里面添加了boto3和pyboto3,因此寫(xiě)腳本的時(shí)候可以直接在自己的PyCharm里面編寫(xiě)。
下面是一個(gè)例子遍歷所有的region查找EC2,如果狀態(tài)是開(kāi)機(jī),那就關(guān)掉;或者倒過(guò)來(lái)也可以寫(xiě)成 如果是關(guān)機(jī)狀態(tài),就開(kāi)機(jī)。
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
然后我們?cè)赼ws的Lambda里創(chuàng)建一個(gè)新的函數(shù), 這里我已經(jīng)自定義了一個(gè)role了,確保這個(gè)role可以對(duì)ec2有開(kāi)機(jī)和關(guān)機(jī)的權(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ù)上來(lái)
接下來(lái) 在cloudwatch里面添加一個(gè)新的rule
創(chuàng)建向?qū)?,這里選擇schedule,這里使用 cron的表達(dá)式,注意他是GMT的時(shí)間,因此需要自己和本地時(shí)間轉(zhuǎn)換一下
寫(xiě)好之后他會(huì)有個(gè)友好的提示界面
完成創(chuàng)建
回到Lambda的界面, 可以看見(jiàn)他的觸發(fā)器多了一個(gè)CloudWatch Events
等待執(zhí)行之后,可以查看日志
也可以確認(rèn)EC2 服務(wù) 的確關(guān)機(jī)了
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
