繁体   English   中英

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

[英]How to start all the ec2 instances using python by configuring boto3 libraries in windows?

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

是否有人有解决方案来满足要求。

将凭证添加到环境变量: 用于配置凭证的文档

为您的boto3客户端设置区域设置区域教程

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
)
#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 Value。 它将获取所有使用给定值标记的运行实例,并逐一启动它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM