简体   繁体   中英

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

I have installed python 3.6.4 version on my windows 8.1 64-bit machine. what all steps required to install and configure boto3 and boto libraries. I was trying to fetch all the AWS EC2 instances of particular region and stoping them, but not able to execute the task.

Do anybody have solution to accomplished the requirement.

Add Credentials to environment variables: Doc to configure credentials

Set region for your boto3 client: 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
)
#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)

Above code can be executed with 2 parameters, 1st is the Tag Key of all the instances and 2nd is the Tag Value. it will fetch all the running instaces which are taged with the given value and start them one by one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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