maxbeeeee
maxbeeeee

Reputation: 21

AWS Boto3 Error of Malformed InstanceID when using for loop

Hi I am experiencing an error when using a for loop for inputting instance id. Below is my code along with the error.

The code is just putting all instance ids in a file which I use to in a for loop to get a describe-instances output.

The format seems fine and when I manually input the instance id it works just fine. Let me know

#!/usr/bin/python3
import boto3
import csv

ec2_re = boto3.resource('ec2')
ids= [instance.id for instance in ec2_re.instances.all()]
with open('ids.txt', 'w') as file_handler:
    for id in ids:
        file_handler.write("'{}'\n".format(id))

ec2 = boto3.client('ec2', region_name='us-east-1')
INSTANCE_ID = open("ids.txt", "r")  #need to loop thru this
for x in INSTANCE_ID:
    result = []
    response = ec2.describe_instances(
        InstanceIds=[
            x
        ]).get('Reservations')

Error

Traceback (most recent call last):
  File "./excel_new.py", line 17, in <module>
    x
  File "/usr/local/lib/python3.7/site-packages/botocore/client.py", line 514, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/usr/local/lib/python3.7/site-packages/botocore/client.py", line 934, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (InvalidInstanceID.Malformed) when calling the DescribeInstances operation: Invalid id: "'i-03b6908c79e0dd9dd'

Upvotes: 1

Views: 939

Answers (1)

jarmod
jarmod

Reputation: 78573

Write your instance IDs without extraneous quotes. For example:

file_handler.write("{}\n".format(id))

There is a secondary issue in how you are reading the text file later. You need to strip newlines from the lines of text containing the instance IDs. For example:

with open("ids.txt", "r") as fp:
    for id in [line.rstrip() for line in fp.readlines()]:
        print(id)

Here's a fuller example that both writes and then reads instance IDs:

ids = ["id-12345", "id-23456", "id-34567"]

with open("ids.txt", "w") as fp:
    for id in ids:
        fp.write(f"{id}\n")

with open("ids.txt", "r") as fp:
    for id in [line.rstrip() for line in fp.readlines()]:
        print(id)

Because file objects in Python are iterators, you could also use:

for id in [line.rstrip() for line in open("ids.txt", "r")]:
    print(id)

Upvotes: 1

Related Questions