上一篇豆子已经配置在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。