![](/img/trans.png)
[英]How to start or stop an Amazon EC2 instance from Google App Engine (python)
[英]How to Stop EC2 Instance from the list
我有下面的代碼,它在本地運行良好,可以停止 EC2 實例,但是當我試圖移動它的生產時,它只停止第一個實例而不是第二個/第 n 個實例
import boto3
import json
access_key = "AKIAJSVXXXXXXXXXX"
secret_key = "mSvhX5q7uw8dTZ543qtC6OXXXXXXXXXXXX"
client = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name='us-east-1')
file1 = open("Myfile.txt", "r").read().split("\n")
print(file1)
ec2_result = client.describe_instances(
Filters=[
{
'Name': 'tag:Name',
'Values': file1
}
]
)
ids = [ec2_result['Reservations'][0]['Instances'][i]['InstanceId'] for i in
range(len(ec2_result['Reservations'][0]['Instances']))]
print(ids)
response = client.stop_instances(
InstanceIds=ids
)
print("stooped now")
我的文件.txt
instanceonename
instance2name
它在我的本地系統中運行良好,但在生產中,它只停止第一個 EC2 實例而不是第二個
它只停止一個實例,因為您的列表理解只迭代一個實例。 你需要雙倍:
ids = [instance['InstanceId'] \
for reservation in ec2_result['Reservations'] \
for instance in reservation['Instances']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.