【问题标题】:How to start all the ec2 instances using python by configuring boto3 libraries in windows?如何通过在windows中配置boto3库来使用python启动所有ec2实例?
【发布时间】:2018-07-14 00:34:38
【问题描述】:

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

是否有人有解决方案来完成要求。

【问题讨论】:

    标签: python-3.x amazon-ec2 boto boto3 botocore


    【解决方案1】:

    将凭据添加到环境变量: 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
    )
    

    【讨论】:

    • 嘿 Parashar,非常感谢您提供的解决方案。我以不同的方式完成了我的任务,非常感谢您的解决方案。请看看我的出路,希望它可以帮助别人。
    【解决方案2】:
    #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。 它将获取所有正在运行的带有给定值标记的实例,并一一启动它们。

    【讨论】:

    • 赞成,因为您的回答解决了目的。虽然我给出的答案是使用 api 管理 ec2 的通用方法。此外,对于您的解决方案,1 个建议是:由于通常在不添加标签的情况下创建实例,因此请尝试先添加相关标签(使用相同的代码而不是手动),然后停止实例。流程将是.. 添加标签,如果尚未添加到实例 > 立即获取具有该标签的所有实例 ID > 停止它们。但是,它对 Elastic Beanstalk 实例没有帮助。另外,您可以查看标签:boto3.readthedocs.io/en/latest/reference/services/ec2.html#tag
    • 嘿 Parashar,您的建议非常感谢。我想让您知道,我们已经为所有实例配置了标签及其值。但是,正如您所说,流程应该是您所说的方式。非常感谢您对此问题陈述的澄清。
    猜你喜欢
    • 2019-02-25
    • 1970-01-01
    • 2017-05-21
    • 2018-04-07
    • 2020-01-02
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 2020-09-30
    相关资源
    最近更新 更多