Friday, February 4, 2022

[SOLVED] How to Stop EC2 Instance from the list

Issue

I have the below code it is working very well in local for stopping EC2 Instance but while I am trying to move its production it is stopping only the first instance not the second one/nth one

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")

Myfile.txt

instanceonename
instance2name

It is working very well in my local system but in production, it is stopping only the first EC2 instance not second one


Solution

It stops only one instance, because your list comprehension iterates only over one instance. You need double for:

ids = [instance['InstanceId'] \
         for reservation in ec2_result['Reservations'] \
         for instance in reservation['Instances']]


Answered By - Marcin
Answer Checked By - Clifford M. (WPSolving Volunteer)