[英]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實例並停止它們,但無法執行任務。
是否有人有解決方案來滿足要求。
將憑證添加到環境變量: 用於配置憑證的文檔
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.