Python Script to return all instances in all regions

legolasthehansy
legolasthehansy used Ask the Experts™
on
I'm trying to get all running instances in all regions to shut them down off hours and this is the script I use. However, I get a Syntax error: return outside function. It maybe a indentation problem which I'm not able find out. Can you help?

import boto3
import logging

client = boto3.client('ec2')

instances = []
for region in client.describe_regions()['Regions']:
    ec2 = boto3.resource('ec2', region_name=region['RegionName'])
    result = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
for instance in result:
    instances.append(instance.id)
return instances

print instances

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
ZhaawZSoftware Developer

Commented:
Remove line 12 ("return instances")

Author

Commented:
Thanks for your response. But how do I see the output or see the results of running instances?
Software Developer
Commented:
I haven't used AWS, Amazon EC2 or boto3, so I can only guess what "instance" means in this case.
1) You should remove "return instances", because keyword "return" may be used only in functions to return function's result. In your case, you don't have any function there, therefore you got syntax error. After removing that line, you should get some output (assuming that there are no other errors).
2) I believe you should indent lines 10 and 11, otherwise the second loop (for instance in result) is executed only for last value of "result" variable. If the first loop is not run at all, you will probably get "name 'result' is not defined" exception.
3) line 14 ("print instances") should print to stdout(?) contents of "instances" list. I have no idea how you run the script. If run it from the console, you should see the output in the console.

Author

Commented:
That was it. The second for loop did not have a indentation as expected and didn't give me an output I was expecting. Cheers!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial