Python批量开关EC2脚本
使用Python和boto3库实现EC2实例的批量开关操作。通过AWS CLI配置和boto3库,解决手动管理多个EC2实例的效率问题。
前提条件:
- 需要本机配置AWS CLI的AK/SK;
- 本机安装Python3;
- 本机安装boto3库(执行pip3 install boto3)。
Python脚本如下:
import boto3.ec2
client = boto3.client('ec2')
ec2action = boto3.resource('ec2')
response = client.describe_instance_status(
IncludeAllInstances=True
)
for i in response['InstanceStatuses']:
instance = ec2action.Instance(i['InstanceId'])
response1 = instance.stop(
#DryRun=True,
Force=True
)
print("instance: ", i['InstanceId'], "is being stopped." )
print(response1)
以上为关机脚本。如果需要批量开机,替换stop为start即可。
最后修改于 2021-06-24