如何通过在Windows中配置boto3库来使用python启动所有ec2实例?

问题描述 投票:0回答:2

我已经在我的Windows 8.1 64位机器上安装了python 3.6.4版本。安装和配置boto3和boto库所需的所有步骤。我试图获取特定区域的所有AWS EC2实例并停止它们,但无法执行任务。

有没有人有解决方案来完成这个要求。

python-3.x amazon-ec2 boto boto3 botocore
2个回答
2
投票

将凭据添加到环境变量:Doc to configure credentials

为您的boto3客户端设置区域:Tutorial to Set region

import boto3

client = boto3.client('ec2',region_name='us-west-2') #Add your region

print('Loading function')

def lambda_handler(event, context):
    responses = client.start_instances(
    InstanceIds=[
        'YOUR INSTANCE IDs'
    ],

    DryRun=True # Make it False to test
)

1
投票
#Basic import boto3 libraries
import boto3
import sys

#provided Access Credentialsaccess_key
access_key = ""
secret_key = ""

count=0
#Establish a connection to EC2 resource using credentials and region_name
conn = boto3.resource('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key,region_name='us-west-1')
print("Argument length: ",len(sys.argv))

if len(sys.argv)>2:
    Keyname = sys.argv[1]
    value = sys.argv[2]
    instances = conn.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped'],'Name': 'tag:'+Keyname,'Values': [value]}])
    print("Arguments passed\nKey: "+Keyname+"\nValue: "+value)
else:
    instances = conn.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])

for instance in instances:
    #instance.start(instance.id)
    count+=1
    print(instance.id,",",instance.state["Name"])

print("Total number of EC2 instances are stopped on cloud: ",count)

上面的代码可以用2个参数执行,第一个是所有实例的Tag Key,第二个是Tag值。它将获取所有使用给定值进行taging的运行实例并逐个启动它们。

© www.soinside.com 2019 - 2024. All rights reserved.